Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb_zstd Namespace Reference

Classes

struct  ZSTD_bounds
struct  ZSTD_inBuffer_s
struct  ZSTD_outBuffer_s
struct  ZSTD_Sequence
struct  ZSTD_compressionParameters
struct  ZSTD_frameParameters
struct  ZSTD_parameters
struct  ZSTD_frameHeader
struct  ZSTD_customMem
struct  ZSTD_frameProgression
struct  BIT_CStream_t
struct  BIT_DStream_t
struct  FSE_CState_t
struct  FSE_DState_t
struct  FSE_symbolCompressionTransform
struct  FSE_DTableHeader
struct  FSE_decode_t
struct  HUF_CTableHeader
struct  FSE_DecompressWksp
struct  POOL_job_s
struct  POOL_ctx_s
struct  XXH32_canonical_t
struct  XXH64_canonical_t
struct  XXH32_state_s
struct  XXH64_state_s
struct  ZSTD_cpuid_t
struct  seqDef_s
struct  seqStore_t
struct  ZSTD_sequenceLength
struct  ZSTD_frameSizeInfo
struct  blockProperties_t
struct  nodeElt_s
struct  HUF_CompressWeightsWksp
struct  HUF_WriteCTableWksp
struct  rankPos
struct  HUF_buildCTable_wksp_tables
struct  HUF_CStream_t
struct  HUF_compress_tables_t
struct  ZSTD_cwksp
struct  ZSTD_prefixDict_s
struct  ZSTD_localDict
struct  ZSTD_hufCTables_t
struct  ZSTD_fseCTables_t
struct  ZSTD_entropyCTables_t
struct  ZSTD_match_t
struct  rawSeq
struct  rawSeqStore_t
struct  ZSTD_sequencePosition
struct  ZSTD_optimal_t
struct  optState_t
struct  ZSTD_compressedBlockState_t
struct  ZSTD_window_t
struct  ZSTD_matchState_t
struct  ZSTD_blockState_t
struct  ldmEntry_t
struct  ldmMatchCandidate_t
struct  ldmState_t
struct  ldmParams_t
struct  SeqCollector
struct  ZSTD_CCtx_params_s
struct  ZSTD_blockSplitCtx
struct  ZSTD_CCtx_s
struct  repcodes_s
struct  ZSTD_CDict_s
struct  ZSTD_symbolEncodingTypeStats_t
struct  seqStoreSplits
struct  ZSTD_BuildCTableWksp
struct  EstimatedBlockSize
struct  ldmRollingHashState_t
struct  ZSTD_optLdm_t
struct  buffer_s
struct  ZSTDMT_bufferPool_s
struct  ZSTDMT_CCtxPool
struct  range_t
struct  serialState_t
struct  ZSTDMT_jobDescription
struct  inBuff_t
struct  roundBuff_t
struct  rsyncState_t
struct  ZSTDMT_CCtx_s
struct  syncPoint_t
struct  DTableDesc
struct  HUF_DecompressFastArgs
struct  HUF_DEltX1
struct  HUF_ReadDTableX1_Workspace
struct  HUF_DEltX2
struct  sortedSymbol_t
struct  HUF_ReadDTableX2_Workspace
struct  algo_time_t
struct  ZSTD_seqSymbol_header
struct  ZSTD_seqSymbol
struct  ZSTD_entropyDTables_t
struct  ZSTD_DDictHashSet
struct  ZSTD_DCtx_s
struct  ZSTD_DDict_s
struct  seq_t
struct  ZSTD_fseState
struct  seqState_t
struct  ZSTD_OffsetInfo
struct  ZDICT_params_t
struct  ZDICT_cover_params_t
struct  ZDICT_fastCover_params_t
struct  ZDICT_legacy_params_t
struct  COVER_best_s
struct  COVER_segment_t
struct  COVER_epoch_info_t
struct  COVER_dictSelection
struct  COVER_map_pair_t_s
struct  COVER_map_s
struct  COVER_ctx_t
struct  COVER_tryParameters_data_s
struct  _trbudget_t
struct  FASTCOVER_accel_t
struct  FASTCOVER_ctx_t
struct  FASTCOVER_tryParameters_data_s
struct  dictItem
struct  EStats_ress_t
struct  offsetCount_t

Typedefs

typedef struct ZSTD_CCtx_s ZSTD_CCtx
typedef struct ZSTD_DCtx_s ZSTD_DCtx
typedef struct duckdb_zstd::ZSTD_inBuffer_s ZSTD_inBuffer
typedef struct duckdb_zstd::ZSTD_outBuffer_s ZSTD_outBuffer
typedef ZSTD_CCtx ZSTD_CStream
typedef ZSTD_DCtx ZSTD_DStream
typedef struct ZSTD_CDict_s ZSTD_CDict
typedef struct ZSTD_DDict_s ZSTD_DDict
typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params
typedef void *(* ZSTD_allocFunction) (void *opaque, size_t size)
typedef void(* ZSTD_freeFunction) (void *opaque, void *address)
typedef struct POOL_ctx_s ZSTD_threadPool
typedef size_t(* ZSTD_sequenceProducer_F) (void *sequenceProducerState, ZSTD_Sequence *outSeqs, size_t outSeqsCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, int compressionLevel, size_t windowSize)
typedef ZSTD_ErrorCode ERR_enum
typedef unsigned FSE_CTable
typedef unsigned FSE_DTable
typedef size_t BitContainerType
typedef size_t HUF_CElt
typedef U32 HUF_DTable
typedef struct POOL_ctx_s POOL_ctx
typedef void(* POOL_function) (void *)
typedef struct duckdb_zstd::POOL_job_s POOL_job
typedef unsigned int XXH32_hash_t
typedef unsigned long long XXH64_hash_t
typedef struct XXH32_state_s XXH32_state_t
typedef struct XXH64_state_s XXH64_state_t
typedef struct duckdb_zstd::seqDef_s seqDef
typedef struct duckdb_zstd::nodeElt_s nodeElt
typedef nodeElt huffNodeTable[2 *(HUF_SYMBOLVALUE_MAX+1)]
typedef struct ZSTDMT_CCtx_s ZSTDMT_CCtx
typedef struct duckdb_zstd::ZSTD_prefixDict_s ZSTD_prefixDict
typedef struct ZSTD_matchState_t ZSTD_matchState_t
typedef size_t(* ZSTD_blockCompressor) (ZSTD_matchState_t *bs, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
typedef struct duckdb_zstd::repcodes_s repcodes_t
typedef size_t(* ZSTD_sequenceCopier) (ZSTD_CCtx *cctx, ZSTD_sequencePosition *seqPos, const ZSTD_Sequence *const inSeqs, size_t inSeqsSize, const void *src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch)
typedef U64 ZSTD_VecMask
typedef U32(* ZSTD_getAllMatchesFn) (ZSTD_match_t *, ZSTD_matchState_t *, U32 *, const BYTE *, const BYTE *, const U32 rep[ZSTD_REP_NUM], U32 const ll0, U32 const lengthToBeat)
typedef struct duckdb_zstd::buffer_s buffer_t
typedef struct duckdb_zstd::ZSTDMT_bufferPool_s ZSTDMT_bufferPool
typedef ZSTDMT_bufferPool ZSTDMT_seqPool
typedef size_t(* HUF_DecompressUsingDTableFn) (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable)
typedef void(* HUF_DecompressFastLoopFn) (HUF_DecompressFastArgs *)
typedef U32 rankValCol_t[HUF_TABLELOG_MAX+1]
typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX]
typedef size_t(* ZSTD_decompressSequences_t) (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
typedef ZSTD_CStream ZBUFF_CCtx
typedef ZSTD_DStream ZBUFF_DCtx
typedef struct duckdb_zstd::COVER_best_s COVER_best_t
typedef struct duckdb_zstd::COVER_dictSelection COVER_dictSelection_t
typedef struct duckdb_zstd::COVER_map_pair_t_s COVER_map_pair_t
typedef struct duckdb_zstd::COVER_map_s COVER_map_t
typedef struct duckdb_zstd::COVER_tryParameters_data_s COVER_tryParameters_data_t
typedef struct _trbudget_t trbudget_t
typedef struct duckdb_zstd::FASTCOVER_tryParameters_data_s FASTCOVER_tryParameters_data_t

Enumerations

enum  ZSTD_strategy {
  ZSTD_fast =1 , ZSTD_dfast =2 , ZSTD_greedy =3 , ZSTD_lazy =4 ,
  ZSTD_lazy2 =5 , ZSTD_btlazy2 =6 , ZSTD_btopt =7 , ZSTD_btultra =8 ,
  ZSTD_btultra2 =9
}
enum  ZSTD_cParameter {
  ZSTD_c_compressionLevel =100 , ZSTD_c_windowLog =101 , ZSTD_c_hashLog =102 , ZSTD_c_chainLog =103 ,
  ZSTD_c_searchLog =104 , ZSTD_c_minMatch =105 , ZSTD_c_targetLength =106 , ZSTD_c_strategy =107 ,
  ZSTD_c_targetCBlockSize =130 , ZSTD_c_enableLongDistanceMatching =160 , ZSTD_c_ldmHashLog =161 , ZSTD_c_ldmMinMatch =162 ,
  ZSTD_c_ldmBucketSizeLog =163 , ZSTD_c_ldmHashRateLog =164 , ZSTD_c_contentSizeFlag =200 , ZSTD_c_checksumFlag =201 ,
  ZSTD_c_dictIDFlag =202 , ZSTD_c_nbWorkers =400 , ZSTD_c_jobSize =401 , ZSTD_c_overlapLog =402 ,
  ZSTD_c_experimentalParam1 =500 , ZSTD_c_experimentalParam2 =10 , ZSTD_c_experimentalParam3 =1000 , ZSTD_c_experimentalParam4 =1001 ,
  ZSTD_c_experimentalParam5 =1002 , ZSTD_c_experimentalParam7 =1004 , ZSTD_c_experimentalParam8 =1005 , ZSTD_c_experimentalParam9 =1006 ,
  ZSTD_c_experimentalParam10 =1007 , ZSTD_c_experimentalParam11 =1008 , ZSTD_c_experimentalParam12 =1009 , ZSTD_c_experimentalParam13 =1010 ,
  ZSTD_c_experimentalParam14 =1011 , ZSTD_c_experimentalParam15 =1012 , ZSTD_c_experimentalParam16 =1013 , ZSTD_c_experimentalParam17 =1014 ,
  ZSTD_c_experimentalParam18 =1015 , ZSTD_c_experimentalParam19 =1016
}
enum  ZSTD_ResetDirective { ZSTD_reset_session_only = 1 , ZSTD_reset_parameters = 2 , ZSTD_reset_session_and_parameters = 3 }
enum  ZSTD_dParameter {
  ZSTD_d_windowLogMax =100 , ZSTD_d_experimentalParam1 =1000 , ZSTD_d_experimentalParam2 =1001 , ZSTD_d_experimentalParam3 =1002 ,
  ZSTD_d_experimentalParam4 =1003 , ZSTD_d_experimentalParam5 =1004 , ZSTD_d_experimentalParam6 =1005
}
enum  ZSTD_EndDirective { ZSTD_e_continue =0 , ZSTD_e_flush =1 , ZSTD_e_end =2 }
enum  ZSTD_dictContentType_e { ZSTD_dct_auto = 0 , ZSTD_dct_rawContent = 1 , ZSTD_dct_fullDict = 2 }
enum  ZSTD_dictLoadMethod_e { ZSTD_dlm_byCopy = 0 , ZSTD_dlm_byRef = 1 }
enum  ZSTD_format_e { ZSTD_f_zstd1 = 0 , ZSTD_f_zstd1_magicless = 1 }
enum  ZSTD_forceIgnoreChecksum_e { ZSTD_d_validateChecksum = 0 , ZSTD_d_ignoreChecksum = 1 }
enum  ZSTD_refMultipleDDicts_e { ZSTD_rmd_refSingleDDict = 0 , ZSTD_rmd_refMultipleDDicts = 1 }
enum  ZSTD_dictAttachPref_e { ZSTD_dictDefaultAttach = 0 , ZSTD_dictForceAttach = 1 , ZSTD_dictForceCopy = 2 , ZSTD_dictForceLoad = 3 }
enum  ZSTD_literalCompressionMode_e { ZSTD_lcm_auto = 0 , ZSTD_lcm_huffman = 1 , ZSTD_lcm_uncompressed = 2 }
enum  ZSTD_paramSwitch_e { ZSTD_ps_auto = 0 , ZSTD_ps_enable = 1 , ZSTD_ps_disable = 2 }
enum  ZSTD_frameType_e { ZSTD_frame , ZSTD_skippableFrame }
enum  ZSTD_sequenceFormat_e { ZSTD_sf_noBlockDelimiters = 0 , ZSTD_sf_explicitBlockDelimiters = 1 }
enum  ZSTD_nextInputType_e {
  ZSTDnit_frameHeader , ZSTDnit_blockHeader , ZSTDnit_block , ZSTDnit_lastBlock ,
  ZSTDnit_checksum , ZSTDnit_skippableFrame
}
enum  ZSTD_ErrorCode {
  ZSTD_error_no_error = 0 , ZSTD_error_GENERIC = 1 , ZSTD_error_prefix_unknown = 10 , ZSTD_error_version_unsupported = 12 ,
  ZSTD_error_frameParameter_unsupported = 14 , ZSTD_error_frameParameter_windowTooLarge = 16 , ZSTD_error_corruption_detected = 20 , ZSTD_error_checksum_wrong = 22 ,
  ZSTD_error_literals_headerWrong = 24 , ZSTD_error_dictionary_corrupted = 30 , ZSTD_error_dictionary_wrong = 32 , ZSTD_error_dictionaryCreation_failed = 34 ,
  ZSTD_error_parameter_unsupported = 40 , ZSTD_error_parameter_combination_unsupported = 41 , ZSTD_error_parameter_outOfBound = 42 , ZSTD_error_tableLog_tooLarge = 44 ,
  ZSTD_error_maxSymbolValue_tooLarge = 46 , ZSTD_error_maxSymbolValue_tooSmall = 48 , ZSTD_error_stabilityCondition_notRespected = 50 , ZSTD_error_stage_wrong = 60 ,
  ZSTD_error_init_missing = 62 , ZSTD_error_memory_allocation = 64 , ZSTD_error_workSpace_tooSmall = 66 , ZSTD_error_dstSize_tooSmall = 70 ,
  ZSTD_error_srcSize_wrong = 72 , ZSTD_error_dstBuffer_null = 74 , ZSTD_error_noForwardProgress_destFull = 80 , ZSTD_error_noForwardProgress_inputEmpty = 82 ,
  ZSTD_error_frameIndex_tooLarge = 100 , ZSTD_error_seekableIO = 102 , ZSTD_error_dstBuffer_wrong = 104 , ZSTD_error_srcBuffer_wrong = 105 ,
  ZSTD_error_sequenceProducer_failed = 106 , ZSTD_error_externalSequences_invalid = 107 , ZSTD_error_maxCode = 120
}
enum  BIT_DStream_status { BIT_DStream_unfinished = 0 , BIT_DStream_endOfBuffer = 1 , BIT_DStream_completed = 2 , BIT_DStream_overflow = 3 }
enum  FSE_repeat { FSE_repeat_none , FSE_repeat_check , FSE_repeat_valid }
enum  HUF_flags_e {
  HUF_flags_bmi2 = (1 << 0) , HUF_flags_optimalDepth = (1 << 1) , HUF_flags_preferRepeat = (1 << 2) , HUF_flags_suspectUncompressible = (1 << 3) ,
  HUF_flags_disableAsm = (1 << 4) , HUF_flags_disableFast = (1 << 5)
}
enum  HUF_repeat { HUF_repeat_none , HUF_repeat_check , HUF_repeat_valid }
enum  XXH_errorcode { XXH_OK =0 , XXH_ERROR }
enum  XXH_endianess { XXH_bigEndian =0 , XXH_littleEndian =1 }
enum  XXH_alignment { XXH_aligned , XXH_unaligned }
enum  blockType_e { bt_raw , bt_rle , bt_compressed , bt_reserved }
enum  symbolEncodingType_e { set_basic , set_rle , set_compressed , set_repeat }
enum  ZSTD_overlap_e { ZSTD_no_overlap , ZSTD_overlap_src_before_dst }
enum  ZSTD_bufferMode_e { ZSTD_bm_buffered = 0 , ZSTD_bm_stable = 1 }
enum  ZSTD_longLengthType_e { ZSTD_llt_none = 0 , ZSTD_llt_literalLength = 1 , ZSTD_llt_matchLength = 2 }
enum  HIST_checkInput_e { trustInput , checkMaxSymbolValue }
enum  HUF_nbStreams_e { HUF_singleStream , HUF_fourStreams }
enum  ZSTD_cwksp_alloc_phase_e { ZSTD_cwksp_alloc_objects , ZSTD_cwksp_alloc_aligned_init_once , ZSTD_cwksp_alloc_aligned , ZSTD_cwksp_alloc_buffers }
enum  ZSTD_cwksp_static_alloc_e { ZSTD_cwksp_dynamic_alloc , ZSTD_cwksp_static_alloc }
enum  ZSTD_compressionStage_e { ZSTDcs_created =0 , ZSTDcs_init , ZSTDcs_ongoing , ZSTDcs_ending }
enum  ZSTD_cStreamStage { zcss_init =0 , zcss_load , zcss_flush }
enum  ZSTD_OptPrice_e { zop_dynamic =0 , zop_predef }
enum  ZSTD_buffered_policy_e { ZSTDb_not_buffered , ZSTDb_buffered }
enum  ZSTD_dictTableLoadMethod_e { ZSTD_dtlm_fast , ZSTD_dtlm_full }
enum  ZSTD_tableFillPurpose_e { ZSTD_tfp_forCCtx , ZSTD_tfp_forCDict }
enum  ZSTD_dictMode_e { ZSTD_noDict = 0 , ZSTD_extDict = 1 , ZSTD_dictMatchState = 2 , ZSTD_dedicatedDictSearch = 3 }
enum  ZSTD_cParamMode_e { ZSTD_cpm_noAttachDict = 0 , ZSTD_cpm_attachDict = 1 , ZSTD_cpm_createCDict = 2 , ZSTD_cpm_unknown = 3 }
enum  ZSTD_defaultPolicy_e { ZSTD_defaultDisallowed = 0 , ZSTD_defaultAllowed = 1 }
enum  ZSTD_compResetPolicy_e { ZSTDcrp_makeClean , ZSTDcrp_leaveDirty }
enum  ZSTD_indexResetPolicy_e { ZSTDirp_continue , ZSTDirp_reset }
enum  ZSTD_resetTarget_e { ZSTD_resetTarget_CDict , ZSTD_resetTarget_CCtx }
enum  ZSTD_buildSeqStore_e { ZSTDbss_compress , ZSTDbss_noCompress }
enum  searchMethod_e { search_hashChain =0 , search_binaryTree =1 , search_rowHash =2 }
enum  base_directive_e { base_0possible =0 , base_1guaranteed =1 }
enum  ZSTD_dStage {
  ZSTDds_getFrameHeaderSize , ZSTDds_decodeFrameHeader , ZSTDds_decodeBlockHeader , ZSTDds_decompressBlock ,
  ZSTDds_decompressLastBlock , ZSTDds_checkChecksum , ZSTDds_decodeSkippableHeader , ZSTDds_skipFrame
}
enum  ZSTD_dStreamStage {
  zdss_init =0 , zdss_loadHeader , zdss_read , zdss_load ,
  zdss_flush
}
enum  ZSTD_dictUses_e { ZSTD_use_indefinitely = -1 , ZSTD_dont_use = 0 , ZSTD_use_once = 1 }
enum  ZSTD_litLocation_e { ZSTD_not_in_dst = 0 , ZSTD_in_dst = 1 , ZSTD_split = 2 }
enum  streaming_operation { not_streaming = 0 , is_streaming = 1 }
enum  ZSTD_longOffset_e { ZSTD_lo_isRegularOffset , ZSTD_lo_isLongOffset =1 }

Functions

ZSTDLIB_API unsigned ZSTD_versionNumber (void)
ZSTDLIB_API const char * ZSTD_versionString (void)
ZSTDLIB_API size_t ZSTD_decompress (void *dst, size_t dstCapacity, const void *src, size_t compressedSize)
ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize (const void *src, size_t srcSize)
ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize (const void *src, size_t srcSize)
ZSTDLIB_API size_t ZSTD_findFrameCompressedSize (const void *src, size_t srcSize)
ZSTDLIB_API size_t ZSTD_compressBound (size_t srcSize)
ZSTDLIB_API unsigned ZSTD_isError (size_t code)
ZSTDLIB_API const char * ZSTD_getErrorName (size_t code)
ZSTDLIB_API int ZSTD_minCLevel (void)
ZSTDLIB_API int ZSTD_maxCLevel (void)
ZSTDLIB_API int ZSTD_defaultCLevel (void)
ZSTDLIB_API ZSTD_CCtx * ZSTD_createCCtx (void)
ZSTDLIB_API size_t ZSTD_freeCCtx (ZSTD_CCtx *cctx)
ZSTDLIB_API size_t ZSTD_compressCCtx (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, int compressionLevel)
ZSTDLIB_API ZSTD_DCtx * ZSTD_createDCtx (void)
ZSTDLIB_API size_t ZSTD_freeDCtx (ZSTD_DCtx *dctx)
ZSTDLIB_API size_t ZSTD_decompressDCtx (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds (ZSTD_cParameter cParam)
ZSTDLIB_API size_t ZSTD_CCtx_setParameter (ZSTD_CCtx *cctx, ZSTD_cParameter param, int value)
ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize (ZSTD_CCtx *cctx, unsigned long long pledgedSrcSize)
ZSTDLIB_API size_t ZSTD_CCtx_reset (ZSTD_CCtx *cctx, ZSTD_ResetDirective reset)
ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds (ZSTD_dParameter dParam)
ZSTDLIB_API size_t ZSTD_DCtx_setParameter (ZSTD_DCtx *dctx, ZSTD_dParameter param, int value)
ZSTDLIB_API size_t ZSTD_DCtx_reset (ZSTD_DCtx *dctx, ZSTD_ResetDirective reset)
ZSTDLIB_API ZSTD_CStream * ZSTD_createCStream (void)
ZSTDLIB_API size_t ZSTD_freeCStream (ZSTD_CStream *zcs)
ZSTDLIB_API size_t ZSTD_compressStream2 (ZSTD_CCtx *cctx, ZSTD_outBuffer *output, ZSTD_inBuffer *input, ZSTD_EndDirective endOp)
ZSTDLIB_API size_t ZSTD_CStreamInSize (void)
ZSTDLIB_API size_t ZSTD_CStreamOutSize (void)
ZSTDLIB_API size_t ZSTD_initCStream (ZSTD_CStream *zcs, int compressionLevel)
ZSTDLIB_API size_t ZSTD_compressStream (ZSTD_CStream *zcs, ZSTD_outBuffer *output, ZSTD_inBuffer *input)
ZSTDLIB_API size_t ZSTD_flushStream (ZSTD_CStream *zcs, ZSTD_outBuffer *output)
ZSTDLIB_API size_t ZSTD_endStream (ZSTD_CStream *zcs, ZSTD_outBuffer *output)
ZSTDLIB_API ZSTD_DStream * ZSTD_createDStream (void)
ZSTDLIB_API size_t ZSTD_freeDStream (ZSTD_DStream *zds)
ZSTDLIB_API size_t ZSTD_initDStream (ZSTD_DStream *zds)
ZSTDLIB_API size_t ZSTD_decompressStream (ZSTD_DStream *zds, ZSTD_outBuffer *output, ZSTD_inBuffer *input)
ZSTDLIB_API size_t ZSTD_DStreamInSize (void)
ZSTDLIB_API size_t ZSTD_DStreamOutSize (void)
ZSTDLIB_API size_t ZSTD_compress_usingDict (ZSTD_CCtx *ctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, int compressionLevel)
ZSTDLIB_API size_t ZSTD_decompress_usingDict (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize)
ZSTDLIB_API ZSTD_CDict * ZSTD_createCDict (const void *dictBuffer, size_t dictSize, int compressionLevel)
ZSTDLIB_API size_t ZSTD_freeCDict (ZSTD_CDict *CDict)
ZSTDLIB_API size_t ZSTD_compress_usingCDict (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict)
ZSTDLIB_API ZSTD_DDict * ZSTD_createDDict (const void *dictBuffer, size_t dictSize)
ZSTDLIB_API size_t ZSTD_freeDDict (ZSTD_DDict *ddict)
ZSTDLIB_API size_t ZSTD_decompress_usingDDict (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_DDict *ddict)
ZSTDLIB_API unsigned ZSTD_getDictID_fromDict (const void *dict, size_t dictSize)
ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict (const ZSTD_CDict *cdict)
ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict (const ZSTD_DDict *ddict)
ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame (const void *src, size_t srcSize)
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary (ZSTD_CCtx *cctx, const void *dict, size_t dictSize)
ZSTDLIB_API size_t ZSTD_CCtx_refCDict (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict)
ZSTDLIB_API size_t ZSTD_CCtx_refPrefix (ZSTD_CCtx *cctx, const void *prefix, size_t prefixSize)
ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary (ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
ZSTDLIB_API size_t ZSTD_DCtx_refDDict (ZSTD_DCtx *dctx, const ZSTD_DDict *ddict)
ZSTDLIB_API size_t ZSTD_DCtx_refPrefix (ZSTD_DCtx *dctx, const void *prefix, size_t prefixSize)
ZSTDLIB_API size_t ZSTD_sizeof_CCtx (const ZSTD_CCtx *cctx)
ZSTDLIB_API size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx *dctx)
ZSTDLIB_API size_t ZSTD_sizeof_CStream (const ZSTD_CStream *zcs)
ZSTDLIB_API size_t ZSTD_sizeof_DStream (const ZSTD_DStream *zds)
ZSTDLIB_API size_t ZSTD_sizeof_CDict (const ZSTD_CDict *cdict)
ZSTDLIB_API size_t ZSTD_sizeof_DDict (const ZSTD_DDict *ddict)
ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize (const void *src, size_t srcSize)
ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound (const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize (const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader (ZSTD_frameHeader *zfhPtr, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced (ZSTD_frameHeader *zfhPtr, const void *src, size_t srcSize, ZSTD_format_e format)
ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin (const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound (size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_generateSequences (ZSTD_CCtx *zc, ZSTD_Sequence *outSeqs, size_t outSeqsSize, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters (ZSTD_Sequence *sequences, size_t seqsSize)
ZSTDLIB_STATIC_API size_t ZSTD_compressSequences (ZSTD_CCtx *cctx, void *dst, size_t dstSize, const ZSTD_Sequence *inSeqs, size_t inSeqsSize, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame (void *dst, size_t dstCapacity, const void *src, size_t srcSize, unsigned magicVariant)
ZSTDLIB_API size_t ZSTD_readSkippableFrame (void *dst, size_t dstCapacity, unsigned *magicVariant, const void *src, size_t srcSize)
ZSTDLIB_API unsigned ZSTD_isSkippableFrame (const void *buffer, size_t size)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize (int maxCompressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams (ZSTD_compressionParameters cParams)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams (const ZSTD_CCtx_params *params)
ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize (void)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize (int maxCompressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams (ZSTD_compressionParameters cParams)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams (const ZSTD_CCtx_params *params)
ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize (size_t maxWindowSize)
ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame (const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize (size_t dictSize, int compressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize_advanced (size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod)
ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize (size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod)
ZSTDLIB_STATIC_API ZSTD_CCtx * ZSTD_initStaticCCtx (void *workspace, size_t workspaceSize)
ZSTDLIB_STATIC_API ZSTD_CStream * ZSTD_initStaticCStream (void *workspace, size_t workspaceSize)
ZSTDLIB_STATIC_API ZSTD_DCtx * ZSTD_initStaticDCtx (void *workspace, size_t workspaceSize)
ZSTDLIB_STATIC_API ZSTD_DStream * ZSTD_initStaticDStream (void *workspace, size_t workspaceSize)
ZSTDLIB_STATIC_API const ZSTD_CDict * ZSTD_initStaticCDict (void *workspace, size_t workspaceSize, const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, ZSTD_compressionParameters cParams)
ZSTDLIB_STATIC_API const ZSTD_DDict * ZSTD_initStaticDDict (void *workspace, size_t workspaceSize, const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
ZSTDLIB_STATIC_API ZSTD_CCtx * ZSTD_createCCtx_advanced (ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_CStream * ZSTD_createCStream_advanced (ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_DCtx * ZSTD_createDCtx_advanced (ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_DStream * ZSTD_createDStream_advanced (ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_CDict * ZSTD_createCDict_advanced (const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_threadPool * ZSTD_createThreadPool (size_t numThreads)
ZSTDLIB_STATIC_API void ZSTD_freeThreadPool (ZSTD_threadPool *pool)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refThreadPool (ZSTD_CCtx *cctx, ZSTD_threadPool *pool)
ZSTDLIB_STATIC_API ZSTD_CDict * ZSTD_createCDict_advanced2 (const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, const ZSTD_CCtx_params *cctxParams, ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_DDict * ZSTD_createDDict_advanced (const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, ZSTD_customMem customMem)
ZSTDLIB_STATIC_API ZSTD_CDict * ZSTD_createCDict_byReference (const void *dictBuffer, size_t dictSize, int compressionLevel)
ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_getCParams (int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize)
ZSTDLIB_STATIC_API ZSTD_parameters ZSTD_getParams (int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_checkCParams (ZSTD_compressionParameters params)
ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_adjustCParams (ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setCParams (ZSTD_CCtx *cctx, ZSTD_compressionParameters cparams)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setFParams (ZSTD_CCtx *cctx, ZSTD_frameParameters fparams)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParams (ZSTD_CCtx *cctx, ZSTD_parameters params)
ZSTDLIB_STATIC_API size_t ZSTD_compress_advanced (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, ZSTD_parameters params)
ZSTDLIB_STATIC_API size_t ZSTD_compress_usingCDict_advanced (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict, ZSTD_frameParameters fParams)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference (ZSTD_CCtx *cctx, const void *dict, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced (ZSTD_CCtx *cctx, const void *prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_getParameter (const ZSTD_CCtx *cctx, ZSTD_cParameter param, int *value)
ZSTDLIB_STATIC_API ZSTD_CCtx_params * ZSTD_createCCtxParams (void)
ZSTDLIB_STATIC_API size_t ZSTD_freeCCtxParams (ZSTD_CCtx_params *params)
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_reset (ZSTD_CCtx_params *params)
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init (ZSTD_CCtx_params *cctxParams, int compressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init_advanced (ZSTD_CCtx_params *cctxParams, ZSTD_parameters params)
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_setParameter (ZSTD_CCtx_params *params, ZSTD_cParameter param, int value)
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_getParameter (const ZSTD_CCtx_params *params, ZSTD_cParameter param, int *value)
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParametersUsingCCtxParams (ZSTD_CCtx *cctx, const ZSTD_CCtx_params *params)
ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, size_t *dstPos, const void *src, size_t srcSize, size_t *srcPos, ZSTD_EndDirective endOp)
ZSTDLIB_STATIC_API unsigned ZSTD_isFrame (const void *buffer, size_t size)
ZSTDLIB_STATIC_API ZSTD_DDict * ZSTD_createDDict_byReference (const void *dictBuffer, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference (ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced (ZSTD_DCtx *dctx, const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced (ZSTD_DCtx *dctx, const void *prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_setMaxWindowSize (ZSTD_DCtx *dctx, size_t maxWindowSize)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter (ZSTD_DCtx *dctx, ZSTD_dParameter param, int *value)
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_setFormat (ZSTD_DCtx *dctx, ZSTD_format_e format)
ZSTDLIB_STATIC_API size_t ZSTD_decompressStream_simpleArgs (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, size_t *dstPos, const void *src, size_t srcSize, size_t *srcPos)
ZSTDLIB_STATIC_API size_t ZSTD_initCStream_srcSize (ZSTD_CStream *zcs, int compressionLevel, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_initCStream_usingDict (ZSTD_CStream *zcs, const void *dict, size_t dictSize, int compressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_initCStream_advanced (ZSTD_CStream *zcs, const void *dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_initCStream_usingCDict (ZSTD_CStream *zcs, const ZSTD_CDict *cdict)
ZSTDLIB_STATIC_API size_t ZSTD_initCStream_usingCDict_advanced (ZSTD_CStream *zcs, const ZSTD_CDict *cdict, ZSTD_frameParameters fParams, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_resetCStream (ZSTD_CStream *zcs, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API ZSTD_frameProgression ZSTD_getFrameProgression (const ZSTD_CCtx *cctx)
ZSTDLIB_STATIC_API size_t ZSTD_toFlushNow (ZSTD_CCtx *cctx)
ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDict (ZSTD_DStream *zds, const void *dict, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDDict (ZSTD_DStream *zds, const ZSTD_DDict *ddict)
ZSTDLIB_STATIC_API size_t ZSTD_resetDStream (ZSTD_DStream *zds)
ZSTDLIB_STATIC_API void ZSTD_registerSequenceProducer (ZSTD_CCtx *cctx, void *sequenceProducerState, ZSTD_sequenceProducer_F sequenceProducer)
ZSTDLIB_STATIC_API void ZSTD_CCtxParams_registerSequenceProducer (ZSTD_CCtx_params *params, void *sequenceProducerState, ZSTD_sequenceProducer_F sequenceProducer)
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin (ZSTD_CCtx *cctx, int compressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, int compressionLevel)
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict)
ZSTDLIB_STATIC_API size_t ZSTD_copyCCtx (ZSTD_CCtx *cctx, const ZSTD_CCtx *preparedCCtx, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_compressContinue (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_compressEnd (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_advanced (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict_advanced (ZSTD_CCtx *const cctx, const ZSTD_CDict *const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min (unsigned long long windowSize, unsigned long long frameContentSize)
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin (ZSTD_DCtx *dctx)
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict (ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict (ZSTD_DCtx *dctx, const ZSTD_DDict *ddict)
ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress (ZSTD_DCtx *dctx)
ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API void ZSTD_copyDCtx (ZSTD_DCtx *dctx, const ZSTD_DCtx *preparedDCtx)
ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType (ZSTD_DCtx *dctx)
ZSTDLIB_STATIC_API size_t ZSTD_getBlockSize (const ZSTD_CCtx *cctx)
ZSTDLIB_STATIC_API size_t ZSTD_compressBlock (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_decompressBlock (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
ZSTDLIB_STATIC_API size_t ZSTD_insertBlock (ZSTD_DCtx *dctx, const void *blockStart, size_t blockSize)
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR ptrdiff_t ZSTD_wrappedPtrDiff (unsigned char const *lhs, unsigned char const *rhs)
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR unsigned char const * ZSTD_wrappedPtrAdd (unsigned char const *ptr, ptrdiff_t add)
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR unsigned char const * ZSTD_wrappedPtrSub (unsigned char const *ptr, ptrdiff_t sub)
MEM_STATIC unsigned char * ZSTD_maybeNullPtrAdd (unsigned char *ptr, ptrdiff_t add)
MEM_STATIC unsigned MEM_32bits (void)
MEM_STATIC unsigned MEM_64bits (void)
MEM_STATIC unsigned MEM_isLittleEndian (void)
MEM_STATIC U16 MEM_read16 (const void *memPtr)
MEM_STATIC U32 MEM_read32 (const void *memPtr)
MEM_STATIC U64 MEM_read64 (const void *memPtr)
MEM_STATIC size_t MEM_readST (const void *memPtr)
MEM_STATIC void MEM_write16 (void *memPtr, U16 value)
MEM_STATIC void MEM_write32 (void *memPtr, U32 value)
MEM_STATIC void MEM_write64 (void *memPtr, U64 value)
MEM_STATIC U16 MEM_readLE16 (const void *memPtr)
MEM_STATIC U32 MEM_readLE24 (const void *memPtr)
MEM_STATIC U32 MEM_readLE32 (const void *memPtr)
MEM_STATIC U64 MEM_readLE64 (const void *memPtr)
MEM_STATIC size_t MEM_readLEST (const void *memPtr)
MEM_STATIC void MEM_writeLE16 (void *memPtr, U16 val)
MEM_STATIC void MEM_writeLE24 (void *memPtr, U32 val)
MEM_STATIC void MEM_writeLE32 (void *memPtr, U32 val32)
MEM_STATIC void MEM_writeLE64 (void *memPtr, U64 val64)
MEM_STATIC void MEM_writeLEST (void *memPtr, size_t val)
MEM_STATIC U32 MEM_readBE32 (const void *memPtr)
MEM_STATIC U64 MEM_readBE64 (const void *memPtr)
MEM_STATIC size_t MEM_readBEST (const void *memPtr)
MEM_STATIC void MEM_writeBE32 (void *memPtr, U32 val32)
MEM_STATIC void MEM_writeBE64 (void *memPtr, U64 val64)
MEM_STATIC void MEM_writeBEST (void *memPtr, size_t val)
MEM_STATIC U32 MEM_swap32 (U32 in)
MEM_STATIC U64 MEM_swap64 (U64 in)
MEM_STATIC size_t MEM_swapST (size_t in)
MEM_STATIC U32 MEM_swap32_fallback (U32 in)
MEM_STATIC U64 MEM_swap64_fallback (U64 in)
MEM_STATIC void MEM_check (void)
ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode (size_t functionResult)
ZSTDERRORLIB_API const char * ZSTD_getErrorString (ZSTD_ErrorCode code)
ERR_STATIC unsigned ERR_isError (size_t code)
ERR_STATIC ERR_enum ERR_getErrorCode (size_t code)
const char * ERR_getErrorString (ERR_enum code)
ERR_STATIC const char * ERR_getErrorName (size_t code)
static INLINE_KEYWORD UNUSED_ATTR void _force_has_format_string (const char *format,...)
FSE_PUBLIC_API unsigned FSE_versionNumber (void)
FSE_PUBLIC_API size_t FSE_compressBound (size_t size)
FSE_PUBLIC_API unsigned FSE_isError (size_t code)
FSE_PUBLIC_API const char * FSE_getErrorName (size_t code)
FSE_PUBLIC_API unsigned FSE_optimalTableLog (unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
FSE_PUBLIC_API size_t FSE_normalizeCount (short *normalizedCounter, unsigned tableLog, const unsigned *count, size_t srcSize, unsigned maxSymbolValue, unsigned useLowProbCount)
FSE_PUBLIC_API size_t FSE_NCountWriteBound (unsigned maxSymbolValue, unsigned tableLog)
FSE_PUBLIC_API size_t FSE_writeNCount (void *buffer, size_t bufferSize, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
FSE_PUBLIC_API size_t FSE_buildCTable (FSE_CTable *ct, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
FSE_PUBLIC_API size_t FSE_compress_usingCTable (void *dst, size_t dstCapacity, const void *src, size_t srcSize, const FSE_CTable *ct)
FSE_PUBLIC_API size_t FSE_readNCount (short *normalizedCounter, unsigned *maxSymbolValuePtr, unsigned *tableLogPtr, const void *rBuffer, size_t rBuffSize)
FSE_PUBLIC_API size_t FSE_readNCount_bmi2 (short *normalizedCounter, unsigned *maxSymbolValuePtr, unsigned *tableLogPtr, const void *rBuffer, size_t rBuffSize, int bmi2)
MEM_STATIC unsigned ZSTD_countTrailingZeros32_fallback (U32 val)
MEM_STATIC unsigned ZSTD_countTrailingZeros32 (U32 val)
MEM_STATIC unsigned ZSTD_countLeadingZeros32_fallback (U32 val)
MEM_STATIC unsigned ZSTD_countLeadingZeros32 (U32 val)
MEM_STATIC unsigned ZSTD_countTrailingZeros64 (U64 val)
MEM_STATIC unsigned ZSTD_countLeadingZeros64 (U64 val)
MEM_STATIC unsigned ZSTD_NbCommonBytes (size_t val)
MEM_STATIC unsigned ZSTD_highbit32 (U32 val)
MEM_STATIC U64 ZSTD_rotateRight_U64 (U64 const value, U32 count)
MEM_STATIC U32 ZSTD_rotateRight_U32 (U32 const value, U32 count)
MEM_STATIC U16 ZSTD_rotateRight_U16 (U16 const value, U32 count)
MEM_STATIC size_t BIT_initCStream (BIT_CStream_t *bitC, void *dstBuffer, size_t dstCapacity)
MEM_STATIC void BIT_addBits (BIT_CStream_t *bitC, size_t value, unsigned nbBits)
MEM_STATIC void BIT_flushBits (BIT_CStream_t *bitC)
MEM_STATIC size_t BIT_closeCStream (BIT_CStream_t *bitC)
MEM_STATIC size_t BIT_initDStream (BIT_DStream_t *bitD, const void *srcBuffer, size_t srcSize)
MEM_STATIC size_t BIT_readBits (BIT_DStream_t *bitD, unsigned nbBits)
MEM_STATIC BIT_DStream_status BIT_reloadDStream (BIT_DStream_t *bitD)
MEM_STATIC unsigned BIT_endOfDStream (const BIT_DStream_t *bitD)
MEM_STATIC void BIT_addBitsFast (BIT_CStream_t *bitC, size_t value, unsigned nbBits)
MEM_STATIC void BIT_flushBitsFast (BIT_CStream_t *bitC)
MEM_STATIC size_t BIT_readBitsFast (BIT_DStream_t *bitD, unsigned nbBits)
FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits (size_t bitContainer, U32 const nbBits)
FORCE_INLINE_TEMPLATE size_t BIT_getUpperBits (BitContainerType bitContainer, U32 const start)
FORCE_INLINE_TEMPLATE size_t BIT_getMiddleBits (BitContainerType bitContainer, U32 const start, U32 const nbBits)
FORCE_INLINE_TEMPLATE size_t BIT_lookBits (const BIT_DStream_t *bitD, U32 nbBits)
MEM_STATIC size_t BIT_lookBitsFast (const BIT_DStream_t *bitD, U32 nbBits)
FORCE_INLINE_TEMPLATE void BIT_skipBits (BIT_DStream_t *bitD, U32 nbBits)
MEM_STATIC BIT_DStream_status BIT_reloadDStream_internal (BIT_DStream_t *bitD)
MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast (BIT_DStream_t *bitD)
unsigned FSE_optimalTableLog_internal (unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
size_t FSE_buildCTable_rle (FSE_CTable *ct, unsigned char symbolValue)
size_t FSE_buildCTable_wksp (FSE_CTable *ct, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize)
FSE_PUBLIC_API size_t FSE_buildDTable_wksp (FSE_DTable *dt, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize)
size_t FSE_decompress_wksp_bmi2 (void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, unsigned maxLog, void *workSpace, size_t wkspSize, int bmi2)
static void FSE_initCState (FSE_CState_t *CStatePtr, const FSE_CTable *ct)
static void FSE_encodeSymbol (BIT_CStream_t *bitC, FSE_CState_t *CStatePtr, unsigned symbol)
static void FSE_flushCState (BIT_CStream_t *bitC, const FSE_CState_t *CStatePtr)
static void FSE_initDState (FSE_DState_t *DStatePtr, BIT_DStream_t *bitD, const FSE_DTable *dt)
static unsigned char FSE_decodeSymbol (FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
static unsigned FSE_endOfDState (const FSE_DState_t *DStatePtr)
static unsigned char FSE_decodeSymbolFast (FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
MEM_STATIC void FSE_initCState2 (FSE_CState_t *statePtr, const FSE_CTable *ct, U32 symbol)
MEM_STATIC U32 FSE_getMaxNbBits (const void *symbolTTPtr, U32 symbolValue)
MEM_STATIC U32 FSE_bitCost (const void *symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)
MEM_STATIC BYTE FSE_peekSymbol (const FSE_DState_t *DStatePtr)
MEM_STATIC void FSE_updateState (FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
size_t HUF_compressBound (size_t size)
unsigned HUF_isError (size_t code)
const char * HUF_getErrorName (size_t code)
unsigned HUF_minTableLog (unsigned symbolCardinality)
unsigned HUF_cardinality (const unsigned *count, unsigned maxSymbolValue)
unsigned HUF_optimalTableLog (unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, void *workSpace, size_t wkspSize, HUF_CElt *table, const unsigned *count, int flags)
size_t HUF_writeCTable_wksp (void *dst, size_t maxDstSize, const HUF_CElt *CTable, unsigned maxSymbolValue, unsigned huffLog, void *workspace, size_t workspaceSize)
size_t HUF_compress4X_usingCTable (void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable, int flags)
size_t HUF_estimateCompressedSize (const HUF_CElt *CTable, const unsigned *count, unsigned maxSymbolValue)
int HUF_validateCTable (const HUF_CElt *CTable, const unsigned *count, unsigned maxSymbolValue)
size_t HUF_compress4X_repeat (void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int flags)
size_t HUF_buildCTable_wksp (HUF_CElt *tree, const unsigned *count, U32 maxSymbolValue, U32 maxNbBits, void *workSpace, size_t wkspSize)
size_t HUF_readStats (BYTE *huffWeight, size_t hwSize, U32 *rankStats, U32 *nbSymbolsPtr, U32 *tableLogPtr, const void *src, size_t srcSize)
size_t HUF_readStats_wksp (BYTE *huffWeight, size_t hwSize, U32 *rankStats, U32 *nbSymbolsPtr, U32 *tableLogPtr, const void *src, size_t srcSize, void *workspace, size_t wkspSize, int flags)
size_t HUF_readCTable (HUF_CElt *CTable, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, unsigned *hasZeroWeights)
U32 HUF_getNbBitsFromCTable (const HUF_CElt *symbolTable, U32 symbolValue)
HUF_CTableHeader HUF_readCTableHeader (HUF_CElt const *ctable)
U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize)
size_t HUF_compress1X_usingCTable (void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable, int flags)
size_t HUF_compress1X_repeat (void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int flags)
size_t HUF_decompress1X_DCtx_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
size_t HUF_decompress1X2_DCtx_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
size_t HUF_decompress1X_usingDTable (void *dst, size_t maxDstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable, int flags)
size_t HUF_decompress1X1_DCtx_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
size_t HUF_decompress4X_usingDTable (void *dst, size_t maxDstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable, int flags)
size_t HUF_decompress4X_hufOnly_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
size_t HUF_readDTableX1_wksp (HUF_DTable *DTable, const void *src, size_t srcSize, void *workSpace, size_t wkspSize, int flags)
size_t HUF_readDTableX2_wksp (HUF_DTable *DTable, const void *src, size_t srcSize, void *workSpace, size_t wkspSize, int flags)
FORCE_INLINE_TEMPLATE size_t FSE_readNCount_body (short *normalizedCounter, unsigned *maxSVPtr, unsigned *tableLogPtr, const void *headerBuffer, size_t hbSize)
static size_t FSE_readNCount_body_default (short *normalizedCounter, unsigned *maxSVPtr, unsigned *tableLogPtr, const void *headerBuffer, size_t hbSize)
FORCE_INLINE_TEMPLATE size_t HUF_readStats_body (BYTE *huffWeight, size_t hwSize, U32 *rankStats, U32 *nbSymbolsPtr, U32 *tableLogPtr, const void *src, size_t srcSize, void *workSpace, size_t wkspSize, int bmi2)
static size_t HUF_readStats_body_default (BYTE *huffWeight, size_t hwSize, U32 *rankStats, U32 *nbSymbolsPtr, U32 *tableLogPtr, const void *src, size_t srcSize, void *workSpace, size_t wkspSize)
static size_t FSE_buildDTable_internal (FSE_DTable *dt, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize)
FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic (void *dst, size_t maxDstSize, const void *cSrc, size_t cSrcSize, const FSE_DTable *dt, const unsigned fast)
FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body (void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, unsigned maxLog, void *workSpace, size_t wkspSize, int bmi2)
static size_t FSE_decompress_wksp_body_default (void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, unsigned maxLog, void *workSpace, size_t wkspSize)
MEM_STATIC void * ZSTD_customMalloc (size_t size, ZSTD_customMem customMem)
MEM_STATIC void * ZSTD_customCalloc (size_t size, ZSTD_customMem customMem)
MEM_STATIC void ZSTD_customFree (void *ptr, ZSTD_customMem customMem)
POOL_ctx * POOL_create (size_t numThreads, size_t queueSize)
POOL_ctx * POOL_create_advanced (size_t numThreads, size_t queueSize, ZSTD_customMem customMem)
void POOL_free (POOL_ctx *ctx)
void POOL_joinJobs (POOL_ctx *ctx)
int POOL_resize (POOL_ctx *ctx, size_t numThreads)
size_t POOL_sizeof (const POOL_ctx *ctx)
void POOL_add (POOL_ctx *ctx, POOL_function function, void *opaque)
int POOL_tryAdd (POOL_ctx *ctx, POOL_function function, void *opaque)
static void * POOL_thread (void *opaque)
static void POOL_join (POOL_ctx *ctx)
static int POOL_resize_internal (POOL_ctx *ctx, size_t numThreads)
static int isQueueFull (POOL_ctx const *ctx)
static void POOL_add_internal (POOL_ctx *ctx, POOL_function function, void *opaque)
XXH_PUBLIC_API unsigned XXH_versionNumber (void)
XXH_PUBLIC_API XXH32_hash_t XXH32 (const void *input, size_t length, unsigned int seed)
XXH_PUBLIC_API XXH64_hash_t XXH64 (const void *input, size_t length, unsigned long long seed)
XXH_PUBLIC_API XXH32_state_t * XXH32_createState (void)
XXH_PUBLIC_API XXH_errorcode XXH32_freeState (XXH32_state_t *statePtr)
XXH_PUBLIC_API XXH64_state_t * XXH64_createState (void)
XXH_PUBLIC_API XXH_errorcode XXH64_freeState (XXH64_state_t *statePtr)
XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t *statePtr, unsigned int seed)
XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t *statePtr, const void *input, size_t length)
XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t *statePtr)
XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t *statePtr, unsigned long long seed)
XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t *statePtr, const void *input, size_t length)
XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t *statePtr)
XXH_PUBLIC_API void XXH32_copyState (XXH32_state_t *__restrict dst_state, const XXH32_state_t *__restrict src_state)
XXH_PUBLIC_API void XXH64_copyState (XXH64_state_t *__restrict dst_state, const XXH64_state_t *__restrict src_state)
XXH_PUBLIC_API void XXH32_canonicalFromHash (XXH32_canonical_t *dst, XXH32_hash_t hash)
XXH_PUBLIC_API void XXH64_canonicalFromHash (XXH64_canonical_t *dst, XXH64_hash_t hash)
XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical (const XXH32_canonical_t *src)
XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical (const XXH64_canonical_t *src)
static void * XXH_malloc (size_t s)
static void XXH_free (void *p)
static void * XXH_memcpy (void *dest, const void *src, size_t size)
static U32 XXH_read32 (const void *memPtr)
static U64 XXH_read64 (const void *memPtr)
static U32 XXH_swap32 (U32 x)
static U64 XXH_swap64 (U64 x)
XXHASH_FORCE_INLINE_TEMPLATE U32 XXH_readLE32_align (const void *ptr, XXH_endianess endian, XXH_alignment align)
XXHASH_FORCE_INLINE_TEMPLATE U32 XXH_readLE32 (const void *ptr, XXH_endianess endian)
static U32 XXH_readBE32 (const void *ptr)
XXHASH_FORCE_INLINE_TEMPLATE U64 XXH_readLE64_align (const void *ptr, XXH_endianess endian, XXH_alignment align)
XXHASH_FORCE_INLINE_TEMPLATE U64 XXH_readLE64 (const void *ptr, XXH_endianess endian)
static U64 XXH_readBE64 (const void *ptr)
static U32 XXH32_round (U32 seed, U32 input)
XXHASH_FORCE_INLINE_TEMPLATE U32 XXH32_endian_align (const void *input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)
static U64 XXH64_round (U64 acc, U64 input)
static U64 XXH64_mergeRound (U64 acc, U64 val)
XXHASH_FORCE_INLINE_TEMPLATE U64 XXH64_endian_align (const void *input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)
XXHASH_FORCE_INLINE_TEMPLATE XXH_errorcode XXH32_update_endian (XXH32_state_t *state, const void *input, size_t len, XXH_endianess endian)
XXHASH_FORCE_INLINE_TEMPLATE U32 XXH32_digest_endian (const XXH32_state_t *state, XXH_endianess endian)
XXHASH_FORCE_INLINE_TEMPLATE XXH_errorcode XXH64_update_endian (XXH64_state_t *state, const void *input, size_t len, XXH_endianess endian)
XXHASH_FORCE_INLINE_TEMPLATE U64 XXH64_digest_endian (const XXH64_state_t *state, XXH_endianess endian)
MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid (void)
 C (sse3, 0) C(pclmuldq
 C (dtes64, 2) C(monitor
 C (dscpl, 4) C(vmx
 C (smx, 6) C(eist
 C (tm2, 8) C(ssse3
 C (cnxtid, 10) C(fma
 C (cx16, 13) C(xtpr
 C (pdcm, 15) C(pcid
 C (dca, 18) C(sse41
 C (sse42, 20) C(x2apic
 C (movbe, 22) C(popcnt
 C (tscdeadline, 24) C(aes
 C (xsave, 26) C(osxsave
 C (avx, 28) C(f16c
 C (rdrand, 30) D(fpu
 D (vme, 1) D(de
 D (pse, 3) D(tsc
 D (msr, 5) D(pae
 D (mce, 7) D(cx8
 D (apic, 9) D(sep
 D (mtrr, 12) D(pge
 D (mca, 14) D(cmov
 D (pat, 16) D(pse36
 D (psn, 18) D(clfsh
 D (ds, 21) D(acpi
 D (mmx, 23) D(fxsr
 D (sse, 25) D(sse2
 D (ss, 27) D(htt
 D (tm, 29) D(pbe
 B (bmi1, 3) B(hle
 B (avx2, 5) B(smep
 B (bmi2, 8) B(erms
 B (invpcid, 10) B(rtm
 B (mpx, 14) B(avx512f
 B (avx512dq, 17) B(rdseed
 B (adx, 19) B(smap
 B (avx512ifma, 21) B(pcommit
 B (clflushopt, 23) B(clwb
 B (avx512pf, 26) B(avx512er
 B (avx512cd, 28) B(sha
 B (avx512bw, 30) B(avx512vl
 C (prefetchwt1, 0) C(avx512vbmi
static void ZSTD_copy8 (void *dst, const void *src)
static void ZSTD_copy16 (void *dst, const void *src)
MEM_STATIC FORCE_INLINE_ATTR void ZSTD_wildcopy (void *dst, const void *src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
MEM_STATIC size_t ZSTD_limitCopy (void *dst, size_t dstCapacity, const void *src, size_t srcSize)
MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength (seqStore_t const *seqStore, seqDef const *seq)
const seqStore_t * ZSTD_getSeqStore (const ZSTD_CCtx *ctx)
int ZSTD_seqToCodes (const seqStore_t *seqStorePtr)
void ZSTD_invalidateRepCodes (ZSTD_CCtx *cctx)
size_t ZSTD_getcBlockSize (const void *src, size_t srcSize, blockProperties_t *bpPtr)
size_t ZSTD_decodeSeqHeaders (ZSTD_DCtx *dctx, int *nbSeqPtr, const void *src, size_t srcSize)
MEM_STATIC int ZSTD_cpuSupportsBmi2 (void)
size_t HIST_count (unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize)
unsigned HIST_isError (size_t code)
size_t HIST_count_wksp (unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, void *workSpace, size_t workSpaceSize)
size_t HIST_countFast (unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize)
size_t HIST_countFast_wksp (unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, void *workSpace, size_t workSpaceSize)
unsigned HIST_count_simple (unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize)
static size_t FSE_writeNCount_generic (void *header, size_t headerBufferSize, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, unsigned writeIsSafe)
static unsigned FSE_minTableLog (size_t srcSize, unsigned maxSymbolValue)
static size_t FSE_normalizeM2 (short *norm, U32 tableLog, const unsigned *count, size_t total, U32 maxSymbolValue, short lowProbCount)
static size_t FSE_compress_usingCTable_generic (void *dst, size_t dstSize, const void *src, size_t srcSize, const FSE_CTable *ct, const unsigned fast)
static size_t HIST_count_parallel_wksp (unsigned *count, unsigned *maxSymbolValuePtr, const void *source, size_t sourceSize, HIST_checkInput_e check, U32 *const workSpace)
static void * HUF_alignUpWorkspace (void *workspace, size_t *workspaceSizePtr, size_t align)
static size_t HUF_compressWeights (void *dst, size_t dstSize, const void *weightTable, size_t wtSize, void *workspace, size_t workspaceSize)
static size_t HUF_getNbBits (HUF_CElt elt)
static size_t HUF_getNbBitsFast (HUF_CElt elt)
static size_t HUF_getValue (HUF_CElt elt)
static size_t HUF_getValueFast (HUF_CElt elt)
static void HUF_setNbBits (HUF_CElt *elt, size_t nbBits)
static void HUF_setValue (HUF_CElt *elt, size_t value)
static void HUF_writeCTableHeader (HUF_CElt *ctable, U32 tableLog, U32 maxSymbolValue)
static U32 HUF_setMaxHeight (nodeElt *huffNode, U32 lastNonNull, U32 targetNbBits)
static U32 HUF_getIndex (U32 const count)
static void HUF_swapNodes (nodeElt *a, nodeElt *b)
MEM_STATIC int HUF_isSorted (nodeElt huffNode[], U32 const maxSymbolValue1)
HINT_INLINE void HUF_insertionSort (nodeElt huffNode[], int const low, int const high)
static int HUF_quickSortPartition (nodeElt arr[], int const low, int const high)
static void HUF_simpleQuickSort (nodeElt arr[], int low, int high)
static void HUF_sort (nodeElt huffNode[], const unsigned count[], U32 const maxSymbolValue, rankPos rankPosition[])
static int HUF_buildTree (nodeElt *huffNode, U32 maxSymbolValue)
static void HUF_buildCTableFromTree (HUF_CElt *CTable, nodeElt const *huffNode, int nonNullRank, U32 maxSymbolValue, U32 maxNbBits)
static size_t HUF_initCStream (HUF_CStream_t *bitC, void *startPtr, size_t dstCapacity)
FORCE_INLINE_TEMPLATE void HUF_addBits (HUF_CStream_t *bitC, HUF_CElt elt, int idx, int kFast)
FORCE_INLINE_TEMPLATE void HUF_zeroIndex1 (HUF_CStream_t *bitC)
FORCE_INLINE_TEMPLATE void HUF_mergeIndex1 (HUF_CStream_t *bitC)
FORCE_INLINE_TEMPLATE void HUF_flushBits (HUF_CStream_t *bitC, int kFast)
static HUF_CElt HUF_endMark (void)
static size_t HUF_closeCStream (HUF_CStream_t *bitC)
FORCE_INLINE_TEMPLATE void HUF_encodeSymbol (HUF_CStream_t *bitCPtr, U32 symbol, const HUF_CElt *CTable, int idx, int fast)
FORCE_INLINE_TEMPLATE void HUF_compress1X_usingCTable_internal_body_loop (HUF_CStream_t *bitC, const BYTE *ip, size_t srcSize, const HUF_CElt *ct, int kUnroll, int kFastFlush, int kLastFast)
static size_t HUF_tightCompressBound (size_t srcSize, size_t tableLog)
FORCE_INLINE_TEMPLATE size_t HUF_compress1X_usingCTable_internal_body (void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable)
static size_t HUF_compress1X_usingCTable_internal (void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable, const int flags)
static size_t HUF_compress4X_usingCTable_internal (void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable, int flags)
static size_t HUF_compressCTable_internal (BYTE *const ostart, BYTE *op, BYTE *const oend, const void *src, size_t srcSize, HUF_nbStreams_e nbStreams, const HUF_CElt *CTable, const int flags)
static size_t HUF_compress_internal (void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog, HUF_nbStreams_e nbStreams, void *workSpace, size_t wkspSize, HUF_CElt *oldHufTable, HUF_repeat *repeat, int flags)
MEM_STATIC size_t ZSTD_cwksp_available_space (ZSTD_cwksp *ws)
MEM_STATIC void * ZSTD_cwksp_initialAllocStart (ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_assert_internal_consistency (ZSTD_cwksp *ws)
MEM_STATIC size_t ZSTD_cwksp_align (size_t size, size_t const align)
MEM_STATIC size_t ZSTD_cwksp_alloc_size (size_t size)
MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size (size_t size)
MEM_STATIC size_t ZSTD_cwksp_slack_space_required (void)
MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr (void *ptr, const size_t alignBytes)
MEM_STATIC void * ZSTD_cwksp_reserve_internal_buffer_space (ZSTD_cwksp *ws, size_t const bytes)
MEM_STATIC size_t ZSTD_cwksp_internal_advance_phase (ZSTD_cwksp *ws, ZSTD_cwksp_alloc_phase_e phase)
MEM_STATIC int ZSTD_cwksp_owns_buffer (const ZSTD_cwksp *ws, const void *ptr)
MEM_STATIC void * ZSTD_cwksp_reserve_internal (ZSTD_cwksp *ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase)
MEM_STATIC BYTE * ZSTD_cwksp_reserve_buffer (ZSTD_cwksp *ws, size_t bytes)
MEM_STATIC void * ZSTD_cwksp_reserve_aligned_init_once (ZSTD_cwksp *ws, size_t bytes)
MEM_STATIC void * ZSTD_cwksp_reserve_aligned (ZSTD_cwksp *ws, size_t bytes)
MEM_STATIC void * ZSTD_cwksp_reserve_table (ZSTD_cwksp *ws, size_t bytes)
MEM_STATIC void * ZSTD_cwksp_reserve_object (ZSTD_cwksp *ws, size_t bytes)
MEM_STATIC void ZSTD_cwksp_mark_tables_dirty (ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_mark_tables_clean (ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_clean_tables (ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_clear_tables (ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_clear (ZSTD_cwksp *ws)
MEM_STATIC size_t ZSTD_cwksp_sizeof (const ZSTD_cwksp *ws)
MEM_STATIC size_t ZSTD_cwksp_used (const ZSTD_cwksp *ws)
MEM_STATIC void ZSTD_cwksp_init (ZSTD_cwksp *ws, void *start, size_t size, ZSTD_cwksp_static_alloc_e isStatic)
MEM_STATIC size_t ZSTD_cwksp_create (ZSTD_cwksp *ws, size_t size, ZSTD_customMem customMem)
MEM_STATIC void ZSTD_cwksp_free (ZSTD_cwksp *ws, ZSTD_customMem customMem)
MEM_STATIC void ZSTD_cwksp_move (ZSTD_cwksp *dst, ZSTD_cwksp *src)
MEM_STATIC int ZSTD_cwksp_reserve_failed (const ZSTD_cwksp *ws)
MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds (const ZSTD_cwksp *const ws, size_t const estimatedSpace)
MEM_STATIC int ZSTD_cwksp_check_available (ZSTD_cwksp *ws, size_t additionalNeededSpace)
MEM_STATIC int ZSTD_cwksp_check_too_large (ZSTD_cwksp *ws, size_t additionalNeededSpace)
MEM_STATIC int ZSTD_cwksp_check_wasteful (ZSTD_cwksp *ws, size_t additionalNeededSpace)
MEM_STATIC void ZSTD_cwksp_bump_oversized_duration (ZSTD_cwksp *ws, size_t additionalNeededSpace)
ZSTDMT_CCtx * ZSTDMT_createCCtx_advanced (unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool *pool)
size_t ZSTDMT_freeCCtx (ZSTDMT_CCtx *mtctx)
size_t ZSTDMT_sizeof_CCtx (ZSTDMT_CCtx *mtctx)
size_t ZSTDMT_nextInputSizeHint (const ZSTDMT_CCtx *mtctx)
size_t ZSTDMT_initCStream_internal (ZSTDMT_CCtx *mtctx, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, const ZSTD_CDict *cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
size_t ZSTDMT_compressStream_generic (ZSTDMT_CCtx *mtctx, ZSTD_outBuffer *output, ZSTD_inBuffer *input, ZSTD_EndDirective endOp)
size_t ZSTDMT_toFlushNow (ZSTDMT_CCtx *mtctx)
void ZSTDMT_updateCParams_whileCompressing (ZSTDMT_CCtx *mtctx, const ZSTD_CCtx_params *cctxParams)
ZSTD_frameProgression ZSTDMT_getFrameProgression (ZSTDMT_CCtx *mtctx)
size_t ZSTD_buildBlockEntropyStats (const seqStore_t *seqStorePtr, const ZSTD_entropyCTables_t *prevEntropy, ZSTD_entropyCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, ZSTD_entropyCTablesMetadata_t *entropyMetadata, void *workspace, size_t wkspSize)
ZSTD_blockCompressor ZSTD_selectBlockCompressor (ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode)
MEM_STATIC U32 ZSTD_LLcode (U32 litLength)
MEM_STATIC U32 ZSTD_MLcode (U32 mlBase)
MEM_STATIC int ZSTD_cParam_withinBounds (ZSTD_cParameter cParam, int value)
MEM_STATIC size_t ZSTD_noCompressBlock (void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastBlock)
MEM_STATIC size_t ZSTD_rleCompressBlock (void *dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
MEM_STATIC size_t ZSTD_minGain (size_t srcSize, ZSTD_strategy strat)
MEM_STATIC int ZSTD_literalsCompressionIsDisabled (const ZSTD_CCtx_params *cctxParams)
static void ZSTD_safecopyLiterals (BYTE *op, BYTE const *ip, BYTE const *const iend, BYTE const *ilimit_w)
HINT_INLINE UNUSED_ATTR void ZSTD_storeSeq (seqStore_t *seqStorePtr, size_t litLength, const BYTE *literals, const BYTE *litLimit, U32 offBase, size_t matchLength)
MEM_STATIC void ZSTD_updateRep (U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
MEM_STATIC repcodes_t ZSTD_newRep (U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
MEM_STATIC size_t ZSTD_count (const BYTE *pIn, const BYTE *pMatch, const BYTE *const pInLimit)
MEM_STATIC size_t ZSTD_count_2segments (const BYTE *ip, const BYTE *match, const BYTE *iEnd, const BYTE *mEnd, const BYTE *iStart)
static U32 ZSTD_hash3 (U32 u, U32 h, U32 s)
MEM_STATIC size_t ZSTD_hash3Ptr (const void *ptr, U32 h)
MEM_STATIC size_t ZSTD_hash3PtrS (const void *ptr, U32 h, U32 s)
static U32 ZSTD_hash4 (U32 u, U32 h, U32 s)
static size_t ZSTD_hash4Ptr (const void *ptr, U32 h)
static size_t ZSTD_hash4PtrS (const void *ptr, U32 h, U32 s)
static size_t ZSTD_hash5 (U64 u, U32 h, U64 s)
static size_t ZSTD_hash5Ptr (const void *p, U32 h)
static size_t ZSTD_hash5PtrS (const void *p, U32 h, U64 s)
static size_t ZSTD_hash6 (U64 u, U32 h, U64 s)
static size_t ZSTD_hash6Ptr (const void *p, U32 h)
static size_t ZSTD_hash6PtrS (const void *p, U32 h, U64 s)
static size_t ZSTD_hash7 (U64 u, U32 h, U64 s)
static size_t ZSTD_hash7Ptr (const void *p, U32 h)
static size_t ZSTD_hash7PtrS (const void *p, U32 h, U64 s)
static size_t ZSTD_hash8 (U64 u, U32 h, U64 s)
static size_t ZSTD_hash8Ptr (const void *p, U32 h)
static size_t ZSTD_hash8PtrS (const void *p, U32 h, U64 s)
MEM_STATIC FORCE_INLINE_ATTR size_t ZSTD_hashPtr (const void *p, U32 hBits, U32 mls)
MEM_STATIC FORCE_INLINE_ATTR size_t ZSTD_hashPtrSalted (const void *p, U32 hBits, U32 mls, const U64 hashSalt)
static U64 ZSTD_ipow (U64 base, U64 exponent)
static U64 ZSTD_rollingHash_append (U64 hash, void const *buf, size_t size)
MEM_STATIC U64 ZSTD_rollingHash_compute (void const *buf, size_t size)
MEM_STATIC U64 ZSTD_rollingHash_primePower (U32 length)
MEM_STATIC U64 ZSTD_rollingHash_rotate (U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
MEM_STATIC void ZSTD_window_clear (ZSTD_window_t *window)
MEM_STATIC U32 ZSTD_window_isEmpty (ZSTD_window_t const window)
MEM_STATIC U32 ZSTD_window_hasExtDict (ZSTD_window_t const window)
MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode (const ZSTD_matchState_t *ms)
MEM_STATIC U32 ZSTD_window_canOverflowCorrect (ZSTD_window_t const window, U32 cycleLog, U32 maxDist, U32 loadedDictEnd, void const *src)
MEM_STATIC U32 ZSTD_window_needOverflowCorrection (ZSTD_window_t const window, U32 cycleLog, U32 maxDist, U32 loadedDictEnd, void const *src, void const *srcEnd)
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_window_correctOverflow (ZSTD_window_t *window, U32 cycleLog, U32 maxDist, void const *src)
MEM_STATIC void ZSTD_window_enforceMaxDist (ZSTD_window_t *window, const void *blockEnd, U32 maxDist, U32 *loadedDictEndPtr, const ZSTD_matchState_t **dictMatchStatePtr)
MEM_STATIC void ZSTD_checkDictValidity (const ZSTD_window_t *window, const void *blockEnd, U32 maxDist, U32 *loadedDictEndPtr, const ZSTD_matchState_t **dictMatchStatePtr)
MEM_STATIC void ZSTD_window_init (ZSTD_window_t *window)
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_window_update (ZSTD_window_t *window, void const *src, size_t srcSize, int forceNonContiguous)
MEM_STATIC U32 ZSTD_getLowestMatchIndex (const ZSTD_matchState_t *ms, U32 curr, unsigned windowLog)
MEM_STATIC U32 ZSTD_getLowestPrefixIndex (const ZSTD_matchState_t *ms, U32 curr, unsigned windowLog)
MEM_STATIC void ZSTD_writeTaggedIndex (U32 *const hashTable, size_t hashAndTag, U32 index)
MEM_STATIC int ZSTD_comparePackedTags (size_t packedTag1, size_t packedTag2)
size_t ZSTD_loadCEntropy (ZSTD_compressedBlockState_t *bs, void *workspace, const void *const dict, size_t dictSize)
void ZSTD_reset_compressedBlockState (ZSTD_compressedBlockState_t *bs)
ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams (const ZSTD_CCtx_params *CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
size_t ZSTD_initCStream_internal (ZSTD_CStream *zcs, const void *dict, size_t dictSize, const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, unsigned long long pledgedSrcSize)
void ZSTD_resetSeqStore (seqStore_t *ssPtr)
ZSTD_compressionParameters ZSTD_getCParamsFromCDict (const ZSTD_CDict *cdict)
size_t ZSTD_compressBegin_advanced_internal (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, unsigned long long pledgedSrcSize)
size_t ZSTD_compress_advanced_internal (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, const ZSTD_CCtx_params *params)
size_t ZSTD_writeLastEmptyBlock (void *dst, size_t dstCapacity)
void ZSTD_referenceExternalSequences (ZSTD_CCtx *cctx, rawSeq *seq, size_t nbSeq)
U32 ZSTD_cycleLog (U32 hashLog, ZSTD_strategy strat)
void ZSTD_CCtx_trace (ZSTD_CCtx *cctx, size_t extraCSize)
size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim (ZSTD_CCtx *cctx, ZSTD_sequencePosition *seqPos, const ZSTD_Sequence *const inSeqs, size_t inSeqsSize, const void *src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch)
size_t ZSTD_copySequencesToSeqStoreNoBlockDelim (ZSTD_CCtx *cctx, ZSTD_sequencePosition *seqPos, const ZSTD_Sequence *const inSeqs, size_t inSeqsSize, const void *src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch)
MEM_STATIC int ZSTD_hasExtSeqProd (const ZSTD_CCtx_params *params)
size_t ZSTD_compressBegin_usingCDict_deprecated (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict)
size_t ZSTD_compressContinue_public (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
size_t ZSTD_compressEnd_public (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
size_t ZSTD_compressBlock_deprecated (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
symbolEncodingType_e ZSTD_selectEncodingType (FSE_repeat *repeatMode, unsigned const *count, unsigned const max, size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, FSE_CTable const *prevCTable, short const *defaultNorm, U32 defaultNormLog, ZSTD_defaultPolicy_e const isDefaultAllowed, ZSTD_strategy const strategy)
size_t ZSTD_buildCTable (void *dst, size_t dstCapacity, FSE_CTable *nextCTable, U32 FSELog, symbolEncodingType_e type, unsigned *count, U32 max, const BYTE *codeTable, size_t nbSeq, const S16 *defaultNorm, U32 defaultNormLog, U32 defaultMax, const FSE_CTable *prevCTable, size_t prevCTableSize, void *entropyWorkspace, size_t entropyWorkspaceSize)
size_t ZSTD_encodeSequences (void *dst, size_t dstCapacity, FSE_CTable const *CTable_MatchLength, BYTE const *mlCodeTable, FSE_CTable const *CTable_OffsetBits, BYTE const *ofCodeTable, FSE_CTable const *CTable_LitLength, BYTE const *llCodeTable, seqDef const *sequences, size_t nbSeq, int longOffsets, int bmi2)
size_t ZSTD_fseBitCost (FSE_CTable const *ctable, unsigned const *count, unsigned const max)
size_t ZSTD_crossEntropyCost (short const *norm, unsigned accuracyLog, unsigned const *count, unsigned const max)
size_t ZSTD_noCompressLiterals (void *dst, size_t dstCapacity, const void *src, size_t srcSize)
size_t ZSTD_compressRleLiteralsBlock (void *dst, size_t dstCapacity, const void *src, size_t srcSize)
size_t ZSTD_compressLiterals (void *dst, size_t dstCapacity, const void *src, size_t srcSize, void *entropyWorkspace, size_t entropyWorkspaceSize, const ZSTD_hufCTables_t *prevHuf, ZSTD_hufCTables_t *nextHuf, ZSTD_strategy strategy, int disableLiteralCompression, int suspectUncompressible, int bmi2)
void ZSTD_fillHashTable (ZSTD_matchState_t *ms, void const *end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp)
size_t ZSTD_compressBlock_fast (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_fast_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_fast_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
void ZSTD_fillDoubleHashTable (ZSTD_matchState_t *ms, void const *end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp)
size_t ZSTD_compressBlock_doubleFast (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_doubleFast_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_doubleFast_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
U32 ZSTD_insertAndFindFirstIndex (ZSTD_matchState_t *ms, const BYTE *ip)
void ZSTD_row_update (ZSTD_matchState_t *const ms, const BYTE *ip)
void ZSTD_dedicatedDictSearch_lazy_loadDictionary (ZSTD_matchState_t *ms, const BYTE *const ip)
void ZSTD_preserveUnsortedMark (U32 *const table, U32 const size, U32 const reducerValue)
size_t ZSTD_compressBlock_greedy (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_dictMatchState_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_dedicatedDictSearch (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_greedy_extDict_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_dictMatchState_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_dedicatedDictSearch (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy_extDict_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2 (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_dictMatchState_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_lazy2_extDict_row (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btlazy2 (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btlazy2_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btlazy2_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
void ZSTD_updateTree (ZSTD_matchState_t *ms, const BYTE *ip, const BYTE *iend)
size_t ZSTD_compressBlock_btopt (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btopt_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btopt_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btultra (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btultra_dictMatchState (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btultra_extDict (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
size_t ZSTD_compressBlock_btultra2 (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize)
void ZSTD_ldm_fillHashTable (ldmState_t *state, const BYTE *ip, const BYTE *iend, ldmParams_t const *params)
size_t ZSTD_ldm_generateSequences (ldmState_t *ldms, rawSeqStore_t *sequences, ldmParams_t const *params, void const *src, size_t srcSize)
size_t ZSTD_ldm_blockCompress (rawSeqStore_t *rawSeqStore, ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const *src, size_t srcSize)
void ZSTD_ldm_skipSequences (rawSeqStore_t *rawSeqStore, size_t srcSize, U32 const minMatch)
void ZSTD_ldm_skipRawSeqStoreBytes (rawSeqStore_t *rawSeqStore, size_t nbBytes)
size_t ZSTD_ldm_getTableSize (ldmParams_t params)
size_t ZSTD_ldm_getMaxNbSeq (ldmParams_t params, size_t maxChunkSize)
void ZSTD_ldm_adjustParameters (ldmParams_t *params, ZSTD_compressionParameters const *cParams)
size_t ZSTD_compressSuperBlock (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, void const *src, size_t srcSize, unsigned lastBlock)
static void ZSTD_initCCtx (ZSTD_CCtx *cctx, ZSTD_customMem memManager)
static void ZSTD_clearAllDicts (ZSTD_CCtx *cctx)
static size_t ZSTD_sizeof_localDict (ZSTD_localDict dict)
static void ZSTD_freeCCtxContent (ZSTD_CCtx *cctx)
static size_t ZSTD_sizeof_mtctx (const ZSTD_CCtx *cctx)
static int ZSTD_rowMatchFinderSupported (const ZSTD_strategy strategy)
static int ZSTD_rowMatchFinderUsed (const ZSTD_strategy strategy, const ZSTD_paramSwitch_e mode)
static ZSTD_paramSwitch_e ZSTD_resolveRowMatchFinderMode (ZSTD_paramSwitch_e mode, const ZSTD_compressionParameters *const cParams)
static ZSTD_paramSwitch_e ZSTD_resolveBlockSplitterMode (ZSTD_paramSwitch_e mode, const ZSTD_compressionParameters *const cParams)
static int ZSTD_allocateChainTable (const ZSTD_strategy strategy, const ZSTD_paramSwitch_e useRowMatchFinder, const U32 forDDSDict)
static ZSTD_paramSwitch_e ZSTD_resolveEnableLdm (ZSTD_paramSwitch_e mode, const ZSTD_compressionParameters *const cParams)
static int ZSTD_resolveExternalSequenceValidation (int mode)
static size_t ZSTD_resolveMaxBlockSize (size_t maxBlockSize)
static ZSTD_paramSwitch_e ZSTD_resolveExternalRepcodeSearch (ZSTD_paramSwitch_e value, int cLevel)
static int ZSTD_CDictIndicesAreTagged (const ZSTD_compressionParameters *const cParams)
static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams (ZSTD_compressionParameters cParams)
static ZSTD_CCtx_params * ZSTD_createCCtxParams_advanced (ZSTD_customMem customMem)
static void ZSTD_CCtxParams_init_internal (ZSTD_CCtx_params *cctxParams, const ZSTD_parameters *params, int compressionLevel)
static void ZSTD_CCtxParams_setZstdParams (ZSTD_CCtx_params *cctxParams, const ZSTD_parameters *params)
static size_t ZSTD_cParam_clampBounds (ZSTD_cParameter cParam, int *value)
static int ZSTD_isUpdateAuthorized (ZSTD_cParameter param)
static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams (int const compressionLevel, size_t const dictSize)
static int ZSTD_dedicatedDictSearch_isSupported (const ZSTD_compressionParameters *cParams)
static void ZSTD_dedicatedDictSearch_revertCParams (ZSTD_compressionParameters *cParams)
static size_t ZSTD_initLocalDict (ZSTD_CCtx *cctx)
static ZSTD_compressionParameters ZSTD_clampCParams (ZSTD_compressionParameters cParams)
static U32 ZSTD_dictAndWindowLog (U32 windowLog, U64 srcSize, U64 dictSize)
static ZSTD_compressionParameters ZSTD_adjustCParams_internal (ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize, ZSTD_cParamMode_e mode, ZSTD_paramSwitch_e useRowMatchFinder)
static ZSTD_compressionParameters ZSTD_getCParams_internal (int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
static ZSTD_parameters ZSTD_getParams_internal (int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
static void ZSTD_overrideCParams (ZSTD_compressionParameters *cParams, const ZSTD_compressionParameters *overrides)
static size_t ZSTD_sizeof_matchState (const ZSTD_compressionParameters *const cParams, const ZSTD_paramSwitch_e useRowMatchFinder, const U32 enableDedicatedDictSearch, const U32 forCCtx)
static size_t ZSTD_maxNbSeq (size_t blockSize, unsigned minMatch, int useSequenceProducer)
static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal (const ZSTD_compressionParameters *cParams, const ldmParams_t *ldmParams, const int isStatic, const ZSTD_paramSwitch_e useRowMatchFinder, const size_t buffInSize, const size_t buffOutSize, const U64 pledgedSrcSize, int useSequenceProducer, size_t maxBlockSize)
static size_t ZSTD_estimateCCtxSize_internal (int compressionLevel)
static size_t ZSTD_estimateCStreamSize_internal (int compressionLevel)
static void ZSTD_assertEqualCParams (ZSTD_compressionParameters cParams1, ZSTD_compressionParameters cParams2)
static void ZSTD_invalidateMatchState (ZSTD_matchState_t *ms)
static U64 ZSTD_bitmix (U64 val, U64 len)
static void ZSTD_advanceHashSalt (ZSTD_matchState_t *ms)
static size_t ZSTD_reset_matchState (ZSTD_matchState_t *ms, ZSTD_cwksp *ws, const ZSTD_compressionParameters *cParams, const ZSTD_paramSwitch_e useRowMatchFinder, const ZSTD_compResetPolicy_e crp, const ZSTD_indexResetPolicy_e forceResetIndex, const ZSTD_resetTarget_e forWho)
static int ZSTD_indexTooCloseToMax (ZSTD_window_t w)
static int ZSTD_dictTooBig (size_t const loadedDictSize)
static size_t ZSTD_resetCCtx_internal (ZSTD_CCtx *zc, ZSTD_CCtx_params const *params, U64 const pledgedSrcSize, size_t const loadedDictSize, ZSTD_compResetPolicy_e const crp, ZSTD_buffered_policy_e const zbuff)
static int ZSTD_shouldAttachDict (const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, U64 pledgedSrcSize)
static size_t ZSTD_resetCCtx_byAttachingCDict (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict, ZSTD_CCtx_params params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
static void ZSTD_copyCDictTableIntoCCtx (U32 *dst, U32 const *src, size_t tableSize, ZSTD_compressionParameters const *cParams)
static size_t ZSTD_resetCCtx_byCopyingCDict (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict, ZSTD_CCtx_params params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
static size_t ZSTD_resetCCtx_usingCDict (ZSTD_CCtx *cctx, const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
static size_t ZSTD_copyCCtx_internal (ZSTD_CCtx *dstCCtx, const ZSTD_CCtx *srcCCtx, ZSTD_frameParameters fParams, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
FORCE_INLINE_TEMPLATE void ZSTD_reduceTable_internal (U32 *const table, U32 const size, U32 const reducerValue, int const preserveMark)
static void ZSTD_reduceTable (U32 *const table, U32 const size, U32 const reducerValue)
static void ZSTD_reduceTable_btlazy2 (U32 *const table, U32 const size, U32 const reducerValue)
static void ZSTD_reduceIndex (ZSTD_matchState_t *ms, ZSTD_CCtx_params const *params, const U32 reducerValue)
static int ZSTD_useTargetCBlockSize (const ZSTD_CCtx_params *cctxParams)
static int ZSTD_blockSplitterEnabled (ZSTD_CCtx_params *cctxParams)
static ZSTD_symbolEncodingTypeStats_t ZSTD_buildSequencesStatistics (const seqStore_t *seqStorePtr, size_t nbSeq, const ZSTD_fseCTables_t *prevEntropy, ZSTD_fseCTables_t *nextEntropy, BYTE *dst, const BYTE *const dstEnd, ZSTD_strategy strategy, unsigned *countWorkspace, void *entropyWorkspace, size_t entropyWkspSize)
MEM_STATIC size_t ZSTD_entropyCompressSeqStore_internal (const seqStore_t *seqStorePtr, const ZSTD_entropyCTables_t *prevEntropy, ZSTD_entropyCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, void *entropyWorkspace, size_t entropyWkspSize, const int bmi2)
MEM_STATIC size_t ZSTD_entropyCompressSeqStore (const seqStore_t *seqStorePtr, const ZSTD_entropyCTables_t *prevEntropy, ZSTD_entropyCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, size_t srcSize, void *entropyWorkspace, size_t entropyWkspSize, int bmi2)
static void ZSTD_storeLastLiterals (seqStore_t *seqStorePtr, const BYTE *anchor, size_t lastLLSize)
static size_t ZSTD_postProcessSequenceProducerResult (ZSTD_Sequence *outSeqs, size_t nbExternalSeqs, size_t outSeqsCapacity, size_t srcSize)
static size_t ZSTD_fastSequenceLengthSum (ZSTD_Sequence const *seqBuf, size_t seqBufSize)
static size_t ZSTD_buildSeqStore (ZSTD_CCtx *zc, const void *src, size_t srcSize)
static size_t ZSTD_copyBlockSequences (SeqCollector *seqCollector, const seqStore_t *seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])
static int ZSTD_isRLE (const BYTE *src, size_t length)
static int ZSTD_maybeRLE (seqStore_t const *seqStore)
static void ZSTD_blockState_confirmRepcodesAndEntropyTables (ZSTD_blockState_t *const bs)
static void writeBlockHeader (void *op, size_t cSize, size_t blockSize, U32 lastBlock)
static size_t ZSTD_buildBlockEntropyStats_literals (void *const src, size_t srcSize, const ZSTD_hufCTables_t *prevHuf, ZSTD_hufCTables_t *nextHuf, ZSTD_hufCTablesMetadata_t *hufMetadata, const int literalsCompressionIsDisabled, void *workspace, size_t wkspSize, int hufFlags)
static ZSTD_symbolEncodingTypeStats_t ZSTD_buildDummySequencesStatistics (ZSTD_fseCTables_t *nextEntropy)
static size_t ZSTD_buildBlockEntropyStats_sequences (const seqStore_t *seqStorePtr, const ZSTD_fseCTables_t *prevEntropy, ZSTD_fseCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, ZSTD_fseCTablesMetadata_t *fseMetadata, void *workspace, size_t wkspSize)
static size_t ZSTD_estimateBlockSize_literal (const BYTE *literals, size_t litSize, const ZSTD_hufCTables_t *huf, const ZSTD_hufCTablesMetadata_t *hufMetadata, void *workspace, size_t wkspSize, int writeEntropy)
static size_t ZSTD_estimateBlockSize_symbolType (symbolEncodingType_e type, const BYTE *codeTable, size_t nbSeq, unsigned maxCode, const FSE_CTable *fseCTable, const U8 *additionalBits, short const *defaultNorm, U32 defaultNormLog, U32 defaultMax, void *workspace, size_t wkspSize)
static size_t ZSTD_estimateBlockSize_sequences (const BYTE *ofCodeTable, const BYTE *llCodeTable, const BYTE *mlCodeTable, size_t nbSeq, const ZSTD_fseCTables_t *fseTables, const ZSTD_fseCTablesMetadata_t *fseMetadata, void *workspace, size_t wkspSize, int writeEntropy)
static size_t ZSTD_estimateBlockSize (const BYTE *literals, size_t litSize, const BYTE *ofCodeTable, const BYTE *llCodeTable, const BYTE *mlCodeTable, size_t nbSeq, const ZSTD_entropyCTables_t *entropy, const ZSTD_entropyCTablesMetadata_t *entropyMetadata, void *workspace, size_t wkspSize, int writeLitEntropy, int writeSeqEntropy)
static size_t ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize (seqStore_t *seqStore, ZSTD_CCtx *zc)
static size_t ZSTD_countSeqStoreLiteralsBytes (const seqStore_t *const seqStore)
static size_t ZSTD_countSeqStoreMatchBytes (const seqStore_t *const seqStore)
static void ZSTD_deriveSeqStoreChunk (seqStore_t *resultSeqStore, const seqStore_t *originalSeqStore, size_t startIdx, size_t endIdx)
static U32 ZSTD_resolveRepcodeToRawOffset (const U32 rep[ZSTD_REP_NUM], const U32 offBase, const U32 ll0)
static void ZSTD_seqStore_resolveOffCodes (repcodes_t *const dRepcodes, repcodes_t *const cRepcodes, const seqStore_t *const seqStore, U32 const nbSeq)
static size_t ZSTD_compressSeqStore_singleBlock (ZSTD_CCtx *zc, const seqStore_t *const seqStore, repcodes_t *const dRep, repcodes_t *const cRep, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastBlock, U32 isPartition)
static void ZSTD_deriveBlockSplitsHelper (seqStoreSplits *splits, size_t startIdx, size_t endIdx, ZSTD_CCtx *zc, const seqStore_t *origSeqStore)
static size_t ZSTD_deriveBlockSplits (ZSTD_CCtx *zc, U32 partitions[], U32 nbSeq)
static size_t ZSTD_compressBlock_splitBlock_internal (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t blockSize, U32 lastBlock, U32 nbSeq)
static size_t ZSTD_compressBlock_splitBlock (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastBlock)
static size_t ZSTD_compressBlock_internal (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 frame)
static size_t ZSTD_compressBlock_targetCBlockSize_body (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const size_t bss, U32 lastBlock)
static size_t ZSTD_compressBlock_targetCBlockSize (ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastBlock)
static void ZSTD_overflowCorrectIfNeeded (ZSTD_matchState_t *ms, ZSTD_cwksp *ws, ZSTD_CCtx_params const *params, void const *ip, void const *iend)
static size_t ZSTD_compress_frameChunk (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastFrameChunk)
static size_t ZSTD_writeFrameHeader (void *dst, size_t dstCapacity, const ZSTD_CCtx_params *params, U64 pledgedSrcSize, U32 dictID)
static size_t ZSTD_compressContinue_internal (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 frame, U32 lastFrameChunk)
static size_t ZSTD_getBlockSize_deprecated (const ZSTD_CCtx *cctx)
static size_t ZSTD_loadDictionaryContent (ZSTD_matchState_t *ms, ldmState_t *ls, ZSTD_cwksp *ws, ZSTD_CCtx_params const *params, const void *src, size_t srcSize, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp)
static FSE_repeat ZSTD_dictNCountRepeat (short *normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
static size_t ZSTD_loadZstdDictionary (ZSTD_compressedBlockState_t *bs, ZSTD_matchState_t *ms, ZSTD_cwksp *ws, ZSTD_CCtx_params const *params, const void *dict, size_t dictSize, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, void *workspace)
static size_t ZSTD_compress_insertDictionary (ZSTD_compressedBlockState_t *bs, ZSTD_matchState_t *ms, ldmState_t *ls, ZSTD_cwksp *ws, const ZSTD_CCtx_params *params, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, void *workspace)
static size_t ZSTD_compressBegin_internal (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
static size_t ZSTD_compressBegin_usingDict_deprecated (ZSTD_CCtx *cctx, const void *dict, size_t dictSize, int compressionLevel)
static size_t ZSTD_writeEpilogue (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity)
size_t ZSTD_compress (void *dst, size_t dstCapacity, const void *src, size_t srcSize, int compressionLevel)
static size_t ZSTD_initCDict_internal (ZSTD_CDict *cdict, const void *dictBuffer, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, ZSTD_CCtx_params params)
static ZSTD_CDict * ZSTD_createCDict_advanced_internal (size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_compressionParameters cParams, ZSTD_paramSwitch_e useRowMatchFinder, U32 enableDedicatedDictSearch, ZSTD_customMem customMem)
static size_t ZSTD_compressBegin_usingCDict_internal (ZSTD_CCtx *const cctx, const ZSTD_CDict *const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
static size_t ZSTD_compress_usingCDict_internal (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict, ZSTD_frameParameters fParams)
static ZSTD_cParamMode_e ZSTD_getCParamMode (ZSTD_CDict const *cdict, ZSTD_CCtx_params const *params, U64 pledgedSrcSize)
static size_t ZSTD_nextInputSizeHint (const ZSTD_CCtx *cctx)
static size_t ZSTD_compressStream_generic (ZSTD_CStream *zcs, ZSTD_outBuffer *output, ZSTD_inBuffer *input, ZSTD_EndDirective const flushMode)
static size_t ZSTD_nextInputSizeHint_MTorST (const ZSTD_CCtx *cctx)
static void ZSTD_setBufferExpectations (ZSTD_CCtx *cctx, const ZSTD_outBuffer *output, const ZSTD_inBuffer *input)
static size_t ZSTD_checkBufferStability (ZSTD_CCtx const *cctx, ZSTD_outBuffer const *output, ZSTD_inBuffer const *input, ZSTD_EndDirective endOp)
static size_t ZSTD_CCtx_init_compressStream2 (ZSTD_CCtx *cctx, ZSTD_EndDirective endOp, size_t inSize)
size_t ZSTD_compress2 (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
static size_t ZSTD_validateSequence (U32 offCode, U32 matchLength, U32 minMatch, size_t posInSrc, U32 windowLog, size_t dictSize, int useSequenceProducer)
static U32 ZSTD_finalizeOffBase (U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0)
static ZSTD_sequenceCopier ZSTD_selectSequenceCopier (ZSTD_sequenceFormat_e mode)
static size_t blockSize_explicitDelimiter (const ZSTD_Sequence *inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos)
static size_t blockSize_noDelimiter (size_t blockSize, size_t remaining)
static size_t determine_blockSize (ZSTD_sequenceFormat_e mode, size_t blockSize, size_t remaining, const ZSTD_Sequence *inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos)
static size_t ZSTD_compressSequences_internal (ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const ZSTD_Sequence *inSeqs, size_t inSeqsSize, const void *src, size_t srcSize)
static ZSTD_inBuffer inBuffer_forEndFlush (const ZSTD_CStream *zcs)
static U64 ZSTD_getCParamRowSize (U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
static int allBytesIdentical (const void *src, size_t srcSize)
static size_t ZSTD_minLiteralsToCompress (ZSTD_strategy strategy, HUF_repeat huf_repeat)
static unsigned ZSTD_getFSEMaxSymbolValue (FSE_CTable const *ctable)
static unsigned ZSTD_useLowProbCount (size_t const nbSeq)
static size_t ZSTD_NCountCost (unsigned const *count, unsigned const max, size_t const nbSeq, unsigned const FSELog)
static size_t ZSTD_entropyCost (unsigned const *count, unsigned const max, size_t const total)
FORCE_INLINE_TEMPLATE size_t ZSTD_encodeSequences_body (void *dst, size_t dstCapacity, FSE_CTable const *CTable_MatchLength, BYTE const *mlCodeTable, FSE_CTable const *CTable_OffsetBits, BYTE const *ofCodeTable, FSE_CTable const *CTable_LitLength, BYTE const *llCodeTable, seqDef const *sequences, size_t nbSeq, int longOffsets)
static size_t ZSTD_encodeSequences_default (void *dst, size_t dstCapacity, FSE_CTable const *CTable_MatchLength, BYTE const *mlCodeTable, FSE_CTable const *CTable_OffsetBits, BYTE const *ofCodeTable, FSE_CTable const *CTable_LitLength, BYTE const *llCodeTable, seqDef const *sequences, size_t nbSeq, int longOffsets)
static size_t ZSTD_compressSubBlock_literal (const HUF_CElt *hufTable, const ZSTD_hufCTablesMetadata_t *hufMetadata, const BYTE *literals, size_t litSize, void *dst, size_t dstSize, const int bmi2, int writeEntropy, int *entropyWritten)
static size_t ZSTD_seqDecompressedSize (seqStore_t const *seqStore, const seqDef *sequences, size_t nbSeqs, size_t litSize, int lastSubBlock)
static size_t ZSTD_compressSubBlock_sequences (const ZSTD_fseCTables_t *fseTables, const ZSTD_fseCTablesMetadata_t *fseMetadata, const seqDef *sequences, size_t nbSeq, const BYTE *llCode, const BYTE *mlCode, const BYTE *ofCode, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, const int bmi2, int writeEntropy, int *entropyWritten)
static size_t ZSTD_compressSubBlock (const ZSTD_entropyCTables_t *entropy, const ZSTD_entropyCTablesMetadata_t *entropyMetadata, const seqDef *sequences, size_t nbSeq, const BYTE *literals, size_t litSize, const BYTE *llCode, const BYTE *mlCode, const BYTE *ofCode, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, const int bmi2, int writeLitEntropy, int writeSeqEntropy, int *litEntropyWritten, int *seqEntropyWritten, U32 lastBlock)
static size_t ZSTD_estimateSubBlockSize_literal (const BYTE *literals, size_t litSize, const ZSTD_hufCTables_t *huf, const ZSTD_hufCTablesMetadata_t *hufMetadata, void *workspace, size_t wkspSize, int writeEntropy)
static size_t ZSTD_estimateSubBlockSize_symbolType (symbolEncodingType_e type, const BYTE *codeTable, unsigned maxCode, size_t nbSeq, const FSE_CTable *fseCTable, const U8 *additionalBits, short const *defaultNorm, U32 defaultNormLog, U32 defaultMax, void *workspace, size_t wkspSize)
static size_t ZSTD_estimateSubBlockSize_sequences (const BYTE *ofCodeTable, const BYTE *llCodeTable, const BYTE *mlCodeTable, size_t nbSeq, const ZSTD_fseCTables_t *fseTables, const ZSTD_fseCTablesMetadata_t *fseMetadata, void *workspace, size_t wkspSize, int writeEntropy)
static EstimatedBlockSize ZSTD_estimateSubBlockSize (const BYTE *literals, size_t litSize, const BYTE *ofCodeTable, const BYTE *llCodeTable, const BYTE *mlCodeTable, size_t nbSeq, const ZSTD_entropyCTables_t *entropy, const ZSTD_entropyCTablesMetadata_t *entropyMetadata, void *workspace, size_t wkspSize, int writeLitEntropy, int writeSeqEntropy)
static int ZSTD_needSequenceEntropyTables (ZSTD_fseCTablesMetadata_t const *fseMetadata)
static size_t countLiterals (seqStore_t const *seqStore, const seqDef *sp, size_t seqCount)
static size_t sizeBlockSequences (const seqDef *sp, size_t nbSeqs, size_t targetBudget, size_t avgLitCost, size_t avgSeqCost, int firstSubBlock)
static size_t ZSTD_compressSubBlock_multi (const seqStore_t *seqStorePtr, const ZSTD_compressedBlockState_t *prevCBlock, ZSTD_compressedBlockState_t *nextCBlock, const ZSTD_entropyCTablesMetadata_t *entropyMetadata, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const int bmi2, U32 lastBlock, void *workspace, size_t wkspSize)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_fillDoubleHashTableForCDict (ZSTD_matchState_t *ms, void const *end, ZSTD_dictTableLoadMethod_e dtlm)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_fillDoubleHashTableForCCtx (ZSTD_matchState_t *ms, void const *end, ZSTD_dictTableLoadMethod_e dtlm)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_noDict_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_extDict_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_fillHashTableForCDict (ZSTD_matchState_t *ms, const void *const end, ZSTD_dictTableLoadMethod_e dtlm)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_fillHashTableForCCtx (ZSTD_matchState_t *ms, const void *const end, ZSTD_dictTableLoadMethod_e dtlm)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_noDict_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls, U32 const hasStep)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_dictMatchState_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls, U32 const hasStep)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_extDict_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], void const *src, size_t srcSize, U32 const mls, U32 const hasStep)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_updateDUBT (ZSTD_matchState_t *ms, const BYTE *ip, const BYTE *iend, U32 mls)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_insertDUBT1 (const ZSTD_matchState_t *ms, U32 curr, const BYTE *inputEnd, U32 nbCompares, U32 btLow, const ZSTD_dictMode_e dictMode)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_DUBT_findBetterDictMatch (const ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iend, size_t *offsetPtr, size_t bestLength, U32 nbCompares, U32 const mls, const ZSTD_dictMode_e dictMode)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_DUBT_findBestMatch (ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iend, size_t *offBasePtr, U32 const mls, const ZSTD_dictMode_e dictMode)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_BtFindBestMatch (ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iLimit, size_t *offBasePtr, const U32 mls, const ZSTD_dictMode_e dictMode)
FORCE_INLINE_TEMPLATE size_t ZSTD_dedicatedDictSearch_lazy_search (size_t *offsetPtr, size_t ml, U32 nbAttempts, const ZSTD_matchState_t *const dms, const BYTE *const ip, const BYTE *const iLimit, const BYTE *const prefixStart, const U32 curr, const U32 dictLimit, const size_t ddsIdx)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertAndFindFirstIndex_internal (ZSTD_matchState_t *ms, const ZSTD_compressionParameters *const cParams, const BYTE *ip, U32 const mls, U32 const lazySkipping)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_HcFindBestMatch (ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 mls, const ZSTD_dictMode_e dictMode)
MEM_STATIC U32 ZSTD_VecMask_next (ZSTD_VecMask val)
FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextIndex (BYTE *const tagRow, U32 const rowMask)
MEM_STATIC int ZSTD_isAligned (void const *ptr, size_t align)
FORCE_INLINE_TEMPLATE void ZSTD_row_prefetch (U32 const *hashTable, BYTE const *tagTable, U32 const relRow, U32 const rowLog)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_row_fillHashCache (ZSTD_matchState_t *ms, const BYTE *base, U32 const rowLog, U32 const mls, U32 idx, const BYTE *const iLimit)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_row_nextCachedHash (U32 *cache, U32 const *hashTable, BYTE const *tagTable, BYTE const *base, U32 idx, U32 const hashLog, U32 const rowLog, U32 const mls, U64 const hashSalt)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_row_update_internalImpl (ZSTD_matchState_t *ms, U32 updateStartIdx, U32 const updateEndIdx, U32 const mls, U32 const rowLog, U32 const rowMask, U32 const useCache)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_row_update_internal (ZSTD_matchState_t *ms, const BYTE *ip, U32 const mls, U32 const rowLog, U32 const rowMask, U32 const useCache)
FORCE_INLINE_TEMPLATE U32 ZSTD_row_matchMaskGroupWidth (const U32 rowEntries)
FORCE_INLINE_TEMPLATE ZSTD_VecMask ZSTD_row_getMatchMask (const BYTE *const tagRow, const BYTE tag, const U32 headGrouped, const U32 rowEntries)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_RowFindBestMatch (ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 mls, const ZSTD_dictMode_e dictMode, const U32 rowLog)
FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax (ZSTD_matchState_t *ms, const BYTE *ip, const BYTE *iend, size_t *offsetPtr, U32 const mls, U32 const rowLog, searchMethod_e const searchMethod, ZSTD_dictMode_e const dictMode)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth, ZSTD_dictMode_e const dictMode)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_extDict_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth)
static void ZSTD_ldm_gear_init (ldmRollingHashState_t *state, ldmParams_t const *params)
static void ZSTD_ldm_gear_reset (ldmRollingHashState_t *state, BYTE const *data, size_t minMatchLength)
static size_t ZSTD_ldm_gear_feed (ldmRollingHashState_t *state, BYTE const *data, size_t size, size_t *splits, unsigned *numSplits)
static ldmEntry_t * ZSTD_ldm_getBucket (ldmState_t *ldmState, size_t hash, ldmParams_t const ldmParams)
static void ZSTD_ldm_insertEntry (ldmState_t *ldmState, size_t const hash, const ldmEntry_t entry, ldmParams_t const ldmParams)
static size_t ZSTD_ldm_countBackwardsMatch (const BYTE *pIn, const BYTE *pAnchor, const BYTE *pMatch, const BYTE *pMatchBase)
static size_t ZSTD_ldm_countBackwardsMatch_2segments (const BYTE *pIn, const BYTE *pAnchor, const BYTE *pMatch, const BYTE *pMatchBase, const BYTE *pExtDictStart, const BYTE *pExtDictEnd)
static size_t ZSTD_ldm_fillFastTables (ZSTD_matchState_t *ms, void const *end)
static void ZSTD_ldm_limitTableUpdate (ZSTD_matchState_t *ms, const BYTE *anchor)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_ldm_generateSequences_internal (ldmState_t *ldmState, rawSeqStore_t *rawSeqStore, ldmParams_t const *params, void const *src, size_t srcSize)
static void ZSTD_ldm_reduceTable (ldmEntry_t *const table, U32 const size, U32 const reducerValue)
static rawSeq maybeSplitSequence (rawSeqStore_t *rawSeqStore, U32 const remaining, U32 const minMatch)
MEM_STATIC U32 ZSTD_bitWeight (U32 stat)
MEM_STATIC U32 ZSTD_fracWeight (U32 rawStat)
static int ZSTD_compressedLiterals (optState_t const *const optPtr)
static void ZSTD_setBasePrices (optState_t *optPtr, int optLevel)
static U32 sum_u32 (const unsigned table[], size_t nbElts)
static U32 ZSTD_downscaleStats (unsigned *table, U32 lastEltIndex, U32 shift, base_directive_e base1)
static U32 ZSTD_scaleStats (unsigned *table, U32 lastEltIndex, U32 logTarget)
static void ZSTD_rescaleFreqs (optState_t *const optPtr, const BYTE *const src, size_t const srcSize, int const optLevel)
static U32 ZSTD_rawLiteralsCost (const BYTE *const literals, U32 const litLength, const optState_t *const optPtr, int optLevel)
static U32 ZSTD_litLengthPrice (U32 const litLength, const optState_t *const optPtr, int optLevel)
FORCE_INLINE_TEMPLATE U32 ZSTD_getMatchPrice (U32 const offBase, U32 const matchLength, const optState_t *const optPtr, int const optLevel)
static void ZSTD_updateStats (optState_t *const optPtr, U32 litLength, const BYTE *literals, U32 offBase, U32 matchLength)
MEM_STATIC U32 ZSTD_readMINMATCH (const void *memPtr, U32 length)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t *ms, U32 *nextToUpdate3, const BYTE *const ip)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertBt1 (const ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iend, U32 const target, U32 const mls, const int extDict)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_updateTree_internal (ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iend, const U32 mls, const ZSTD_dictMode_e dictMode)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertBtAndGetAllMatches (ZSTD_match_t *matches, ZSTD_matchState_t *ms, U32 *nextToUpdate3, const BYTE *const ip, const BYTE *const iLimit, const ZSTD_dictMode_e dictMode, const U32 rep[ZSTD_REP_NUM], const U32 ll0, const U32 lengthToBeat, const U32 mls)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_btGetAllMatches_internal (ZSTD_match_t *matches, ZSTD_matchState_t *ms, U32 *nextToUpdate3, const BYTE *ip, const BYTE *const iHighLimit, const U32 rep[ZSTD_REP_NUM], U32 const ll0, U32 const lengthToBeat, const ZSTD_dictMode_e dictMode, const U32 mls)
static ZSTD_getAllMatchesFn ZSTD_selectBtGetAllMatches (ZSTD_matchState_t const *ms, ZSTD_dictMode_e const dictMode)
static void ZSTD_optLdm_skipRawSeqStoreBytes (rawSeqStore_t *rawSeqStore, size_t nbBytes)
static void ZSTD_opt_getNextMatchAndUpdateSeqStore (ZSTD_optLdm_t *optLdm, U32 currPosInBlock, U32 blockBytesRemaining)
static void ZSTD_optLdm_maybeAddMatch (ZSTD_match_t *matches, U32 *nbMatches, const ZSTD_optLdm_t *optLdm, U32 currPosInBlock)
static void ZSTD_optLdm_processMatchCandidate (ZSTD_optLdm_t *optLdm, ZSTD_match_t *matches, U32 *nbMatches, U32 currPosInBlock, U32 remainingBytes)
FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_opt_generic (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize, const int optLevel, const ZSTD_dictMode_e dictMode)
static size_t ZSTD_compressBlock_opt0 (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize, const ZSTD_dictMode_e dictMode)
static size_t ZSTD_compressBlock_opt2 (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize, const ZSTD_dictMode_e dictMode)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_initStats_ultra (ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], const void *src, size_t srcSize)
static void ZSTDMT_freeBufferPool (ZSTDMT_bufferPool *bufPool)
static ZSTDMT_bufferPool * ZSTDMT_createBufferPool (unsigned maxNbBuffers, ZSTD_customMem cMem)
static size_t ZSTDMT_sizeof_bufferPool (ZSTDMT_bufferPool *bufPool)
static void ZSTDMT_setBufferSize (ZSTDMT_bufferPool *const bufPool, size_t const bSize)
static ZSTDMT_bufferPool * ZSTDMT_expandBufferPool (ZSTDMT_bufferPool *srcBufPool, unsigned maxNbBuffers)
static buffer_t ZSTDMT_getBuffer (ZSTDMT_bufferPool *bufPool)
static void ZSTDMT_releaseBuffer (ZSTDMT_bufferPool *bufPool, buffer_t buf)
static size_t ZSTDMT_sizeof_seqPool (ZSTDMT_seqPool *seqPool)
static rawSeqStore_t bufferToSeq (buffer_t buffer)
static buffer_t seqToBuffer (rawSeqStore_t seq)
static rawSeqStore_t ZSTDMT_getSeq (ZSTDMT_seqPool *seqPool)
static void ZSTDMT_releaseSeq (ZSTDMT_seqPool *seqPool, rawSeqStore_t seq)
static void ZSTDMT_setNbSeq (ZSTDMT_seqPool *const seqPool, size_t const nbSeq)
static ZSTDMT_seqPool * ZSTDMT_createSeqPool (unsigned nbWorkers, ZSTD_customMem cMem)
static void ZSTDMT_freeSeqPool (ZSTDMT_seqPool *seqPool)
static ZSTDMT_seqPool * ZSTDMT_expandSeqPool (ZSTDMT_seqPool *pool, U32 nbWorkers)
static void ZSTDMT_freeCCtxPool (ZSTDMT_CCtxPool *pool)
static ZSTDMT_CCtxPool * ZSTDMT_createCCtxPool (int nbWorkers, ZSTD_customMem cMem)
static ZSTDMT_CCtxPool * ZSTDMT_expandCCtxPool (ZSTDMT_CCtxPool *srcPool, int nbWorkers)
static size_t ZSTDMT_sizeof_CCtxPool (ZSTDMT_CCtxPool *cctxPool)
static ZSTD_CCtx * ZSTDMT_getCCtx (ZSTDMT_CCtxPool *cctxPool)
static void ZSTDMT_releaseCCtx (ZSTDMT_CCtxPool *pool, ZSTD_CCtx *cctx)
static int ZSTDMT_serialState_reset (serialState_t *serialState, ZSTDMT_seqPool *seqPool, ZSTD_CCtx_params params, size_t jobSize, const void *dict, size_t const dictSize, ZSTD_dictContentType_e dictContentType)
static int ZSTDMT_serialState_init (serialState_t *serialState)
static void ZSTDMT_serialState_free (serialState_t *serialState)
static void ZSTDMT_serialState_update (serialState_t *serialState, ZSTD_CCtx *jobCCtx, rawSeqStore_t seqStore, range_t src, unsigned jobID)
static void ZSTDMT_serialState_ensureFinished (serialState_t *serialState, unsigned jobID, size_t cSize)
static void ZSTDMT_compressionJob (void *jobDescription)
static void ZSTDMT_freeJobsTable (ZSTDMT_jobDescription *jobTable, U32 nbJobs, ZSTD_customMem cMem)
static ZSTDMT_jobDescription * ZSTDMT_createJobsTable (U32 *nbJobsPtr, ZSTD_customMem cMem)
static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx *mtctx, U32 nbWorkers)
static size_t ZSTDMT_CCtxParam_setNbWorkers (ZSTD_CCtx_params *params, unsigned nbWorkers)
MEM_STATIC ZSTDMT_CCtx * ZSTDMT_createCCtx_advanced_internal (unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool *pool)
static void ZSTDMT_releaseAllJobResources (ZSTDMT_CCtx *mtctx)
static void ZSTDMT_waitForAllJobsCompleted (ZSTDMT_CCtx *mtctx)
static size_t ZSTDMT_resize (ZSTDMT_CCtx *mtctx, unsigned nbWorkers)
static unsigned ZSTDMT_computeTargetJobLog (const ZSTD_CCtx_params *params)
static int ZSTDMT_overlapLog_default (ZSTD_strategy strat)
static int ZSTDMT_overlapLog (int ovlog, ZSTD_strategy strat)
static size_t ZSTDMT_computeOverlapSize (const ZSTD_CCtx_params *params)
static void ZSTDMT_writeLastEmptyBlock (ZSTDMT_jobDescription *job)
static size_t ZSTDMT_createCompressionJob (ZSTDMT_CCtx *mtctx, size_t srcSize, ZSTD_EndDirective endOp)
static size_t ZSTDMT_flushProduced (ZSTDMT_CCtx *mtctx, ZSTD_outBuffer *output, unsigned blockToFlush, ZSTD_EndDirective end)
static range_t ZSTDMT_getInputDataInUse (ZSTDMT_CCtx *mtctx)
static int ZSTDMT_isOverlapped (buffer_t buffer, range_t range)
static int ZSTDMT_doesOverlapWindow (buffer_t buffer, ZSTD_window_t window)
static void ZSTDMT_waitForLdmComplete (ZSTDMT_CCtx *mtctx, buffer_t buffer)
static int ZSTDMT_tryGetInputRange (ZSTDMT_CCtx *mtctx)
static syncPoint_t findSynchronizationPoint (ZSTDMT_CCtx const *mtctx, ZSTD_inBuffer const input)
static DTableDesc HUF_getDTableDesc (const HUF_DTable *table)
static size_t HUF_initFastDStream (BYTE const *ip)
static size_t HUF_DecompressFastArgs_init (HUF_DecompressFastArgs *args, void *dst, size_t dstSize, void const *src, size_t srcSize, const HUF_DTable *DTable)
static size_t HUF_initRemainingDStream (BIT_DStream_t *bit, HUF_DecompressFastArgs const *args, int stream, BYTE *segmentEnd)
static U64 HUF_DEltX1_set4 (BYTE symbol, BYTE nbBits)
static U32 HUF_rescaleStats (BYTE *huffWeight, U32 *rankVal, U32 nbSymbols, U32 tableLog, U32 targetTableLog)
FORCE_INLINE_TEMPLATE BYTE HUF_decodeSymbolX1 (BIT_DStream_t *Dstream, const HUF_DEltX1 *dt, const U32 dtLog)
HINT_INLINE size_t HUF_decodeStreamX1 (BYTE *p, BIT_DStream_t *const bitDPtr, BYTE *const pEnd, const HUF_DEltX1 *const dt, const U32 dtLog)
FORCE_INLINE_TEMPLATE size_t HUF_decompress1X1_usingDTable_internal_body (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable)
FORCE_INLINE_TEMPLATE size_t HUF_decompress4X1_usingDTable_internal_body (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable)
static size_t HUF_decompress4X1_usingDTable_internal_default (void *dst, size_t dstSize, void const *cSrc, size_t cSrcSize, HUF_DTable const *DTable)
static HUF_FAST_BMI2_ATTRS void HUF_decompress4X1_usingDTable_internal_fast_c_loop (HUF_DecompressFastArgs *args)
static HUF_FAST_BMI2_ATTRS size_t HUF_decompress4X1_usingDTable_internal_fast (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable, HUF_DecompressFastLoopFn loopFn)
static size_t HUF_decompress4X1_usingDTable_internal (void *dst, size_t dstSize, void const *cSrc, size_t cSrcSize, HUF_DTable const *DTable, int flags)
static size_t HUF_decompress4X1_DCtx_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
static U32 HUF_buildDEltX2U32 (U32 symbol, U32 nbBits, U32 baseSeq, int level)
static HUF_DEltX2 HUF_buildDEltX2 (U32 symbol, U32 nbBits, U32 baseSeq, int level)
static U64 HUF_buildDEltX2U64 (U32 symbol, U32 nbBits, U16 baseSeq, int level)
static void HUF_fillDTableX2ForWeight (HUF_DEltX2 *DTableRank, sortedSymbol_t const *begin, sortedSymbol_t const *end, U32 nbBits, U32 tableLog, U16 baseSeq, int const level)
static void HUF_fillDTableX2Level2 (HUF_DEltX2 *DTable, U32 targetLog, const U32 consumedBits, const U32 *rankVal, const int minWeight, const int maxWeight1, const sortedSymbol_t *sortedSymbols, U32 const *rankStart, U32 nbBitsBaseline, U16 baseSeq)
static void HUF_fillDTableX2 (HUF_DEltX2 *DTable, const U32 targetLog, const sortedSymbol_t *sortedList, const U32 *rankStart, rankValCol_t *rankValOrigin, const U32 maxWeight, const U32 nbBitsBaseline)
FORCE_INLINE_TEMPLATE U32 HUF_decodeSymbolX2 (void *op, BIT_DStream_t *DStream, const HUF_DEltX2 *dt, const U32 dtLog)
FORCE_INLINE_TEMPLATE U32 HUF_decodeLastSymbolX2 (void *op, BIT_DStream_t *DStream, const HUF_DEltX2 *dt, const U32 dtLog)
HINT_INLINE size_t HUF_decodeStreamX2 (BYTE *p, BIT_DStream_t *bitDPtr, BYTE *const pEnd, const HUF_DEltX2 *const dt, const U32 dtLog)
FORCE_INLINE_TEMPLATE size_t HUF_decompress1X2_usingDTable_internal_body (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable)
FORCE_INLINE_TEMPLATE size_t HUF_decompress4X2_usingDTable_internal_body (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable)
static size_t HUF_decompress4X2_usingDTable_internal_default (void *dst, size_t dstSize, void const *cSrc, size_t cSrcSize, HUF_DTable const *DTable)
static HUF_FAST_BMI2_ATTRS void HUF_decompress4X2_usingDTable_internal_fast_c_loop (HUF_DecompressFastArgs *args)
static HUF_FAST_BMI2_ATTRS size_t HUF_decompress4X2_usingDTable_internal_fast (void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, const HUF_DTable *DTable, HUF_DecompressFastLoopFn loopFn)
static size_t HUF_decompress4X2_usingDTable_internal (void *dst, size_t dstSize, void const *cSrc, size_t cSrcSize, HUF_DTable const *DTable, int flags)
static size_t HUF_decompress4X2_DCtx_wksp (HUF_DTable *dctx, void *dst, size_t dstSize, const void *cSrc, size_t cSrcSize, void *workSpace, size_t wkspSize, int flags)
MEM_STATIC int ZSTD_DCtx_get_bmi2 (const struct ZSTD_DCtx_s *dctx)
size_t ZSTD_loadDEntropy (ZSTD_entropyDTables_t *entropy, const void *const dict, size_t const dictSize)
void ZSTD_checkContinuity (ZSTD_DCtx *dctx, const void *dst, size_t dstSize)
const void * ZSTD_DDict_dictContent (const ZSTD_DDict *ddict)
size_t ZSTD_DDict_dictSize (const ZSTD_DDict *ddict)
void ZSTD_copyDDictParameters (ZSTD_DCtx *dctx, const ZSTD_DDict *ddict)
static size_t ZSTD_loadEntropy_intoDDict (ZSTD_DDict *ddict, ZSTD_dictContentType_e dictContentType)
static size_t ZSTD_initDDict_internal (ZSTD_DDict *ddict, const void *dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
size_t ZSTD_decompressBlock_internal (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const streaming_operation streaming)
void ZSTD_buildFSETable (ZSTD_seqSymbol *dt, const short *normalizedCounter, unsigned maxSymbolValue, const U32 *baseValue, const U8 *nbAdditionalBits, unsigned tableLog, void *wksp, size_t wkspSize, int bmi2)
size_t ZSTD_decompressBlock_deprecated (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
static size_t ZSTD_DDictHashSet_getIndex (const ZSTD_DDictHashSet *hashSet, U32 dictID)
static size_t ZSTD_DDictHashSet_emplaceDDict (ZSTD_DDictHashSet *hashSet, const ZSTD_DDict *ddict)
static size_t ZSTD_DDictHashSet_expand (ZSTD_DDictHashSet *hashSet, ZSTD_customMem customMem)
static const ZSTD_DDict * ZSTD_DDictHashSet_getDDict (ZSTD_DDictHashSet *hashSet, U32 dictID)
static ZSTD_DDictHashSet * ZSTD_createDDictHashSet (ZSTD_customMem customMem)
static void ZSTD_freeDDictHashSet (ZSTD_DDictHashSet *hashSet, ZSTD_customMem customMem)
static size_t ZSTD_DDictHashSet_addDDict (ZSTD_DDictHashSet *hashSet, const ZSTD_DDict *ddict, ZSTD_customMem customMem)
static size_t ZSTD_startingInputLength (ZSTD_format_e format)
static void ZSTD_DCtx_resetParameters (ZSTD_DCtx *dctx)
static void ZSTD_initDCtx_internal (ZSTD_DCtx *dctx)
static ZSTD_DCtx * ZSTD_createDCtx_internal (ZSTD_customMem customMem)
static void ZSTD_clearDict (ZSTD_DCtx *dctx)
static void ZSTD_DCtx_selectFrameDDict (ZSTD_DCtx *dctx)
static size_t ZSTD_frameHeaderSize_internal (const void *src, size_t srcSize, ZSTD_format_e format)
static size_t readSkippableFrameSize (void const *src, size_t srcSize)
static size_t ZSTD_decodeFrameHeader (ZSTD_DCtx *dctx, const void *src, size_t headerSize)
static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo (size_t ret)
static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo (const void *src, size_t srcSize, ZSTD_format_e format)
static size_t ZSTD_findFrameCompressedSize_advanced (const void *src, size_t srcSize, ZSTD_format_e format)
static size_t ZSTD_copyRawBlock (void *dst, size_t dstCapacity, const void *src, size_t srcSize)
static size_t ZSTD_setRleBlock (void *dst, size_t dstCapacity, BYTE b, size_t regenSize)
static void ZSTD_DCtx_trace_end (ZSTD_DCtx const *dctx, U64 uncompressedSize, U64 compressedSize, unsigned streaming)
static size_t ZSTD_decompressFrame (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void **srcPtr, size_t *srcSizePtr)
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_decompressMultiFrame (ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, const ZSTD_DDict *ddict)
static ZSTD_DDict const * ZSTD_getDDict (ZSTD_DCtx *dctx)
static size_t ZSTD_nextSrcSizeToDecompressWithInputSize (ZSTD_DCtx *dctx, size_t inputSize)
static int ZSTD_isSkipFrame (ZSTD_DCtx *dctx)
 RETURN_ERROR_IF (srcSize !=ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed")
 ZSTD_checkContinuity (dctx, dst, dstCapacity)
 switch (dctx->stage)
static size_t ZSTD_refDictContent (ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
static size_t ZSTD_decompress_insertDictionary (ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
static int ZSTD_dParam_withinBounds (ZSTD_dParameter dParam, int value)
static size_t ZSTD_decodingBufferSize_internal (unsigned long long windowSize, unsigned long long frameContentSize, size_t blockSizeMax)
static int ZSTD_DCtx_isOverflow (ZSTD_DStream *zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
static void ZSTD_DCtx_updateOversizedDuration (ZSTD_DStream *zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
static int ZSTD_DCtx_isOversizedTooLong (ZSTD_DStream *zds)
static size_t ZSTD_checkOutBuffer (ZSTD_DStream const *zds, ZSTD_outBuffer const *output)
static size_t ZSTD_decompressContinueStream (ZSTD_DStream *zds, char **op, char *oend, void const *src, size_t srcSize)
static void ZSTD_copy4 (void *dst, const void *src)
static size_t ZSTD_blockSizeMax (ZSTD_DCtx const *dctx)
static void ZSTD_allocateLiteralsBuffer (ZSTD_DCtx *dctx, void *const dst, const size_t dstCapacity, const size_t litSize, const streaming_operation streaming, const size_t expectedWriteSize, const unsigned splitImmediately)
static size_t ZSTD_decodeLiteralsBlock (ZSTD_DCtx *dctx, const void *src, size_t srcSize, void *dst, size_t dstCapacity, const streaming_operation streaming)
size_t ZSTD_decodeLiteralsBlock_wrapper (ZSTD_DCtx *dctx, const void *src, size_t srcSize, void *dst, size_t dstCapacity)
static void ZSTD_buildSeqTable_rle (ZSTD_seqSymbol *dt, U32 baseValue, U8 nbAddBits)
FORCE_INLINE_TEMPLATE void ZSTD_buildFSETable_body (ZSTD_seqSymbol *dt, const short *normalizedCounter, unsigned maxSymbolValue, const U32 *baseValue, const U8 *nbAdditionalBits, unsigned tableLog, void *wksp, size_t wkspSize)
static void ZSTD_buildFSETable_body_default (ZSTD_seqSymbol *dt, const short *normalizedCounter, unsigned maxSymbolValue, const U32 *baseValue, const U8 *nbAdditionalBits, unsigned tableLog, void *wksp, size_t wkspSize)
static size_t ZSTD_buildSeqTable (ZSTD_seqSymbol *DTableSpace, const ZSTD_seqSymbol **DTablePtr, symbolEncodingType_e type, unsigned max, U32 maxLog, const void *src, size_t srcSize, const U32 *baseValue, const U8 *nbAdditionalBits, const ZSTD_seqSymbol *defaultTable, U32 flagRepeatTable, int ddictIsCold, int nbSeq, U32 *wksp, size_t wkspSize, int bmi2)
HINT_INLINE void ZSTD_overlapCopy8 (BYTE **op, BYTE const **ip, size_t offset)
static void ZSTD_safecopy (BYTE *op, const BYTE *const oend_w, BYTE const *ip, ptrdiff_t length, ZSTD_overlap_e ovtype)
static void ZSTD_safecopyDstBeforeSrc (BYTE *op, const BYTE *ip, ptrdiff_t length)
FORCE_NOINLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_execSequenceEnd (BYTE *op, BYTE *const oend, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const prefixStart, const BYTE *const virtualStart, const BYTE *const dictEnd)
FORCE_NOINLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_execSequenceEndSplitLitBuffer (BYTE *op, BYTE *const oend, const BYTE *const oend_w, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const prefixStart, const BYTE *const virtualStart, const BYTE *const dictEnd)
HINT_INLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_execSequence (BYTE *op, BYTE *const oend, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const prefixStart, const BYTE *const virtualStart, const BYTE *const dictEnd)
HINT_INLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_execSequenceSplitLitBuffer (BYTE *op, BYTE *const oend, const BYTE *const oend_w, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const prefixStart, const BYTE *const virtualStart, const BYTE *const dictEnd)
static void ZSTD_initFseState (ZSTD_fseState *DStatePtr, BIT_DStream_t *bitD, const ZSTD_seqSymbol *dt)
FORCE_INLINE_TEMPLATE void ZSTD_updateFseStateWithDInfo (ZSTD_fseState *DStatePtr, BIT_DStream_t *bitD, U16 nextState, U32 nbBits)
FORCE_INLINE_TEMPLATE seq_t ZSTD_decodeSequence (seqState_t *seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq)
FORCE_INLINE_TEMPLATE size_t DONT_VECTORIZE ZSTD_decompressSequences_bodySplitLitBuffer (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
FORCE_INLINE_TEMPLATE size_t DONT_VECTORIZE ZSTD_decompressSequences_body (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequences_default (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequencesSplitLitBuffer_default (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
FORCE_INLINE_TEMPLATE size_t ZSTD_prefetchMatch (size_t prefetchPos, seq_t const sequence, const BYTE *const prefixStart, const BYTE *const dictEnd)
FORCE_INLINE_TEMPLATE size_t ZSTD_decompressSequencesLong_body (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequencesLong_default (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequences (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequencesSplitLitBuffer (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_decompressSequencesLong (ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset)
static size_t ZSTD_totalHistorySize (BYTE *op, BYTE const *virtualStart)
static ZSTD_OffsetInfo ZSTD_getOffsetInfo (const ZSTD_seqSymbol *offTable, int nbSeq)
static size_t ZSTD_maxShortOffset (void)
 ZBUFF_DEPRECATED ("use ZSTD_createCStream") ZBUFF_CCtx *ZBUFF_createCCtx(void)
 ZBUFF_DEPRECATED ("use ZSTD_freeCStream") size_t ZBUFF_freeCCtx(ZBUFF_CCtx *cctx)
 ZBUFF_DEPRECATED ("use ZSTD_initCStream") size_t ZBUFF_compressInit(ZBUFF_CCtx *cctx
 ZBUFF_DEPRECATED ("use ZSTD_initCStream_usingDict") size_t ZBUFF_compressInitDictionary(ZBUFF_CCtx *cctx
 ZBUFF_DEPRECATED ("use ZSTD_compressStream") size_t ZBUFF_compressContinue(ZBUFF_CCtx *cctx
 ZBUFF_DEPRECATED ("use ZSTD_flushStream") size_t ZBUFF_compressFlush(ZBUFF_CCtx *cctx
 ZBUFF_DEPRECATED ("use ZSTD_endStream") size_t ZBUFF_compressEnd(ZBUFF_CCtx *cctx
 ZBUFF_DEPRECATED ("use ZSTD_createDStream") ZBUFF_DCtx *ZBUFF_createDCtx(void)
 ZBUFF_DEPRECATED ("use ZSTD_freeDStream") size_t ZBUFF_freeDCtx(ZBUFF_DCtx *dctx)
 ZBUFF_DEPRECATED ("use ZSTD_initDStream") size_t ZBUFF_decompressInit(ZBUFF_DCtx *dctx)
 ZBUFF_DEPRECATED ("use ZSTD_initDStream_usingDict") size_t ZBUFF_decompressInitDictionary(ZBUFF_DCtx *dctx
 ZBUFF_DEPRECATED ("use ZSTD_decompressStream") size_t ZBUFF_decompressContinue(ZBUFF_DCtx *dctx
 ZBUFF_DEPRECATED ("use ZSTD_isError") unsigned ZBUFF_isError(size_t errorCode)
 ZBUFF_DEPRECATED ("use ZSTD_getErrorName") const char *ZBUFF_getErrorName(size_t errorCode)
 ZBUFF_DEPRECATED ("use ZSTD_CStreamInSize") size_t ZBUFF_recommendedCInSize(void)
 ZBUFF_DEPRECATED ("use ZSTD_CStreamOutSize") size_t ZBUFF_recommendedCOutSize(void)
 ZBUFF_DEPRECATED ("use ZSTD_DStreamInSize") size_t ZBUFF_recommendedDInSize(void)
 ZBUFF_DEPRECATED ("use ZSTD_DStreamOutSize") size_t ZBUFF_recommendedDOutSize(void)
unsigned ZBUFF_isError (size_t errorCode)
const char * ZBUFF_getErrorName (size_t errorCode)
ZBUFF_CCtx * ZBUFF_createCCtx (void)
ZBUFF_CCtx * ZBUFF_createCCtx_advanced (ZSTD_customMem customMem)
size_t ZBUFF_freeCCtx (ZBUFF_CCtx *zbc)
size_t ZBUFF_compressInit_advanced (ZBUFF_CCtx *zbc, const void *dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize)
size_t ZBUFF_compressInitDictionary (ZBUFF_CCtx *zbc, const void *dict, size_t dictSize, int compressionLevel)
size_t ZBUFF_compressInit (ZBUFF_CCtx *zbc, int compressionLevel)
size_t ZBUFF_compressContinue (ZBUFF_CCtx *zbc, void *dst, size_t *dstCapacityPtr, const void *src, size_t *srcSizePtr)
size_t ZBUFF_compressFlush (ZBUFF_CCtx *zbc, void *dst, size_t *dstCapacityPtr)
size_t ZBUFF_compressEnd (ZBUFF_CCtx *zbc, void *dst, size_t *dstCapacityPtr)
size_t ZBUFF_recommendedCInSize (void)
size_t ZBUFF_recommendedCOutSize (void)
ZBUFF_DCtx * ZBUFF_createDCtx (void)
ZBUFF_DCtx * ZBUFF_createDCtx_advanced (ZSTD_customMem customMem)
size_t ZBUFF_freeDCtx (ZBUFF_DCtx *zbd)
size_t ZBUFF_decompressInitDictionary (ZBUFF_DCtx *zbd, const void *dict, size_t dictSize)
size_t ZBUFF_decompressInit (ZBUFF_DCtx *zbd)
size_t ZBUFF_decompressContinue (ZBUFF_DCtx *zbd, void *dst, size_t *dstCapacityPtr, const void *src, size_t *srcSizePtr)
size_t ZBUFF_recommendedDInSize (void)
size_t ZBUFF_recommendedDOutSize (void)
ZDICTLIB_API size_t ZDICT_trainFromBuffer (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples)
ZDICTLIB_API size_t ZDICT_finalizeDictionary (void *dstDictBuffer, size_t maxDictSize, const void *dictContent, size_t dictContentSize, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_params_t parameters)
ZDICTLIB_API unsigned ZDICT_getDictID (const void *dictBuffer, size_t dictSize)
ZDICTLIB_API size_t ZDICT_getDictHeaderSize (const void *dictBuffer, size_t dictSize)
ZDICTLIB_API unsigned ZDICT_isError (size_t errorCode)
ZDICTLIB_API const char * ZDICT_getErrorName (size_t errorCode)
ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_cover_params_t parameters)
ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_cover_params_t *parameters)
ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_fastCover (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_fastCover_params_t parameters)
ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_fastCover (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_fastCover_params_t *parameters)
ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_legacy (void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_legacy_params_t parameters)
ZDICTLIB_STATIC_API size_t ZDICT_addEntropyTablesFromBuffer (void *dictBuffer, size_t dictContentSize, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples)
COVER_epoch_info_t COVER_computeEpochs (U32 maxDictSize, U32 nbDmers, U32 k, U32 passes)
void COVER_warnOnSmallCorpus (size_t maxDictSize, size_t nbDmers, int displayLevel)
size_t COVER_checkTotalCompressedSize (const ZDICT_cover_params_t parameters, const size_t *samplesSizes, const BYTE *samples, size_t *offsets, size_t nbTrainSamples, size_t nbSamples, BYTE *const dict, size_t dictBufferCapacity)
size_t COVER_sum (const size_t *samplesSizes, unsigned nbSamples)
void COVER_best_init (COVER_best_t *best)
void COVER_best_wait (COVER_best_t *best)
void COVER_best_destroy (COVER_best_t *best)
void COVER_best_start (COVER_best_t *best)
void COVER_best_finish (COVER_best_t *best, ZDICT_cover_params_t parameters, COVER_dictSelection_t selection)
unsigned COVER_dictSelectionIsError (COVER_dictSelection_t selection)
COVER_dictSelection_t COVER_dictSelectionError (size_t error)
void COVER_dictSelectionFree (COVER_dictSelection_t selection)
COVER_dictSelection_t COVER_selectDict (BYTE *customDictContent, size_t dictBufferCapacity, size_t dictContentSize, const BYTE *samplesBuffer, const size_t *samplesSizes, unsigned nbFinalizeSamples, size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t *offsets, size_t totalCompressedSize)
static void COVER_map_clear (COVER_map_t *map)
static int COVER_map_init (COVER_map_t *map, U32 size)
static U32 COVER_map_hash (COVER_map_t *map, U32 key)
static U32 COVER_map_index (COVER_map_t *map, U32 key)
static U32 * COVER_map_at (COVER_map_t *map, U32 key)
static void COVER_map_remove (COVER_map_t *map, U32 key)
static void COVER_map_destroy (COVER_map_t *map)
static int COVER_cmp (COVER_ctx_t *ctx, const void *lp, const void *rp)
static int COVER_cmp8 (COVER_ctx_t *ctx, const void *lp, const void *rp)
static int WIN_CDECL COVER_strict_cmp (const void *lp, const void *rp)
static int WIN_CDECL COVER_strict_cmp8 (const void *lp, const void *rp)
static const size_t * COVER_lower_bound (const size_t *first, const size_t *last, size_t value)
static void COVER_groupBy (const void *data, size_t count, size_t size, COVER_ctx_t *ctx, int(*cmp)(COVER_ctx_t *, const void *, const void *), void(*grp)(COVER_ctx_t *, const void *, const void *))
static void COVER_group (COVER_ctx_t *ctx, const void *group, const void *groupEnd)
static COVER_segment_t COVER_selectSegment (const COVER_ctx_t *ctx, U32 *freqs, COVER_map_t *activeDmers, U32 begin, U32 end, ZDICT_cover_params_t parameters)
static int COVER_checkParameters (ZDICT_cover_params_t parameters, size_t maxDictSize)
static void COVER_ctx_destroy (COVER_ctx_t *ctx)
static size_t COVER_ctx_init (COVER_ctx_t *ctx, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, unsigned d, double splitPoint)
static size_t COVER_buildDictionary (const COVER_ctx_t *ctx, U32 *freqs, COVER_map_t *activeDmers, void *dictBuffer, size_t dictBufferCapacity, ZDICT_cover_params_t parameters)
static COVER_dictSelection_t setDictSelection (BYTE *buf, size_t s, size_t csz)
static void COVER_tryParameters (void *opaque)
int divsufsort (const unsigned char *T, int *SA, int n, int openMP)
int divbwt (const unsigned char *T, unsigned char *U, int *A, int n, unsigned char *num_indexes, int *indexes, int openMP)
static INLINE int ss_ilg (int n)
static INLINE int ss_isqrt (int x)
static INLINE int ss_compare (const unsigned char *T, const int *p1, const int *p2, int depth)
static void ss_insertionsort (const unsigned char *T, const int *PA, int *first, int *last, int depth)
static INLINE void ss_fixdown (const unsigned char *Td, const int *PA, int *SA, int i, int size)
static void ss_heapsort (const unsigned char *Td, const int *PA, int *SA, int size)
static INLINE int * ss_median3 (const unsigned char *Td, const int *PA, int *v1, int *v2, int *v3)
static INLINE int * ss_median5 (const unsigned char *Td, const int *PA, int *v1, int *v2, int *v3, int *v4, int *v5)
static INLINE int * ss_pivot (const unsigned char *Td, const int *PA, int *first, int *last)
static INLINE int * ss_partition (const int *PA, int *first, int *last, int depth)
static void ss_mintrosort (const unsigned char *T, const int *PA, int *first, int *last, int depth)
static INLINE void ss_blockswap (int *a, int *b, int n)
static INLINE void ss_rotate (int *first, int *middle, int *last)
static void ss_inplacemerge (const unsigned char *T, const int *PA, int *first, int *middle, int *last, int depth)
static void ss_mergeforward (const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int depth)
static void ss_mergebackward (const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int depth)
static void ss_swapmerge (const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int bufsize, int depth)
static void sssort (const unsigned char *T, const int *PA, int *first, int *last, int *buf, int bufsize, int depth, int n, int lastsuffix)
static INLINE int tr_ilg (int n)
static void tr_insertionsort (const int *ISAd, int *first, int *last)
static INLINE void tr_fixdown (const int *ISAd, int *SA, int i, int size)
static void tr_heapsort (const int *ISAd, int *SA, int size)
static INLINE int * tr_median3 (const int *ISAd, int *v1, int *v2, int *v3)
static INLINE int * tr_median5 (const int *ISAd, int *v1, int *v2, int *v3, int *v4, int *v5)
static INLINE int * tr_pivot (const int *ISAd, int *first, int *last)
static INLINE void trbudget_init (trbudget_t *budget, int chance, int incval)
static INLINE int trbudget_check (trbudget_t *budget, int size)
static INLINE void tr_partition (const int *ISAd, int *first, int *middle, int *last, int **pa, int **pb, int v)
static void tr_copy (int *ISA, const int *SA, int *first, int *a, int *b, int *last, int depth)
static void tr_partialcopy (int *ISA, const int *SA, int *first, int *a, int *b, int *last, int depth)
static void tr_introsort (int *ISA, const int *ISAd, int *SA, int *first, int *last, trbudget_t *budget)
static void trsort (int *ISA, int *SA, int n, int depth)
static int sort_typeBstar (const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int openMP)
static void construct_SA (const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int m)
static int construct_BWT (const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int m)
static int construct_BWT_indexes (const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int m, unsigned char *num_indexes, int *indexes)
static size_t FASTCOVER_hashPtrToIndex (const void *p, U32 f, unsigned d)
static COVER_segment_t FASTCOVER_selectSegment (const FASTCOVER_ctx_t *ctx, U32 *freqs, U32 begin, U32 end, ZDICT_cover_params_t parameters, U16 *segmentFreqs)
static int FASTCOVER_checkParameters (ZDICT_cover_params_t parameters, size_t maxDictSize, unsigned f, unsigned accel)
static void FASTCOVER_ctx_destroy (FASTCOVER_ctx_t *ctx)
static void FASTCOVER_computeFrequency (U32 *freqs, const FASTCOVER_ctx_t *ctx)
static size_t FASTCOVER_ctx_init (FASTCOVER_ctx_t *ctx, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, unsigned d, double splitPoint, unsigned f, FASTCOVER_accel_t accelParams)
static size_t FASTCOVER_buildDictionary (const FASTCOVER_ctx_t *ctx, U32 *freqs, void *dictBuffer, size_t dictBufferCapacity, ZDICT_cover_params_t parameters, U16 *segmentFreqs)
static void FASTCOVER_tryParameters (void *opaque)
static void FASTCOVER_convertToCoverParams (ZDICT_fastCover_params_t fastCoverParams, ZDICT_cover_params_t *coverParams)
static void FASTCOVER_convertToFastCoverParams (ZDICT_cover_params_t coverParams, ZDICT_fastCover_params_t *fastCoverParams, unsigned f, unsigned accel)
static clock_t ZDICT_clockSpan (clock_t nPrevious)
static void ZDICT_printHex (const void *ptr, size_t length)
static size_t ZDICT_count (const void *pIn, const void *pMatch)
static void ZDICT_initDictItem (dictItem *d)
static dictItem ZDICT_analyzePos (BYTE *doneMarks, const int *suffix, U32 start, const void *buffer, U32 minRatio, U32 notificationLevel)
static int isIncluded (const void *in, const void *container, size_t length)
static U32 ZDICT_tryMerge (dictItem *table, dictItem elt, U32 eltNbToSkip, const void *buffer)
static void ZDICT_removeDictItem (dictItem *table, U32 id)
static void ZDICT_insertDictItem (dictItem *table, U32 maxSize, dictItem elt, const void *buffer)
static U32 ZDICT_dictSize (const dictItem *dictList)
static size_t ZDICT_trainBuffer_legacy (dictItem *dictList, U32 dictListSize, const void *const buffer, size_t bufferSize, const size_t *fileSizes, unsigned nbFiles, unsigned minRatio, U32 notificationLevel)
static void ZDICT_fillNoise (void *buffer, size_t length)
static void ZDICT_countEStats (EStats_ress_t esr, const ZSTD_parameters *params, unsigned *countLit, unsigned *offsetcodeCount, unsigned *matchlengthCount, unsigned *litlengthCount, U32 *repOffsets, const void *src, size_t srcSize, U32 notificationLevel)
static size_t ZDICT_totalSampleSize (const size_t *fileSizes, unsigned nbFiles)
static void ZDICT_insertSortCount (offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
static void ZDICT_flatLit (unsigned *countLit)
static size_t ZDICT_analyzeEntropy (void *dstBuffer, size_t maxDstSize, int compressionLevel, const void *srcBuffer, const size_t *fileSizes, unsigned nbFiles, const void *dictBuffer, size_t dictBufferSize, unsigned notificationLevel)
static U32 ZDICT_maxRep (U32 const reps[ZSTD_REP_NUM])
static size_t ZDICT_addEntropyTablesFromBuffer_advanced (void *dictBuffer, size_t dictContentSize, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_params_t params)
static size_t ZDICT_trainFromBuffer_unsafe_legacy (void *dictBuffer, size_t maxDictSize, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_legacy_params_t params)

Variables

static ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }
int g_debuglevel = DEBUGLEVEL
static const unsigned BIT_mask []
int g_ZSTD_threading_useless_symbol
static const int g_one = 1
static const U32 PRIME32_1 = 2654435761U
static const U32 PRIME32_2 = 2246822519U
static const U32 PRIME32_3 = 3266489917U
static const U32 PRIME32_4 = 668265263U
static const U32 PRIME32_5 = 374761393U
static const U64 PRIME64_1 = 11400714785074694791ULL
static const U64 PRIME64_2 = 14029467366897019727ULL
static const U64 PRIME64_3 = 1609587929392839161ULL
static const U64 PRIME64_4 = 9650029242287828579ULL
static const U64 PRIME64_5 = 2870177450012600261ULL
static UNUSED_ATTR const U32 repStartValue [ZSTD_REP_NUM] = { 1, 4, 8 }
static UNUSED_ATTR const size_t ZSTD_fcs_fieldSize [4] = { 0, 2, 4, 8 }
static UNUSED_ATTR const size_t ZSTD_did_fieldSize [4] = { 0, 1, 2, 4 }
static UNUSED_ATTR const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE
static UNUSED_ATTR const U8 LL_bits [MaxLL+1]
static UNUSED_ATTR const S16 LL_defaultNorm [MaxLL+1]
static UNUSED_ATTR const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG
static UNUSED_ATTR const U8 ML_bits [MaxML+1]
static UNUSED_ATTR const S16 ML_defaultNorm [MaxML+1]
static UNUSED_ATTR const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG
static UNUSED_ATTR const S16 OF_defaultNorm [DefaultMaxOff+1]
static UNUSED_ATTR const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG
static UNUSED_ATTR const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0}
static const U32 prime3bytes = 506832829U
static const U32 prime4bytes = 2654435761U
static const U64 prime5bytes = 889523592379ULL
static const U64 prime6bytes = 227718039650203ULL
static const U64 prime7bytes = 58295818150454627ULL
static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL
static const size_t attachDictSizeCutoffs [ZSTD_STRATEGY_MAX+1]
static const ZSTD_compressionParameters ZSTD_defaultCParameters [4][ZSTD_MAX_CLEVEL+1]
static unsigned const kInverseProbabilityLog256 [256]
static UNUSED_ATTR const U64 ZSTD_ldm_gearTab [256]
static const buffer_t g_nullBuffer = { NULL, 0 }
static const range_t kNullRange = { NULL, 0 }
static const roundBuff_t kNullRoundBuff = {NULL, 0, 0}
static const algo_time_t algoTime [16][2]
static UNUSED_ATTR const U32 LL_base [MaxLL+1]
static UNUSED_ATTR const U32 OF_base [MaxOff+1]
static UNUSED_ATTR const U8 OF_bits [MaxOff+1]
static UNUSED_ATTR const U32 ML_base [MaxML+1]
dctx processedCSize = srcSize
static const ZSTD_seqSymbol LL_defaultDTable [(1<< LL_DEFAULTNORMLOG)+1]
static const ZSTD_seqSymbol OF_defaultDTable [(1<< OF_DEFAULTNORMLOG)+1]
static const ZSTD_seqSymbol ML_defaultDTable [(1<< ML_DEFAULTNORMLOG)+1]
int compressionLevel
const void * dict
const void size_t dictSize
void * dst
void size_t * dstCapacityPtr
void size_t const void * src
void size_t const void size_t * srcSizePtr
static const U32 COVER_prime4bytes = 2654435761U
static COVER_ctx_t * g_coverCtx = NULL
static const int lg_table [256]
static const int sqq_table [256]
static const FASTCOVER_accel_t FASTCOVER_defaultAccelParameters [FASTCOVER_MAX_ACCEL+1]
static const U32 g_selectivity_default = 9

Detailed Description

Copyright (c) 2016 Tino Reichardt All rights reserved.

You can contact the author at:

This source code is licensed under both the BSD-style license (found in the LICENSE file in the root directory of this source tree) and the GPLv2 (found in the COPYING file in the root directory of this source tree). You may select, at your option, one of the above-listed licenses. This file will hold wrapper for systems, which do not support pthreads

Implementation taken from folly/CpuId.h https://github.com/facebook/folly/blob/master/folly/CpuId.h

Typedef Documentation

◆ ZSTD_CCtx

Explicit context

◆ ZSTD_inBuffer

◆ ZSTD_CStream

CCtx and CStream are now effectively same object (>= v1.3.0)

◆ ZSTD_DStream

typedef ZSTD_DCtx duckdb_zstd::ZSTD_DStream

DCtx and DStream are now effectively same object (>= v1.3.0)

◆ ZSTD_CDict

Bulk processing dictionary API

◆ ZSTD_allocFunction

typedef void *(* duckdb_zstd::ZSTD_allocFunction) (void *opaque, size_t size)

Custom memory allocation : These prototypes make it possible to pass your own allocation/free functions. ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.

◆ ZSTD_threadPool

Thread pool : These prototypes make it possible to share a thread pool among multiple compression contexts. This can limit resources for applications with multiple threads where each one uses a threaded compression mode (via ZSTD_c_nbWorkers parameter). ZSTD_createThreadPool creates a new thread pool with a given number of threads. Note that the lifetime of such pool must exist while being used. ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value to use an internal thread pool). ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer.

◆ FSE_CTable

typedef unsigned duckdb_zstd::FSE_CTable

Constructor and Destructor of FSE_CTable. Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue'

◆ POOL_function

typedef void(* duckdb_zstd::POOL_function) (void *)

POOL_function : The function type that can be added to a thread pool.

◆ XXH32_state_t

XXH32() : Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". The memory between input & input+length must be valid (allocated and read-accessible). "seed" can be used to alter the result predictably. Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s XXH64() : Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". "seed" can be used to alter the result predictably. This function runs 2x faster on 64-bits systems, but slower on 32-bits systems (see benchmark).

◆ COVER_best_t

COVER_best_t is used for two purposes:

  1. Synchronizing threads.
  2. Saving the best parameters and dictionary.

All of the methods except COVER_best_init() are thread safe if zstd is compiled with multithreaded support.

◆ COVER_dictSelection_t

Struct used for the dictionary selection function.

◆ COVER_tryParameters_data_t

◆ FASTCOVER_tryParameters_data_t

Enumeration Type Documentation

◆ ZSTD_strategy

Advanced compression API (Requires v1.4.0+)

407443 { ZSTD_fast=1,
407444 ZSTD_dfast=2,
407445 ZSTD_greedy=3,
407446 ZSTD_lazy=4,
407447 ZSTD_lazy2=5,
407448 ZSTD_btlazy2=6,
407449 ZSTD_btopt=7,
407450 ZSTD_btultra=8,
407451 ZSTD_btultra2=9
407452 /* note : new strategies _might_ be added in the future.
407453 Only the order (from fast to strong) is guaranteed */
407454} ZSTD_strategy;
ZSTD_strategy
Definition duckdb.cpp:407443

◆ ZSTD_cParameter

enum duckdb_zstd::ZSTD_cParameter
407456 {
407457
407458 /* compression parameters
407459 * Note: When compressing with a ZSTD_CDict these parameters are superseded
407460 * by the parameters used to construct the ZSTD_CDict.
407461 * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */
407462 ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.
407463 * Note that exact compression parameters are dynamically determined,
407464 * depending on both compression level and srcSize (when known).
407465 * Default level is ZSTD_CLEVEL_DEFAULT==3.
407466 * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.
407467 * Note 1 : it's possible to pass a negative compression level.
407468 * Note 2 : setting a level does not automatically set all other compression parameters
407469 * to default. Setting this will however eventually dynamically impact the compression
407470 * parameters which have not been manually set. The manually set
407471 * ones will 'stick'. */
407472 /* Advanced compression parameters :
407473 * It's possible to pin down compression parameters to some specific values.
407474 * In which case, these values are no longer dynamically selected by the compressor */
407475 ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2.
407476 * This will set a memory budget for streaming decompression,
407477 * with larger values requiring more memory
407478 * and typically compressing more.
407479 * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
407480 * Special: value 0 means "use default windowLog".
407481 * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT
407482 * requires explicitly allowing such size at streaming decompression stage. */
407483 ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2.
407484 * Resulting memory usage is (1 << (hashLog+2)).
407485 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
407486 * Larger tables improve compression ratio of strategies <= dFast,
407487 * and improve speed of strategies > dFast.
407488 * Special: value 0 means "use default hashLog". */
407489 ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2.
407490 * Resulting memory usage is (1 << (chainLog+2)).
407491 * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.
407492 * Larger tables result in better and slower compression.
407493 * This parameter is useless for "fast" strategy.
407494 * It's still useful when using "dfast" strategy,
407495 * in which case it defines a secondary probe table.
407496 * Special: value 0 means "use default chainLog". */
407497 ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2.
407498 * More attempts result in better and slower compression.
407499 * This parameter is useless for "fast" and "dFast" strategies.
407500 * Special: value 0 means "use default searchLog". */
407501 ZSTD_c_minMatch=105, /* Minimum size of searched matches.
407502 * Note that Zstandard can still find matches of smaller size,
407503 * it just tweaks its search algorithm to look for this size and larger.
407504 * Larger values increase compression and decompression speed, but decrease ratio.
407505 * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.
407506 * Note that currently, for all strategies < btopt, effective minimum is 4.
407507 * , for all strategies > fast, effective maximum is 6.
407508 * Special: value 0 means "use default minMatchLength". */
407509 ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.
407510 * For strategies btopt, btultra & btultra2:
407511 * Length of Match considered "good enough" to stop search.
407512 * Larger values make compression stronger, and slower.
407513 * For strategy fast:
407514 * Distance between match sampling.
407515 * Larger values make compression faster, and weaker.
407516 * Special: value 0 means "use default targetLength". */
407517 ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition.
407518 * The higher the value of selected strategy, the more complex it is,
407519 * resulting in stronger and slower compression.
407520 * Special: value 0 means "use default strategy". */
407521
407522 ZSTD_c_targetCBlockSize=130, /* v1.5.6+
407523 * Attempts to fit compressed block size into approximatively targetCBlockSize.
407524 * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX.
407525 * Note that it's not a guarantee, just a convergence target (default:0).
407526 * No target when targetCBlockSize == 0.
407527 * This is helpful in low bandwidth streaming environments to improve end-to-end latency,
407528 * when a client can make use of partial documents (a prominent example being Chrome).
407529 * Note: this parameter is stable since v1.5.6.
407530 * It was present as an experimental parameter in earlier versions,
407531 * but it's not recommended using it with earlier library versions
407532 * due to massive performance regressions.
407533 */
407534 /* LDM mode parameters */
407535 ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
407536 * This parameter is designed to improve compression ratio
407537 * for large inputs, by finding large matches at long distance.
407538 * It increases memory usage and window size.
407539 * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB
407540 * except when expressly set to a different value.
407541 * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and
407542 * compression strategy >= ZSTD_btopt (== compression level 16+) */
407543 ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2.
407544 * Larger values increase memory usage and compression ratio,
407545 * but decrease compression speed.
407546 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX
407547 * default: windowlog - 7.
407548 * Special: value 0 means "automatically determine hashlog". */
407549 ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher.
407550 * Larger/too small values usually decrease compression ratio.
407551 * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.
407552 * Special: value 0 means "use default value" (default: 64). */
407553 ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.
407554 * Larger values improve collision resolution but decrease compression speed.
407555 * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.
407556 * Special: value 0 means "use default value" (default: 3). */
407557 ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.
407558 * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).
407559 * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.
407560 * Larger values improve compression speed.
407561 * Deviating far from default value will likely result in a compression ratio decrease.
407562 * Special: value 0 means "automatically determine hashRateLog". */
407563
407564 /* frame parameters */
407565 ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)
407566 * Content size must be known at the beginning of compression.
407567 * This is automatically the case when using ZSTD_compress2(),
407568 * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */
407569 ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */
407570 ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */
407571
407572 /* multi-threading parameters */
407573 /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).
407574 * Otherwise, trying to set any other value than default (0) will be a no-op and return an error.
407575 * In a situation where it's unknown if the linked library supports multi-threading or not,
407576 * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property.
407577 */
407578 ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel.
407579 * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() :
407580 * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,
407581 * while compression is performed in parallel, within worker thread(s).
407582 * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :
407583 * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).
407584 * More workers improve speed, but also increase memory usage.
407585 * Default value is `0`, aka "single-threaded mode" : no worker is spawned,
407586 * compression is performed inside Caller's thread, and all invocations are blocking */
407587 ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1.
407588 * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.
407589 * 0 means default, which is dynamically determined based on compression parameters.
407590 * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest.
407591 * The minimum size is automatically and transparently enforced. */
407592 ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size.
407593 * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.
407594 * It helps preserve compression ratio, while each job is compressed in parallel.
407595 * This value is enforced only when nbWorkers >= 1.
407596 * Larger values increase compression ratio, but decrease speed.
407597 * Possible values range from 0 to 9 :
407598 * - 0 means "default" : value will be determined by the library, depending on strategy
407599 * - 1 means "no overlap"
407600 * - 9 means "full overlap", using a full window size.
407601 * Each intermediate rank increases/decreases load size by a factor 2 :
407602 * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default
407603 * default value varies between 6 and 9, depending on strategy */
407604
407605 /* note : additional experimental parameters are also available
407606 * within the experimental section of the API.
407607 * At the time of this writing, they include :
407608 * ZSTD_c_rsyncable
407609 * ZSTD_c_format
407610 * ZSTD_c_forceMaxWindow
407611 * ZSTD_c_forceAttachDict
407612 * ZSTD_c_literalCompressionMode
407613 * ZSTD_c_srcSizeHint
407614 * ZSTD_c_enableDedicatedDictSearch
407615 * ZSTD_c_stableInBuffer
407616 * ZSTD_c_stableOutBuffer
407617 * ZSTD_c_blockDelimiters
407618 * ZSTD_c_validateSequences
407619 * ZSTD_c_useBlockSplitter
407620 * ZSTD_c_useRowMatchFinder
407621 * ZSTD_c_prefetchCDictTables
407622 * ZSTD_c_enableSeqProducerFallback
407623 * ZSTD_c_maxBlockSize
407624 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
407625 * note : never ever use experimentalParam? names directly;
407626 * also, the enums values themselves are unstable and can still change.
407627 */
407628 ZSTD_c_experimentalParam1=500,
407629 ZSTD_c_experimentalParam2=10,
407630 ZSTD_c_experimentalParam3=1000,
407631 ZSTD_c_experimentalParam4=1001,
407632 ZSTD_c_experimentalParam5=1002,
407633 /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */
407634 ZSTD_c_experimentalParam7=1004,
407635 ZSTD_c_experimentalParam8=1005,
407636 ZSTD_c_experimentalParam9=1006,
407637 ZSTD_c_experimentalParam10=1007,
407638 ZSTD_c_experimentalParam11=1008,
407639 ZSTD_c_experimentalParam12=1009,
407640 ZSTD_c_experimentalParam13=1010,
407641 ZSTD_c_experimentalParam14=1011,
407642 ZSTD_c_experimentalParam15=1012,
407643 ZSTD_c_experimentalParam16=1013,
407644 ZSTD_c_experimentalParam17=1014,
407645 ZSTD_c_experimentalParam18=1015,
407646 ZSTD_c_experimentalParam19=1016
407647} ZSTD_cParameter;

◆ ZSTD_ResetDirective

enum duckdb_zstd::ZSTD_ResetDirective
407694 {
407695 ZSTD_reset_session_only = 1,
407696 ZSTD_reset_parameters = 2,
407697 ZSTD_reset_session_and_parameters = 3
407698} ZSTD_ResetDirective;

◆ ZSTD_dParameter

ZSTD_compress2() : Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. (note that this entry point doesn't even expose a compression level parameter). ZSTD_compress2() always starts a new frame. Should cctx hold data from a previously unfinished frame, everything about it is forgotten.

  • Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
  • The function is always blocking, returns when compression is completed. NOTE: Providing dstCapacity >= ZSTD_compressBound(srcSize) guarantees that zstd will have enough space to successfully compress the data, though it is possible it fails for other reasons.
    Returns
    : compressed size written into dst (<= `dstCapacity), or an error code if it fails (which can be tested using ZSTD_isError()). */ ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
    /*********************************************** Advanced decompression API (Requires v1.4.0+)
407745 {
407746
407747 ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which
407748 * the streaming API will refuse to allocate memory buffer
407749 * in order to protect the host from unreasonable memory requirements.
407750 * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
407751 * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).
407752 * Special: value 0 means "use default maximum windowLog". */
407753
407754 /* note : additional experimental parameters are also available
407755 * within the experimental section of the API.
407756 * At the time of this writing, they include :
407757 * ZSTD_d_format
407758 * ZSTD_d_stableOutBuffer
407759 * ZSTD_d_forceIgnoreChecksum
407760 * ZSTD_d_refMultipleDDicts
407761 * ZSTD_d_disableHuffmanAssembly
407762 * ZSTD_d_maxBlockSize
407763 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
407764 * note : never ever use experimentalParam? names directly
407765 */
407766 ZSTD_d_experimentalParam1=1000,
407767 ZSTD_d_experimentalParam2=1001,
407768 ZSTD_d_experimentalParam3=1002,
407769 ZSTD_d_experimentalParam4=1003,
407770 ZSTD_d_experimentalParam5=1004,
407771 ZSTD_d_experimentalParam6=1005
407772
ZSTD_dParameter
Definition duckdb.cpp:407745

◆ ZSTD_EndDirective

enum duckdb_zstd::ZSTD_EndDirective
407888 {
407889 ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */
407890 ZSTD_e_flush=1, /* flush any data provided so far,
407891 * it creates (at least) one new block, that can be decoded immediately on reception;
407892 * frame will continue: any future data can still reference previously compressed data, improving compression.
407893 * note : multithreaded compression will block to flush as much output as possible. */
407894 ZSTD_e_end=2 /* flush any remaining data _and_ close current frame.
407895 * note that frame is only closed after compressed data is fully flushed (return value == 0).
407896 * After that point, any additional data starts a new frame.
407897 * note : each frame is independent (does not reference any content from previous frame).
407898 : note : multithreaded compression will block to flush as much output as possible. */
407899} ZSTD_EndDirective;

◆ ZSTD_dictContentType_e

enum duckdb_zstd::ZSTD_dictContentType_e
408467 {
408468 ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */
408469 ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */
408470 ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */
408471} ZSTD_dictContentType_e;

◆ ZSTD_dictLoadMethod_e

Enumerator
ZSTD_dlm_byCopy 

Copy dictionary content internally

ZSTD_dlm_byRef 

Reference dictionary content – the dictionary buffer must outlive its users.

408473 {
408474 ZSTD_dlm_byCopy = 0,
408475 ZSTD_dlm_byRef = 1
ZSTD_dictLoadMethod_e
Definition duckdb.cpp:408473
@ ZSTD_dlm_byCopy
Definition duckdb.cpp:408474
@ ZSTD_dlm_byRef
Definition duckdb.cpp:408475

◆ ZSTD_format_e

enum duckdb_zstd::ZSTD_format_e
408478 {
408479 ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */
408480 ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number.
408481 * Useful to save 4 bytes per generated frame.
408482 * Decoder cannot recognise automatically this format, requiring this instruction. */
408483} ZSTD_format_e;

◆ ZSTD_forceIgnoreChecksum_e

enum duckdb_zstd::ZSTD_forceIgnoreChecksum_e
408485 {
408486 /* Note: this enum controls ZSTD_d_forceIgnoreChecksum */
408487 ZSTD_d_validateChecksum = 0,
408488 ZSTD_d_ignoreChecksum = 1
408489} ZSTD_forceIgnoreChecksum_e;

◆ ZSTD_refMultipleDDicts_e

enum duckdb_zstd::ZSTD_refMultipleDDicts_e
408491 {
408492 /* Note: this enum controls ZSTD_d_refMultipleDDicts */
408493 ZSTD_rmd_refSingleDDict = 0,
408494 ZSTD_rmd_refMultipleDDicts = 1
408495} ZSTD_refMultipleDDicts_e;

◆ ZSTD_dictAttachPref_e

enum duckdb_zstd::ZSTD_dictAttachPref_e
408497 {
408498 /* Note: this enum and the behavior it controls are effectively internal
408499 * implementation details of the compressor. They are expected to continue
408500 * to evolve and should be considered only in the context of extremely
408501 * advanced performance tuning.
408502 *
408503 * Zstd currently supports the use of a CDict in three ways:
408504 *
408505 * - The contents of the CDict can be copied into the working context. This
408506 * means that the compression can search both the dictionary and input
408507 * while operating on a single set of internal tables. This makes
408508 * the compression faster per-byte of input. However, the initial copy of
408509 * the CDict's tables incurs a fixed cost at the beginning of the
408510 * compression. For small compressions (< 8 KB), that copy can dominate
408511 * the cost of the compression.
408512 *
408513 * - The CDict's tables can be used in-place. In this model, compression is
408514 * slower per input byte, because the compressor has to search two sets of
408515 * tables. However, this model incurs no start-up cost (as long as the
408516 * working context's tables can be reused). For small inputs, this can be
408517 * faster than copying the CDict's tables.
408518 *
408519 * - The CDict's tables are not used at all, and instead we use the working
408520 * context alone to reload the dictionary and use params based on the source
408521 * size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict().
408522 * This method is effective when the dictionary sizes are very small relative
408523 * to the input size, and the input size is fairly large to begin with.
408524 *
408525 * Zstd has a simple internal heuristic that selects which strategy to use
408526 * at the beginning of a compression. However, if experimentation shows that
408527 * Zstd is making poor choices, it is possible to override that choice with
408528 * this enum.
408529 */
408530 ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */
408531 ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */
408532 ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */
408533 ZSTD_dictForceLoad = 3 /* Always reload the dictionary */
408534} ZSTD_dictAttachPref_e;

◆ ZSTD_literalCompressionMode_e

Enumerator
ZSTD_lcm_auto 

Automatically determine the compression mode based on the compression level. Negative compression levels will be uncompressed, and positive compression levels will be compressed.

ZSTD_lcm_huffman 

Always attempt Huffman compression. Uncompressed literals will still be emitted if Huffman compression is not profitable.

ZSTD_lcm_uncompressed 

Always emit uncompressed literals.

408536 {
408537 ZSTD_lcm_auto = 0,
408540 ZSTD_lcm_huffman = 1,
ZSTD_literalCompressionMode_e
Definition duckdb.cpp:408536
@ ZSTD_lcm_uncompressed
Definition duckdb.cpp:408542
@ ZSTD_lcm_huffman
Definition duckdb.cpp:408540
@ ZSTD_lcm_auto
Definition duckdb.cpp:408537

◆ ZSTD_paramSwitch_e

enum duckdb_zstd::ZSTD_paramSwitch_e
408545 {
408546 /* Note: This enum controls features which are conditionally beneficial. Zstd typically will make a final
408547 * decision on whether or not to enable the feature (ZSTD_ps_auto), but setting the switch to ZSTD_ps_enable
408548 * or ZSTD_ps_disable allow for a force enable/disable the feature.
408549 */
408550 ZSTD_ps_auto = 0, /* Let the library automatically determine whether the feature shall be enabled */
408551 ZSTD_ps_enable = 1, /* Force-enable the feature */
408552 ZSTD_ps_disable = 2 /* Do not use the feature */
408553} ZSTD_paramSwitch_e;

◆ ZSTD_frameType_e

enum duckdb_zstd::ZSTD_frameType_e
408603{ ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e;

◆ ZSTD_sequenceFormat_e

enum duckdb_zstd::ZSTD_sequenceFormat_e
408672 {
408673 ZSTD_sf_noBlockDelimiters = 0, /* Representation of ZSTD_Sequence has no block delimiters, sequences only */
408674 ZSTD_sf_explicitBlockDelimiters = 1 /* Representation of ZSTD_Sequence contains explicit block delimiters */
408675} ZSTD_sequenceFormat_e;

◆ ZSTD_nextInputType_e

enum duckdb_zstd::ZSTD_nextInputType_e
410158{ ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;

◆ ZSTD_ErrorCode

enum duckdb_zstd::ZSTD_ErrorCode
608844 {
608845 ZSTD_error_no_error = 0,
608846 ZSTD_error_GENERIC = 1,
608847 ZSTD_error_prefix_unknown = 10,
608848 ZSTD_error_version_unsupported = 12,
608849 ZSTD_error_frameParameter_unsupported = 14,
608850 ZSTD_error_frameParameter_windowTooLarge = 16,
608851 ZSTD_error_corruption_detected = 20,
608852 ZSTD_error_checksum_wrong = 22,
608853 ZSTD_error_literals_headerWrong = 24,
608854 ZSTD_error_dictionary_corrupted = 30,
608855 ZSTD_error_dictionary_wrong = 32,
608856 ZSTD_error_dictionaryCreation_failed = 34,
608857 ZSTD_error_parameter_unsupported = 40,
608858 ZSTD_error_parameter_combination_unsupported = 41,
608859 ZSTD_error_parameter_outOfBound = 42,
608860 ZSTD_error_tableLog_tooLarge = 44,
608861 ZSTD_error_maxSymbolValue_tooLarge = 46,
608862 ZSTD_error_maxSymbolValue_tooSmall = 48,
608863 ZSTD_error_stabilityCondition_notRespected = 50,
608864 ZSTD_error_stage_wrong = 60,
608865 ZSTD_error_init_missing = 62,
608866 ZSTD_error_memory_allocation = 64,
608867 ZSTD_error_workSpace_tooSmall= 66,
608868 ZSTD_error_dstSize_tooSmall = 70,
608869 ZSTD_error_srcSize_wrong = 72,
608870 ZSTD_error_dstBuffer_null = 74,
608871 ZSTD_error_noForwardProgress_destFull = 80,
608872 ZSTD_error_noForwardProgress_inputEmpty = 82,
608873 /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
608874 ZSTD_error_frameIndex_tooLarge = 100,
608875 ZSTD_error_seekableIO = 102,
608876 ZSTD_error_dstBuffer_wrong = 104,
608877 ZSTD_error_srcBuffer_wrong = 105,
608878 ZSTD_error_sequenceProducer_failed = 106,
608879 ZSTD_error_externalSequences_invalid = 107,
608880 ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */

◆ BIT_DStream_status

enum duckdb_zstd::BIT_DStream_status
609603 { BIT_DStream_unfinished = 0, /* fully refilled */
609604 BIT_DStream_endOfBuffer = 1, /* still some bits left in bitstream */
609605 BIT_DStream_completed = 2, /* bitstream entirely consumed, bit-exact */
609606 BIT_DStream_overflow = 3 /* user requested more bits than present in bitstream */

◆ FSE_repeat

Enumerator
FSE_repeat_none 

Cannot use the previous table

FSE_repeat_check 

Can use the previous table but it must be checked

FSE_repeat_valid 

Can use the previous table and it is assumed to be valid

610011 {
@ FSE_repeat_check
Definition duckdb.cpp:610012
@ FSE_repeat_valid
Definition duckdb.cpp:610013
@ FSE_repeat_none
Definition duckdb.cpp:610011

◆ HUF_flags_e

Huffman flags bitset. For all flags, 0 is the default value.

Enumerator
HUF_flags_bmi2 

If compiled with DYNAMIC_BMI2: Set flag only if the CPU supports BMI2 at runtime. Otherwise: Ignored.

HUF_flags_optimalDepth 

If set: Test possible table depths to find the one that produces the smallest header + encoded size. If unset: Use heuristic to find the table depth.

HUF_flags_preferRepeat 

If set: If the previous table can encode the input, always reuse the previous table. If unset: If the previous table can encode the input, reuse the previous table if it results in a smaller output.

HUF_flags_suspectUncompressible 

If set: Sample the input and check if the sample is uncompressible, if it is then don't attempt to compress. If unset: Always histogram the entire input.

HUF_flags_disableAsm 

If set: Don't use assembly implementations If unset: Allow using assembly implementations

HUF_flags_disableFast 

If set: Don't use the fast decoding loop, always use the fallback decoding loop. If unset: Use the fast decoding loop when possible.

610453 {
610458 HUF_flags_bmi2 = (1 << 0),
610463 HUF_flags_optimalDepth = (1 << 1),
610468 HUF_flags_preferRepeat = (1 << 2),
610478 HUF_flags_disableAsm = (1 << 4),
610483 HUF_flags_disableFast = (1 << 5)
@ HUF_flags_suspectUncompressible
Definition duckdb.cpp:610472
@ HUF_flags_preferRepeat
Definition duckdb.cpp:610467
@ HUF_flags_bmi2
Definition duckdb.cpp:610457
@ HUF_flags_disableFast
Definition duckdb.cpp:610482
@ HUF_flags_disableAsm
Definition duckdb.cpp:610477
@ HUF_flags_optimalDepth
Definition duckdb.cpp:610462

◆ HUF_repeat

Enumerator
HUF_repeat_none 

Cannot use the previous table

HUF_repeat_check 

Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat

HUF_repeat_valid 

Can use the previous table and it is assumed to be valid

610512 {
@ HUF_repeat_valid
Definition duckdb.cpp:610514
@ HUF_repeat_none
Definition duckdb.cpp:610512
@ HUF_repeat_check
Definition duckdb.cpp:610513

◆ XXH_errorcode

enum duckdb_zstd::XXH_errorcode
612441{

◆ XXH_endianess

enum duckdb_zstd::XXH_endianess

◆ XXH_alignment

enum duckdb_zstd::XXH_alignment

◆ blockType_e

enum duckdb_zstd::blockType_e

◆ symbolEncodingType_e

enum duckdb_zstd::symbolEncodingType_e

◆ ZSTD_overlap_e

enum duckdb_zstd::ZSTD_overlap_e
614121 {
614122 ZSTD_no_overlap,
614123 ZSTD_overlap_src_before_dst
614124 /* ZSTD_overlap_dst_before_src, */

◆ ZSTD_bufferMode_e

enum duckdb_zstd::ZSTD_bufferMode_e
614187 {
614188 ZSTD_bm_buffered = 0, /* Buffer the input/output */
614189 ZSTD_bm_stable = 1 /* ZSTD_inBuffer/ZSTD_outBuffer is stable */

◆ ZSTD_longLengthType_e

enum duckdb_zstd::ZSTD_longLengthType_e
614203 {
614204 ZSTD_llt_none = 0, /* no longLengthType */
614205 ZSTD_llt_literalLength = 1, /* represents a long literal */
614206 ZSTD_llt_matchLength = 2 /* represents a long match */

◆ HIST_checkInput_e

enum duckdb_zstd::HIST_checkInput_e

◆ HUF_nbStreams_e

enum duckdb_zstd::HUF_nbStreams_e

◆ ZSTD_cwksp_alloc_phase_e

enum duckdb_zstd::ZSTD_cwksp_alloc_phase_e
616842 {
616843 ZSTD_cwksp_alloc_objects,
616844 ZSTD_cwksp_alloc_aligned_init_once,
616845 ZSTD_cwksp_alloc_aligned,
616846 ZSTD_cwksp_alloc_buffers

◆ ZSTD_cwksp_static_alloc_e

Used to describe whether the workspace is statically allocated (and will not necessarily ever be freed), or if it's dynamically allocated and we can expect a well-formed caller to free this.

616854 {
616855 ZSTD_cwksp_dynamic_alloc,
616856 ZSTD_cwksp_static_alloc

◆ ZSTD_compressionStage_e

enum duckdb_zstd::ZSTD_compressionStage_e

◆ ZSTD_cStreamStage

enum duckdb_zstd::ZSTD_cStreamStage

◆ ZSTD_OptPrice_e

enum duckdb_zstd::ZSTD_OptPrice_e

◆ ZSTD_buffered_policy_e

Indicates whether this compression proceeds directly from user-provided source buffer to user-provided destination buffer (ZSTDb_not_buffered), or whether the context needs to buffer the input/output (ZSTDb_buffered).

◆ ZSTD_dictTableLoadMethod_e

enum duckdb_zstd::ZSTD_dictTableLoadMethod_e

◆ ZSTD_tableFillPurpose_e

enum duckdb_zstd::ZSTD_tableFillPurpose_e

◆ ZSTD_dictMode_e

enum duckdb_zstd::ZSTD_dictMode_e
618002 { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
618003typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;

◆ ZSTD_cParamMode_e

enum duckdb_zstd::ZSTD_cParamMode_e
618005 {
618006 ZSTD_noDict = 0,
618007 ZSTD_extDict = 1,
618008 ZSTD_dictMatchState = 2,
618009 ZSTD_dedicatedDictSearch = 3
618010} ZSTD_dictMode_e;
618011
618012typedef enum {
618013 ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.
618014 * In this mode we use both the srcSize and the dictSize
618015 * when selecting and adjusting parameters.
618016 */
618017 ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.
618018 * In this mode we only take the srcSize into account when selecting
618019 * and adjusting parameters.
618020 */
618021 ZSTD_cpm_createCDict = 2, /* Creating a CDict.
618022 * In this mode we take both the source size and the dictionary size
618023 * into account when selecting and adjusting the parameters.

◆ ZSTD_defaultPolicy_e

enum duckdb_zstd::ZSTD_defaultPolicy_e

◆ ZSTD_compResetPolicy_e

Controls, for this matchState reset, whether the tables need to be cleared / prepared for the coming compression (ZSTDcrp_makeClean), or whether the tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a subsequent operation will overwrite the table space anyways (e.g., copying the matchState contents in from a CDict).

◆ ZSTD_indexResetPolicy_e

Controls, for this matchState reset, whether indexing can continue where it left off (ZSTDirp_continue), or whether it needs to be restarted from zero (ZSTDirp_reset).

◆ ZSTD_resetTarget_e

enum duckdb_zstd::ZSTD_resetTarget_e
621663 {
621664 ZSTDirp_continue,

◆ ZSTD_buildSeqStore_e

enum duckdb_zstd::ZSTD_buildSeqStore_e
622893{

◆ searchMethod_e

enum duckdb_zstd::searchMethod_e

◆ base_directive_e

enum duckdb_zstd::base_directive_e

◆ ZSTD_dStage

enum duckdb_zstd::ZSTD_dStage

◆ ZSTD_dStreamStage

enum duckdb_zstd::ZSTD_dStreamStage

◆ ZSTD_dictUses_e

enum duckdb_zstd::ZSTD_dictUses_e
638781 { zdss_init=0, zdss_loadHeader,

◆ ZSTD_litLocation_e

enum duckdb_zstd::ZSTD_litLocation_e

◆ streaming_operation

enum duckdb_zstd::streaming_operation

◆ ZSTD_longOffset_e

enum duckdb_zstd::ZSTD_longOffset_e

Function Documentation

◆ ZSTD_versionNumber()

unsigned duckdb_zstd::ZSTD_versionNumber ( void )

ZSTD_versionNumber() : Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_versionString()

const char * duckdb_zstd::ZSTD_versionString ( void )

ZSTD_versionString() : Return runtime library version, like "1.4.5". Requires v1.3.0+.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_decompress()

size_t duckdb_zstd::ZSTD_decompress ( void * dst,
size_t dstCapacity,
const void * src,
size_t compressedSize )

Simple API

ZSTD_compress() : Compresses src content as a single zstd compressed frame into already allocated dst. NOTE: Providing dstCapacity >= ZSTD_compressBound(srcSize) guarantees that zstd will have enough space to successfully compress the data.

Returns
: compressed size written into dst (<= `dstCapacity), or an error code if it fails (which can be tested using ZSTD_isError()). */ ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel);

/*! ZSTD_decompress() : compressedSize : must be the exact size of some number of compressed and/or skippable frames. dstCapacity is an upper bound of originalSize to regenerate. If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.

Returns
: the number of bytes decompressed into dst (<= dstCapacity), or an errorCode if it fails (which can be tested using ZSTD_isError()).
640499{
640500 return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx));
640501}
640502
640503
640504size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
640505{
640506#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
640507 size_t regenSize;
640508 ZSTD_DCtx* const dctx = ZSTD_createDCtx_internal(ZSTD_defaultCMem);
640509 RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!");
640510 regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
640511 ZSTD_freeDCtx(dctx);
#define RETURN_ERROR_IF(cond, err,...)
Definition duckdb.cpp:608990
ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
Definition duckdb.cpp:640491
static ZSTD_customMem const ZSTD_defaultCMem
Definition duckdb.cpp:408930
ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_DDict *ddict)
Definition duckdb.cpp:640950
ZSTDLIB_API size_t ZSTD_decompress(void *dst, size_t dstCapacity, const void *src, size_t compressedSize)
Definition duckdb.cpp:640497
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getFrameContentSize()

unsigned long long duckdb_zstd::ZSTD_getFrameContentSize ( const void * src,
size_t srcSize )

ZSTD_getFrameContentSize() : compatible with legacy mode

Returns
: decompressed size of the single frame pointed to be src if known, otherwise
  • ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
  • ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
639871{
639872#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
639873 if (ZSTD_isLegacy(src, srcSize)) {
639874 unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
639875 return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
639876 }
639877#endif
639878 { ZSTD_frameHeader zfh;
639879 if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
#define ZSTD_CONTENTSIZE_UNKNOWN
Definition duckdb.cpp:407319
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader *zfhPtr, const void *src, size_t srcSize)
Definition duckdb.cpp:639853
Here is the caller graph for this function:

◆ ZSTD_getDecompressedSize()

unsigned long long duckdb_zstd::ZSTD_getDecompressedSize ( const void * src,
size_t srcSize )

ZSTD_getDecompressedSize() : NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). Both functions work the same way, but ZSTD_getDecompressedSize() blends "empty", "unknown" and "error" results to the same return value (0), while ZSTD_getFrameContentSize() gives them separate return values.

Returns
: decompressed size of src frame content if known and not empty, 0 otherwise.

ZSTD_getDecompressedSize() : compatible with legacy mode

Returns
: decompressed size if known, 0 otherwise note : 0 can mean any of the following :
  • frame content is empty
  • decompressed size field is not present in frame header
  • frame header unknown / not supported
  • frame header not complete (srcSize too small)
639985 : decompressed size if known, 0 otherwise
639986 note : 0 can mean any of the following :
639987 - frame content is empty
639988 - decompressed size field is not present in frame header
639989 - frame header unknown / not supported
Scalar mean(InputArray src, InputArray mask=noArray())
GOpaque< Size > size(const GMat &src)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_findFrameCompressedSize()

size_t duckdb_zstd::ZSTD_findFrameCompressedSize ( const void * src,
size_t srcSize )

ZSTD_findFrameCompressedSize() : Requires v1.4.0+ src should point to the start of a ZSTD frame or skippable frame. srcSize must be >= first frame size

Returns
: the compressed size of the first frame starting at src, suitable to pass as srcSize to ZSTD_decompress or similar, or an error code if input is invalid

ZSTD_findFrameCompressedSize() : See docs in zstd.h Note: compatible with legacy mode

Here is the call graph for this function:

◆ ZSTD_compressBound()

size_t duckdb_zstd::ZSTD_compressBound ( size_t srcSize)

maximum compressed size in worst case single-pass scenario

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_isError()

unsigned duckdb_zstd::ZSTD_isError ( size_t code)

tells if a size_t function result is an error code

ZSTD_isError() : tells if a return value is an error code symbol is required for external callers

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getErrorName()

const char * duckdb_zstd::ZSTD_getErrorName ( size_t code)

provides readable string from an error code

ZSTD_getErrorName() : provides error code string from function result (useful for debugging)

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_minCLevel()

int duckdb_zstd::ZSTD_minCLevel ( void )

minimum negative compression level allowed, requires v1.4.0+

Here is the caller graph for this function:

◆ ZSTD_maxCLevel()

int duckdb_zstd::ZSTD_maxCLevel ( void )

maximum compression level available

Here is the caller graph for this function:

◆ ZSTD_defaultCLevel()

int duckdb_zstd::ZSTD_defaultCLevel ( void )

default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_createCCtx()

ZSTD_CCtx * duckdb_zstd::ZSTD_createCCtx ( void )

◆ ZSTD_freeCCtx()

size_t duckdb_zstd::ZSTD_freeCCtx ( ZSTD_CCtx * cctx)
619893{
619894 DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);
619895 if (cctx==NULL) return 0; /* support free on NULL */
619896 RETURN_ERROR_IF(cctx->staticSize, memory_allocation,

◆ ZSTD_compressCCtx()

size_t duckdb_zstd::ZSTD_compressCCtx ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
int compressionLevel )

ZSTD_compressCCtx() : Same as ZSTD_compress(), using an explicit ZSTD_CCtx. Important : in order to mirror ZSTD_compress() behavior, this function compresses at the requested compression level, ignoring any other advanced parameter . If any advanced parameter was set using the advanced API, they will all be reset. Only compressionLevel remains.

625056 : compressionLevel);
625057 }
625058 DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
625059 return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
625060}
625061
625062size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
625063 void* dst, size_t dstCapacity,
ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, int compressionLevel)
Definition duckdb.cpp:625055
struct ZSTD_CCtx_s ZSTD_CCtx
Definition duckdb.cpp:407387
Here is the call graph for this function:

◆ ZSTD_createDCtx()

ZSTD_DCtx * duckdb_zstd::ZSTD_createDCtx ( void )
639609{
639610 return ZSTD_createDCtx_internal(customMem);

◆ ZSTD_freeDCtx()

size_t duckdb_zstd::ZSTD_freeDCtx ( ZSTD_DCtx * dctx)
639620{
639621 ZSTD_freeDDict(dctx->ddictLocal);
639622 dctx->ddictLocal = NULL;
639623 dctx->ddict = NULL;
639624 dctx->dictUses = ZSTD_dont_use;
639625}
639626
639627size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
639628{
639629 if (dctx==NULL) return 0; /* support free on NULL */
639630 RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx");
639631 { ZSTD_customMem const cMem = dctx->customMem;
639632 ZSTD_clearDict(dctx);
639633 ZSTD_customFree(dctx->inBuff, cMem);
639634 dctx->inBuff = NULL;
639635#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
639636 if (dctx->legacyContext)
639637 ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
639638#endif
639639 if (dctx->ddictSet) {
ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict *ddict)
Definition duckdb.cpp:639167

◆ ZSTD_decompressDCtx()

size_t duckdb_zstd::ZSTD_decompressDCtx ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

ZSTD_decompressDCtx() : Same as ZSTD_decompress(), requires an allocated ZSTD_DCtx. Compatible with sticky parameters (see below).

640492 :
640493 dctx->dictUses = ZSTD_dont_use;
640494 return dctx->ddict;
Here is the caller graph for this function:

◆ ZSTD_cParam_getBounds()

ZSTD_bounds duckdb_zstd::ZSTD_cParam_getBounds ( ZSTD_cParameter cParam)

ZSTD_cParam_getBounds() : All parameters must belong to an interval with lower and upper bounds, otherwise they will either trigger an error or be automatically clamped.

Returns
: a structure, ZSTD_bounds, which contains
  • an error status field, which must be tested using ZSTD_isError()
  • lower and upper bounds, both inclusive
620140{
620141 ZSTD_bounds bounds = { 0, 0, 0 };
620142
620143 switch(param)
620144 {
620145 case ZSTD_c_compressionLevel:
620146 bounds.lowerBound = ZSTD_minCLevel();
620147 bounds.upperBound = ZSTD_maxCLevel();
620148 return bounds;
620149
620150 case ZSTD_c_windowLog:
620151 bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
620152 bounds.upperBound = ZSTD_WINDOWLOG_MAX;
620153 return bounds;
620154
620155 case ZSTD_c_hashLog:
620156 bounds.lowerBound = ZSTD_HASHLOG_MIN;
620157 bounds.upperBound = ZSTD_HASHLOG_MAX;
620158 return bounds;
620159
620160 case ZSTD_c_chainLog:
620161 bounds.lowerBound = ZSTD_CHAINLOG_MIN;
620162 bounds.upperBound = ZSTD_CHAINLOG_MAX;
620163 return bounds;
620164
620165 case ZSTD_c_searchLog:
620166 bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
620167 bounds.upperBound = ZSTD_SEARCHLOG_MAX;
620168 return bounds;
620169
620170 case ZSTD_c_minMatch:
620171 bounds.lowerBound = ZSTD_MINMATCH_MIN;
620172 bounds.upperBound = ZSTD_MINMATCH_MAX;
620173 return bounds;
620174
620175 case ZSTD_c_targetLength:
620176 bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
620177 bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
620178 return bounds;
620179
620180 case ZSTD_c_strategy:
620181 bounds.lowerBound = ZSTD_STRATEGY_MIN;
620182 bounds.upperBound = ZSTD_STRATEGY_MAX;
620183 return bounds;
620184
620185 case ZSTD_c_contentSizeFlag:
620186 bounds.lowerBound = 0;
620187 bounds.upperBound = 1;
620188 return bounds;
620189
620190 case ZSTD_c_checksumFlag:
620191 bounds.lowerBound = 0;
620192 bounds.upperBound = 1;
620193 return bounds;
620194
620195 case ZSTD_c_dictIDFlag:
620196 bounds.lowerBound = 0;
620197 bounds.upperBound = 1;
620198 return bounds;
620199
620200 case ZSTD_c_nbWorkers:
620201 bounds.lowerBound = 0;
620202#ifdef ZSTD_MULTITHREAD
620203 bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
620204#else
620205 bounds.upperBound = 0;
620206#endif
620207 return bounds;
620208
620209 case ZSTD_c_jobSize:
620210 bounds.lowerBound = 0;
620211#ifdef ZSTD_MULTITHREAD
620212 bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
620213#else
620214 bounds.upperBound = 0;
620215#endif
620216 return bounds;
620217
620218 case ZSTD_c_overlapLog:
620219#ifdef ZSTD_MULTITHREAD
620220 bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
620221 bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
620222#else
620223 bounds.lowerBound = 0;
620224 bounds.upperBound = 0;
620225#endif
620226 return bounds;
620227
620228 case ZSTD_c_enableDedicatedDictSearch:
620229 bounds.lowerBound = 0;
620230 bounds.upperBound = 1;
620231 return bounds;
620232
620233 case ZSTD_c_enableLongDistanceMatching:
620234 bounds.lowerBound = (int)ZSTD_ps_auto;
620235 bounds.upperBound = (int)ZSTD_ps_disable;
620236 return bounds;
620237
620238 case ZSTD_c_ldmHashLog:
620239 bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
620240 bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
620241 return bounds;
620242
620243 case ZSTD_c_ldmMinMatch:
620244 bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
620245 bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
620246 return bounds;
620247
620248 case ZSTD_c_ldmBucketSizeLog:
620249 bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
620250 bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
620251 return bounds;
620252
620253 case ZSTD_c_ldmHashRateLog:
620254 bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
620255 bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
620256 return bounds;
620257
620258 /* experimental parameters */
620259 case ZSTD_c_rsyncable:
620260 bounds.lowerBound = 0;
620261 bounds.upperBound = 1;
620262 return bounds;
620263
620264 case ZSTD_c_forceMaxWindow :
620265 bounds.lowerBound = 0;
620266 bounds.upperBound = 1;
620267 return bounds;
620268
620269 case ZSTD_c_format:
620270 ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
620271 bounds.lowerBound = ZSTD_f_zstd1;
620272 bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */
620273 return bounds;
620274
620275 case ZSTD_c_forceAttachDict:
620276 ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);
620277 bounds.lowerBound = ZSTD_dictDefaultAttach;
620278 bounds.upperBound = ZSTD_dictForceLoad; /* note : how to ensure at compile time that this is the highest value enum ? */
620279 return bounds;
620280
620281 case ZSTD_c_literalCompressionMode:
620282 ZSTD_STATIC_ASSERT(ZSTD_ps_auto < ZSTD_ps_enable && ZSTD_ps_enable < ZSTD_ps_disable);
620283 bounds.lowerBound = (int)ZSTD_ps_auto;
620284 bounds.upperBound = (int)ZSTD_ps_disable;
620285 return bounds;
620286
620287 case ZSTD_c_targetCBlockSize:
620288 bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
620289 bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
620290 return bounds;
620291
620292 case ZSTD_c_srcSizeHint:
620293 bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
620294 bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
620295 return bounds;
620296
620297 case ZSTD_c_stableInBuffer:
620298 case ZSTD_c_stableOutBuffer:
620299 bounds.lowerBound = (int)ZSTD_bm_buffered;
620300 bounds.upperBound = (int)ZSTD_bm_stable;
620301 return bounds;
620302
620303 case ZSTD_c_blockDelimiters:
620304 bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;
620305 bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;
620306 return bounds;
620307
620308 case ZSTD_c_validateSequences:
620309 bounds.lowerBound = 0;
620310 bounds.upperBound = 1;
620311 return bounds;
620312
620313 case ZSTD_c_useBlockSplitter:
620314 bounds.lowerBound = (int)ZSTD_ps_auto;
620315 bounds.upperBound = (int)ZSTD_ps_disable;
620316 return bounds;
620317
620318 case ZSTD_c_useRowMatchFinder:
620319 bounds.lowerBound = (int)ZSTD_ps_auto;
620320 bounds.upperBound = (int)ZSTD_ps_disable;
620321 return bounds;
620322
620323 case ZSTD_c_deterministicRefPrefix:
620324 bounds.lowerBound = 0;
620325 bounds.upperBound = 1;
620326 return bounds;
620327
620328 case ZSTD_c_prefetchCDictTables:
620329 bounds.lowerBound = (int)ZSTD_ps_auto;
620330 bounds.upperBound = (int)ZSTD_ps_disable;
620331 return bounds;
620332
620333 case ZSTD_c_enableSeqProducerFallback:
620334 bounds.lowerBound = 0;
620335 bounds.upperBound = 1;
620336 return bounds;
620337
620338 case ZSTD_c_maxBlockSize:
620339 bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
620340 bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
620341 return bounds;
620342
620343 case ZSTD_c_searchForExternalRepcodes:
620344 bounds.lowerBound = (int)ZSTD_ps_auto;
620345 bounds.upperBound = (int)ZSTD_ps_disable;
ZSTDLIB_API int ZSTD_maxCLevel(void)
Definition duckdb.cpp:626827
ZSTDLIB_API int ZSTD_minCLevel(void)
Definition duckdb.cpp:626828
Definition duckdb.cpp:407649

◆ ZSTD_CCtx_setParameter()

size_t duckdb_zstd::ZSTD_CCtx_setParameter ( ZSTD_CCtx * cctx,
ZSTD_cParameter param,
int value )

ZSTD_CCtx_setParameter() : Set one compression parameter, selected by enum ZSTD_cParameter. All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds(). Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). Setting a parameter is generally only possible during frame initialization (before starting compression). Exception : when using multi-threading mode (nbWorkers >= 1), the following parameters can be updated during compression (within same frame): => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. new parameters will be active for next job only (after a flush()).

Returns
: an error code (which can be tested using ZSTD_isError()).
620415 :
620416 case ZSTD_c_searchForExternalRepcodes:
620417 default:
620418 return 0;
620419 }
620420}
620421
620422size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
620423{
620424 DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
620425 if (cctx->streamStage != zcss_init) {
620426 if (ZSTD_isUpdateAuthorized(param)) {
620427 cctx->cParamsChanged = 1;
620428 } else {
620429 RETURN_ERROR(stage_wrong, "can only set params in cctx init stage");
620430 } }
620431
620432 switch(param)
620433 {
620434 case ZSTD_c_nbWorkers:
620435 RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
620436 "MT not compatible with static alloc");
620437 break;
620438
620439 case ZSTD_c_compressionLevel:
620440 case ZSTD_c_windowLog:
620441 case ZSTD_c_hashLog:
620442 case ZSTD_c_chainLog:
620443 case ZSTD_c_searchLog:
620444 case ZSTD_c_minMatch:
620445 case ZSTD_c_targetLength:
620446 case ZSTD_c_strategy:
620447 case ZSTD_c_ldmHashRateLog:
620448 case ZSTD_c_format:
620449 case ZSTD_c_contentSizeFlag:
620450 case ZSTD_c_checksumFlag:
620451 case ZSTD_c_dictIDFlag:
620452 case ZSTD_c_forceMaxWindow:
620453 case ZSTD_c_forceAttachDict:
620454 case ZSTD_c_literalCompressionMode:
620455 case ZSTD_c_jobSize:
620456 case ZSTD_c_overlapLog:
620457 case ZSTD_c_rsyncable:
620458 case ZSTD_c_enableDedicatedDictSearch:
620459 case ZSTD_c_enableLongDistanceMatching:
620460 case ZSTD_c_ldmHashLog:
620461 case ZSTD_c_ldmMinMatch:
620462 case ZSTD_c_ldmBucketSizeLog:
620463 case ZSTD_c_targetCBlockSize:
620464 case ZSTD_c_srcSizeHint:
620465 case ZSTD_c_stableInBuffer:
620466 case ZSTD_c_stableOutBuffer:
620467 case ZSTD_c_blockDelimiters:
620468 case ZSTD_c_validateSequences:
620469 case ZSTD_c_useBlockSplitter:
620470 case ZSTD_c_useRowMatchFinder:
620471 case ZSTD_c_deterministicRefPrefix:
620472 case ZSTD_c_prefetchCDictTables:
620473 case ZSTD_c_enableSeqProducerFallback:
620474 case ZSTD_c_maxBlockSize:
#define RETURN_ERROR(err,...)
Definition duckdb.cpp:609007
ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx *cctx, ZSTD_cParameter param, int value)
Definition duckdb.cpp:620415
Here is the caller graph for this function:

◆ ZSTD_CCtx_setPledgedSrcSize()

size_t duckdb_zstd::ZSTD_CCtx_setPledgedSrcSize ( ZSTD_CCtx * cctx,
unsigned long long pledgedSrcSize )

ZSTD_CCtx_setPledgedSrcSize() : Total input data size to be compressed as a single frame. Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag. This value will also be controlled at end of frame, and trigger an error if not respected.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame. In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame. Note 2 : pledgedSrcSize is only valid once, for the next frame. It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN. Note 3 : Whenever all input data is provided and consumed in a single round, for example with ZSTD_compress2(), or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end), this value is automatically overridden by srcSize instead.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtx_reset()

size_t duckdb_zstd::ZSTD_CCtx_reset ( ZSTD_CCtx * cctx,
ZSTD_ResetDirective reset )

ZSTD_CCtx_reset() : There are 2 different things that can be reset, independently or jointly :

  • The session : will stop compressing current frame, and make CCtx ready to start a new one. Useful after an error, or to interrupt any ongoing compression. Any internal data not yet flushed is cancelled. Compression parameters and dictionary remain unchanged. They will be used to compress next frame. Resetting session never fails.
  • The parameters : changes all parameters back to "default". This also removes any reference to any dictionary or external sequence producer. Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())
  • Both : similar to resetting the session, followed by resetting parameters.

ZSTD_CCtx_reset() : Also dumps dictionary

621072{
621073 if ( (reset == ZSTD_reset_session_only)
621074 || (reset == ZSTD_reset_session_and_parameters) ) {
621075 cctx->streamStage = zcss_init;
621076 cctx->pledgedSrcSizePlusOne = 0;
621077 }
621078 if ( (reset == ZSTD_reset_parameters)
621079 || (reset == ZSTD_reset_session_and_parameters) ) {
Here is the caller graph for this function:

◆ ZSTD_dParam_getBounds()

ZSTD_bounds duckdb_zstd::ZSTD_dParam_getBounds ( ZSTD_dParameter dParam)

ZSTD_dParam_getBounds() : All parameters must belong to an interval with lower and upper bounds, otherwise they will either trigger an error or be automatically clamped.

Returns
: a structure, ZSTD_bounds, which contains
  • an error status field, which must be tested using ZSTD_isError()
  • both lower and upper bounds, inclusive
641118{
641119 return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (int)format);
641120}
641121
641122ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
641123{
641124 ZSTD_bounds bounds = { 0, 0, 0 };
641125 switch(dParam) {
641126 case ZSTD_d_windowLogMax:
641127 bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
641128 bounds.upperBound = ZSTD_WINDOWLOG_MAX;
641129 return bounds;
641130 case ZSTD_d_format:
641131 bounds.lowerBound = (int)ZSTD_f_zstd1;
641132 bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
641133 ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
641134 return bounds;
641135 case ZSTD_d_stableOutBuffer:
641136 bounds.lowerBound = (int)ZSTD_bm_buffered;
641137 bounds.upperBound = (int)ZSTD_bm_stable;
641138 return bounds;
641139 case ZSTD_d_forceIgnoreChecksum:
641140 bounds.lowerBound = (int)ZSTD_d_validateChecksum;
641141 bounds.upperBound = (int)ZSTD_d_ignoreChecksum;
641142 return bounds;
641143 case ZSTD_d_refMultipleDDicts:
641144 bounds.lowerBound = (int)ZSTD_rmd_refSingleDDict;
641145 bounds.upperBound = (int)ZSTD_rmd_refMultipleDDicts;
641146 return bounds;
641147 case ZSTD_d_disableHuffmanAssembly:
641148 bounds.lowerBound = 0;
641149 bounds.upperBound = 1;
641150 return bounds;
641151 case ZSTD_d_maxBlockSize:
641152 bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
641153 bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
std::basic_string< Char > format(const S &format_str, Args &&... args)
Definition duckdb.cpp:16295
ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx *dctx, ZSTD_dParameter param, int value)
Definition duckdb.cpp:641200
ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
Definition duckdb.cpp:641115

◆ ZSTD_DCtx_setParameter()

size_t duckdb_zstd::ZSTD_DCtx_setParameter ( ZSTD_DCtx * dctx,
ZSTD_dParameter param,
int value )

ZSTD_DCtx_setParameter() : Set one compression parameter, selected by enum ZSTD_dParameter. All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds(). Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). Setting a parameter is only possible during frame initialization (before starting decompression).

Returns
: 0, or an error code (which can be tested using ZSTD_isError()).
641202 :;
641203 }
641204 RETURN_ERROR(parameter_unsupported, "");
641205}
641206
641207size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
641208{
641209 RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
641210 switch(dParam) {
641211 case ZSTD_d_windowLogMax:
641212 if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT;
641213 CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
641214 dctx->maxWindowSize = ((size_t)1) << value;
641215 return 0;
641216 case ZSTD_d_format:
641217 CHECK_DBOUNDS(ZSTD_d_format, value);
641218 dctx->format = (ZSTD_format_e)value;
641219 return 0;
641220 case ZSTD_d_stableOutBuffer:
641221 CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value);
641222 dctx->outBufferMode = (ZSTD_bufferMode_e)value;
641223 return 0;
641224 case ZSTD_d_forceIgnoreChecksum:
641225 CHECK_DBOUNDS(ZSTD_d_forceIgnoreChecksum, value);
641226 dctx->forceIgnoreChecksum = (ZSTD_forceIgnoreChecksum_e)value;
641227 return 0;
641228 case ZSTD_d_refMultipleDDicts:
641229 CHECK_DBOUNDS(ZSTD_d_refMultipleDDicts, value);
641230 if (dctx->staticSize != 0) {
641231 RETURN_ERROR(parameter_unsupported, "Static dctx does not support multiple DDicts!");
641232 }
641233 dctx->refMultipleDDicts = (ZSTD_refMultipleDDicts_e)value;
641234 return 0;
641235 case ZSTD_d_disableHuffmanAssembly:
641236 CHECK_DBOUNDS(ZSTD_d_disableHuffmanAssembly, value);
641237 dctx->disableHufAsm = value != 0;
641238 return 0;
641239 case ZSTD_d_maxBlockSize:

◆ ZSTD_DCtx_reset()

size_t duckdb_zstd::ZSTD_DCtx_reset ( ZSTD_DCtx * dctx,
ZSTD_ResetDirective reset )

ZSTD_DCtx_reset() : Return a DCtx to clean state. Session and parameters can be reset jointly or separately. Parameters can only be reset when no active frame is being decompressed.

Returns
: 0, or an error code, which can be tested with ZSTD_isError()
641243 :;
641244 }
641245 RETURN_ERROR(parameter_unsupported, "");
641246}
641247
641248size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
641249{
641250 if ( (reset == ZSTD_reset_session_only)
641251 || (reset == ZSTD_reset_session_and_parameters) ) {
641252 dctx->streamStage = zdss_init;
641253 dctx->noForwardProgress = 0;
641254 dctx->isFrameDecompression = 1;
641255 }
641256 if ( (reset == ZSTD_reset_parameters)
ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx *dctx, ZSTD_ResetDirective reset)
Definition duckdb.cpp:641241
Here is the caller graph for this function:

◆ ZSTD_createCStream()

ZSTD_CStream * duckdb_zstd::ZSTD_createCStream ( void )

◆ ZSTD_freeCStream()

size_t duckdb_zstd::ZSTD_freeCStream ( ZSTD_CStream * zcs)
625512{ /* CStream and CCtx are now same object */

◆ ZSTD_compressStream2()

size_t duckdb_zstd::ZSTD_compressStream2 ( ZSTD_CCtx * cctx,
ZSTD_outBuffer * output,
ZSTD_inBuffer * input,
ZSTD_EndDirective endOp )

ZSTD_compressStream2() : Requires v1.4.0+ Behaves about the same as ZSTD_compressStream, with additional control on end directive.

  • Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
  • Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)
  • output->pos must be <= dstCapacity, input->pos must be <= srcSize
  • output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.
  • endOp must be a valid directive
  • When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.
  • When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available, and then immediately returns, just indicating that there is some data remaining to be flushed. The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.
  • Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking.
  • Returns
    provides a minimum amount of data remaining to be flushed from internal buffers or an error code, which can be tested using ZSTD_isError(). if
    != 0, flush is not fully completed, there is still some data left within internal buffers. This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers. For ZSTD_e_end,
    == 0 when internal buffers are fully flushed and frame is completed.
  • after a ZSTD_e_end directive, if internal buffer is not fully flushed (
    Returns
    != 0), only ZSTD_e_end or ZSTD_e_flush operations are allowed. Before starting a new compression job, or changing compression parameters, it is required to fully flush internal buffers.
  • note: if an operation ends with an error, it may leave @cctx in an undefined state. Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state. In order to be re-employed after an error, a state must be reset, which can be done explicitly (ZSTD_CCtx_reset()), or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())
626018{
626019 DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
626020 /* check conditions */
626021 RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
626022 RETURN_ERROR_IF(input->pos > input->size, srcSize_wrong, "invalid input buffer");
626023 RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
626024 assert(cctx != NULL);
626025
626026 /* transparent initialization stage */
626027 if (cctx->streamStage == zcss_init) {
626028 size_t const inputSize = input->size - input->pos; /* no obligation to start from pos==0 */
626029 size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;
626030 if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */
626031 && (endOp == ZSTD_e_continue) /* no flush requested, more input to come */
626032 && (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) { /* not even reached one block yet */
626033 if (cctx->stableIn_notConsumed) { /* not the first time */
626034 /* check stable source guarantees */
626035 RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
626036 RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
626037 }
626038 /* pretend input was consumed, to give a sense forward progress */
626039 input->pos = input->size;
626040 /* save stable inBuffer, for later control, and flush/end */
626041 cctx->expectedInBuffer = *input;
626042 /* but actually input wasn't consumed, so keep track of position from where compression shall resume */
626043 cctx->stableIn_notConsumed += inputSize;
626044 /* don't initialize yet, wait for the first block of flush() order, for better parameters adaptation */
626045 return ZSTD_FRAMEHEADERSIZE_MIN(cctx->requestedParams.format); /* at least some header to produce */
626046 }
626047 FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize), "compressStream2 initialization failed");
626048 ZSTD_setBufferExpectations(cctx, output, input); /* Set initial buffer expectations now that we've initialized */
626049 }
626050 /* end of transparent initialization stage */
626051
626052 FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
626053 /* compression stage */
626054#ifdef ZSTD_MULTITHREAD
626055 if (cctx->appliedParams.nbWorkers > 0) {
626056 size_t flushMin;
626057 if (cctx->cParamsChanged) {
626058 ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
626059 cctx->cParamsChanged = 0;
626060 }
626061 if (cctx->stableIn_notConsumed) {
626062 assert(cctx->appliedParams.inBufferMode == ZSTD_bm_stable);
626063 /* some early data was skipped - make it available for consumption */
626064 assert(input->pos >= cctx->stableIn_notConsumed);
626065 input->pos -= cctx->stableIn_notConsumed;
626066 cctx->stableIn_notConsumed = 0;
626067 }
626068 for (;;) {
626069 size_t const ipos = input->pos;
626070 size_t const opos = output->pos;
626071 flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
626072 cctx->consumedSrcSize += (U64)(input->pos - ipos);
626073 cctx->producedCSize += (U64)(output->pos - opos);
626074 if ( ZSTD_isError(flushMin)
626075 || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
626076 if (flushMin == 0)
626077 ZSTD_CCtx_trace(cctx, 0);
626078 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
626079 }
626080 FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
626081
626082 if (endOp == ZSTD_e_continue) {
626083 /* We only require some progress with ZSTD_e_continue, not maximal progress.
626084 * We're done if we've consumed or produced any bytes, or either buffer is
626085 * full.
626086 */
626087 if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
626088 break;
626089 } else {
626090 assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
626091 /* We require maximal progress. We're done when the flush is complete or the
626092 * output buffer is full.
626093 */
626094 if (flushMin == 0 || output->pos == output->size)
626095 break;
626096 }
626097 }
626098 DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
626099 /* Either we don't require maximum forward progress, we've finished the
626100 * flush, or we are out of output space.
626101 */
626102 assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
626103 ZSTD_setBufferExpectations(cctx, output, input);
626104 return flushMin;
#define FORWARD_IF_ERROR(err,...)
Definition duckdb.cpp:609022
#define assert(x)
Definition duckdb.cpp:486071
ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx *cctx, ZSTD_ResetDirective reset)
Definition duckdb.cpp:621064
void ZSTD_CCtx_trace(ZSTD_CCtx *cctx, size_t extraCSize)
Definition duckdb.cpp:624951
void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx *mtctx, const ZSTD_CCtx_params *cctxParams)
Definition duckdb.cpp:635917
size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx *mtctx, ZSTD_outBuffer *output, ZSTD_inBuffer *input, ZSTD_EndDirective endOp)
Definition duckdb.cpp:636649
ZSTDLIB_API unsigned ZSTD_isError(size_t code)
Definition duckdb.cpp:614327
const void * src
Definition duckdb.cpp:407807
size_t size
Definition duckdb.cpp:407808
size_t pos
Definition duckdb.cpp:407809
Here is the caller graph for this function:

◆ ZSTD_CStreamInSize()

size_t duckdb_zstd::ZSTD_CStreamInSize ( void )

recommended size for input buffer

Here is the caller graph for this function:

◆ ZSTD_CStreamOutSize()

size_t duckdb_zstd::ZSTD_CStreamOutSize ( void )

recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_initCStream()

size_t duckdb_zstd::ZSTD_initCStream ( ZSTD_CStream * zcs,
int compressionLevel )

Equivalent to:

ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);

Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API to compress with a dictionary.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressStream()

size_t duckdb_zstd::ZSTD_compressStream ( ZSTD_CStream * zcs,
ZSTD_outBuffer * output,
ZSTD_inBuffer * input )

Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue). NOTE: The return value is different. ZSTD_compressStream() returns a hint for the next read size (if non-zero and not an error). ZSTD_compressStream2() returns the minimum nb of bytes left to flush (if non-zero and not an error).

Here is the caller graph for this function:

◆ ZSTD_flushStream()

size_t duckdb_zstd::ZSTD_flushStream ( ZSTD_CStream * zcs,
ZSTD_outBuffer * output )

Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush).

ZSTD_flushStream() :

Returns
: amount of data remaining to flush
626652 { NULL, 0, 0 };
626653 const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
626654 return stableInput ? zcs->expectedInBuffer : nullInput;
626655}
626656
Here is the caller graph for this function:

◆ ZSTD_endStream()

size_t duckdb_zstd::ZSTD_endStream ( ZSTD_CStream * zcs,
ZSTD_outBuffer * output )

Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_createDStream()

ZSTD_DStream * duckdb_zstd::ZSTD_createDStream ( void )

◆ ZSTD_freeDStream()

size_t duckdb_zstd::ZSTD_freeDStream ( ZSTD_DStream * zds)

◆ ZSTD_initDStream()

size_t duckdb_zstd::ZSTD_initDStream ( ZSTD_DStream * zds)

ZSTD_initDStream() : Initialize/reset DStream state for new decompression operation. Call before new decompression operation using same DStream.

Note : This function is redundant with the advanced API and equivalent to: ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); ZSTD_DCtx_refDDict(zds, NULL);

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_decompressStream()

size_t duckdb_zstd::ZSTD_decompressStream ( ZSTD_DStream * zds,
ZSTD_outBuffer * output,
ZSTD_inBuffer * input )

ZSTD_decompressStream() : Streaming decompression function. Call repetitively to consume full input updating it as necessary. Function will update both input and output pos fields exposing current state via these fields:

  • input.pos < input.size, some input remaining and caller should provide remaining input on the next call.
  • output.pos < output.size, decoder finished and flushed all remaining buffers.
  • output.pos == output.size, potentially uncflushed data present in the internal buffers, call ZSTD_decompressStream() again to flush remaining data to output. Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX.
Returns
: 0 when a frame is completely decoded and fully flushed, or an error code, which can be tested using ZSTD_isError(), or any other value > 0, which means there is some decoding or flushing to do to complete current frame.

Note: when an operation returns with an error code, the @zds state may be left in undefined state. It's UB to invoke ZSTD_decompressStream() on such a state. In order to re-use such a state, it must be first reset, which can be done explicitly (ZSTD_DCtx_reset()), or is implied for operations starting some new decompression job (ZSTD_initDStream, ZSTD_decompressDCtx(), ZSTD_decompress_usingDict())

Here is the caller graph for this function:

◆ ZSTD_DStreamInSize()

size_t duckdb_zstd::ZSTD_DStreamInSize ( void )

recommended size for input buffer

Here is the caller graph for this function:

◆ ZSTD_DStreamOutSize()

size_t duckdb_zstd::ZSTD_DStreamOutSize ( void )

recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances.

Here is the caller graph for this function:

◆ ZSTD_compress_usingDict()

size_t duckdb_zstd::ZSTD_compress_usingDict ( ZSTD_CCtx * ctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const void * dict,
size_t dictSize,
int compressionLevel )

Simple dictionary API

ZSTD_compress_usingDict() : Compression at an explicit compression level using a Dictionary. A dictionary can be any arbitrary data segment (also called a prefix), or a buffer with specified information (see zdict.h). Note : This function loads the dictionary, resulting in significant startup delay. It's intended for a dictionary used only once. Note 2 : When dict == NULL || dictSize < 8 no dictionary is used.

Here is the call graph for this function:

◆ ZSTD_decompress_usingDict()

size_t duckdb_zstd::ZSTD_decompress_usingDict ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const void * dict,
size_t dictSize )

ZSTD_decompress_usingDict() : Decompression using a known Dictionary. Dictionary must be identical to the one used during compression. Note : This function loads the dictionary, resulting in significant startup delay. It's intended for a dictionary used only once. Note : When dict == NULL || dictSize < 8 no dictionary is used.

◆ ZSTD_createCDict()

ZSTD_CDict * duckdb_zstd::ZSTD_createCDict ( const void * dictBuffer,
size_t dictSize,
int compressionLevel )

ZSTD_createCDict() : When compressing multiple messages or blocks using the same dictionary, it's recommended to digest the dictionary only once, since it's a costly operation. ZSTD_createCDict() will create a state from digesting a dictionary. The resulting state can be used for future compression operations with very limited startup cost. ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict. Note 1 : Consider experimental function ZSTD_createCDict_byReference() if you prefer to not duplicate @dictBuffer content. Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer, in which case the only thing that it transports is the @compressionLevel. This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively, expecting a ZSTD_CDict parameter with any data, including those without a known dictionary.

Here is the call graph for this function:

◆ ZSTD_freeCDict()

size_t duckdb_zstd::ZSTD_freeCDict ( ZSTD_CDict * CDict)

ZSTD_freeCDict() : Function frees memory allocated by ZSTD_createCDict(). If a NULL pointer is passed, no operation is performed.

Here is the caller graph for this function:

◆ ZSTD_compress_usingCDict()

size_t duckdb_zstd::ZSTD_compress_usingCDict ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const ZSTD_CDict * cdict )

ZSTD_compress_usingCDict() : Compression using a digested Dictionary. Recommended when same dictionary is used multiple times. Note : compression level is decided at dictionary creation time, and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no)

ZSTD_compress_usingCDict() : Compression using a digested Dictionary. Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times. Note that compression parameters are decided at CDict creation time while frame parameters are hardcoded

◆ ZSTD_createDDict()

ZSTD_DDict * duckdb_zstd::ZSTD_createDDict ( const void * dict,
size_t dictSize )

ZSTD_createDDict() : Create a digested dictionary, ready to start decompression operation without startup delay. dictBuffer can be released after DDict creation, as its content is copied inside DDict.

ZSTD_createDDict() : Create a digested dictionary, to start decompression without startup delay. dict content is copied inside DDict. Consequently, dict can be released after ZSTD_DDict creation

◆ ZSTD_freeDDict()

size_t duckdb_zstd::ZSTD_freeDDict ( ZSTD_DDict * ddict)

ZSTD_freeDDict() : Function frees memory allocated with ZSTD_createDDict() If a NULL pointer is passed, no operation is performed.

◆ ZSTD_decompress_usingDDict()

size_t duckdb_zstd::ZSTD_decompress_usingDDict ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const ZSTD_DDict * ddict )

ZSTD_decompress_usingDDict() : Decompression using a digested Dictionary. Recommended when same dictionary is used multiple times.

ZSTD_decompress_usingDDict() : Decompression using a pre-digested Dictionary Use dictionary without significant overhead.

Here is the caller graph for this function:

◆ ZSTD_getDictID_fromDict()

unsigned duckdb_zstd::ZSTD_getDictID_fromDict ( const void * dict,
size_t dictSize )

Dictionary helper functions

ZSTD_getDictID_fromDict() : Requires v1.4.0+ Provides the dictID stored within dictionary. if

Returns
== 0, the dictionary is not conformant with Zstandard specification. It can still be loaded, but as a content-only dictionary.

ZSTD_getDictID_fromDict() : Provides the dictID stored within dictionary. if

Returns
== 0, the dictionary is not conformant with Zstandard specification. It can still be loaded, but as a content-only dictionary.

◆ ZSTD_getDictID_fromCDict()

unsigned duckdb_zstd::ZSTD_getDictID_fromCDict ( const ZSTD_CDict * cdict)

ZSTD_getDictID_fromCDict() : Requires v1.5.0+ Provides the dictID of the dictionary loaded into cdict. If

Returns
== 0, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries.

ZSTD_getDictID_fromCDict() : Provides the dictID of the dictionary loaded into cdict. If

Returns
== 0, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries.

◆ ZSTD_getDictID_fromDDict()

unsigned duckdb_zstd::ZSTD_getDictID_fromDDict ( const ZSTD_DDict * ddict)

ZSTD_getDictID_fromDDict() : Requires v1.4.0+ Provides the dictID of the dictionary loaded into ddict. If

Returns
== 0, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries.

ZSTD_getDictID_fromDDict() : Provides the dictID of the dictionary loaded into ddict. If

Returns
== 0, the dictionary is not conformant to Zstandard specification, or empty. Non-conformant dictionaries can still be loaded, but as content-only dictionaries.

◆ ZSTD_getDictID_fromFrame()

unsigned duckdb_zstd::ZSTD_getDictID_fromFrame ( const void * src,
size_t srcSize )

ZSTD_getDictID_fromFrame() : Requires v1.4.0+ Provides the dictID required to decompressed the frame stored within src. If

Returns
== 0, the dictID could not be decoded. This could for one of the following reasons :
  • The frame does not require a dictionary to be decoded (most common case).
  • The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information. Note : this use case also happens when using a non-conformant dictionary.
  • srcSize is too small, and as a result, the frame header could not be decoded (only possible if srcSize < ZSTD_FRAMEHEADERSIZE_MAX).
  • This is not a Zstandard frame. When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code.

ZSTD_getDictID_fromFrame() : Provides the dictID required to decompress frame stored within src. If

Returns
== 0, the dictID could not be decoded. This could for one of the following reasons :
  • The frame does not require a dictionary (most common case).
  • The frame was built with dictID intentionally removed. Needed dictionary is a hidden piece of information. Note : this use case also happens when using a non-conformant dictionary.
  • srcSize is too small, and as a result, frame header could not be decoded. Note : possible if srcSize < ZSTD_FRAMEHEADERSIZE_MAX.
  • This is not a Zstandard frame. When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtx_loadDictionary()

size_t duckdb_zstd::ZSTD_CCtx_loadDictionary ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize )

Advanced dictionary and prefix API (Requires v1.4.0+)

This API allows dictionaries to be used with ZSTD_compress2(), ZSTD_compressStream2(), and ZSTD_decompressDCtx(). Dictionaries are sticky, they remain valid when same context is reused, they only reset when the context is reset with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters. In contrast, Prefixes are single-use.

ZSTD_CCtx_loadDictionary() : Requires v1.4.0+ Create an internal CDict from dict buffer. Decompression will have to use same dictionary.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary, meaning "return to no-dictionary mode". Note 1 : Dictionary is sticky, it will be used for all future compressed frames, until parameters are reset, a new dictionary is loaded, or the dictionary is explicitly invalidated by loading a NULL dictionary. Note 2 : Loading a dictionary involves building tables. It's also a CPU consuming operation, with non-negligible impact on latency. Tables are dependent on compression parameters, and for this reason, compression parameters can no longer be changed after loading a dictionary. Note 3 :dict content will be copied internally. Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead. In such a case, dictionary buffer must outlive its users. Note 4 : Use ZSTD_CCtx_loadDictionary_advanced() to precisely select how dictionary content must be interpreted. Note 5 : This method does not benefit from LDM (long distance mode). If you want to employ LDM on some large dictionary content, prefer employing ZSTD_CCtx_refPrefix() described below.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtx_refCDict()

size_t duckdb_zstd::ZSTD_CCtx_refCDict ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict )

ZSTD_CCtx_refCDict() : Requires v1.4.0+ Reference a prepared dictionary, to be used for all future compressed frames. Note that compression parameters are enforced from within CDict, and supersede any compression parameter previously set within CCtx. The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs. The ignored parameters will be used again if the CCtx is returned to no-dictionary mode. The dictionary will remain valid for future compressed frames using same CCtx.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Special : Referencing a NULL CDict means "return to no-dictionary mode". Note 1 : Currently, only one dictionary can be managed. Referencing a new dictionary effectively "discards" any previous one. Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtx_refPrefix()

size_t duckdb_zstd::ZSTD_CCtx_refPrefix ( ZSTD_CCtx * cctx,
const void * prefix,
size_t prefixSize )

ZSTD_CCtx_refPrefix() : Requires v1.4.0+ Reference a prefix (single-usage dictionary) for next compressed frame. A prefix is only used once. Tables are discarded at end of frame (ZSTD_e_end). Decompression will need same prefix to properly regenerate data. Compressing with a prefix is similar in outcome as performing a diff and compressing it, but performs much faster, especially during decompression (compression speed is tunable with compression level). This method is compatible with LDM (long distance mode).

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary Note 1 : Prefix buffer is referenced. It must outlive compression. Its content must remain unmodified during compression. Note 2 : If the intention is to diff some large src data blob with some prior version of itself, ensure that the window size is large enough to contain the entire source. See ZSTD_c_windowLog. Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters. It's a CPU consuming operation, with non-negligible impact on latency. If there is a need to use the same prefix multiple times, consider loadDictionary instead. Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent). Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation.

◆ ZSTD_DCtx_loadDictionary()

size_t duckdb_zstd::ZSTD_DCtx_loadDictionary ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize )

ZSTD_DCtx_loadDictionary() : Requires v1.4.0+ Create an internal DDict from dict buffer, to be used to decompress all future frames. The dictionary remains valid for all future frames, until explicitly invalidated, or a new dictionary is loaded.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, meaning "return to no-dictionary mode". Note 1 : Loading a dictionary involves building tables, which has a non-negligible impact on CPU usage and latency. It's recommended to "load once, use many times", to amortize the cost Note 2 :dict content will be copied internally, so dict can be released after loading. Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead. Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of how dictionary content is loaded and interpreted.
Here is the caller graph for this function:

◆ ZSTD_DCtx_refDDict()

size_t duckdb_zstd::ZSTD_DCtx_refDDict ( ZSTD_DCtx * dctx,
const ZSTD_DDict * ddict )

ZSTD_DCtx_refDDict() : Requires v1.4.0+ Reference a prepared dictionary, to be used to decompress next frames. The dictionary remains active for decompression of future frames using same DCtx.

If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function will store the DDict references in a table, and the DDict used for decompression will be determined at decompression time, as per the dict ID in the frame. The memory for the table is allocated on the first call to refDDict, and can be freed with ZSTD_freeDCtx().

If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary will be managed, and referencing a dictionary effectively "discards" any previous one.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Special: referencing a NULL DDict means "return to no-dictionary mode". Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_DCtx_refPrefix()

size_t duckdb_zstd::ZSTD_DCtx_refPrefix ( ZSTD_DCtx * dctx,
const void * prefix,
size_t prefixSize )

ZSTD_DCtx_refPrefix() : Requires v1.4.0+ Reference a prefix (single-usage dictionary) to decompress next frame. This is the reverse operation of ZSTD_CCtx_refPrefix(), and must use the same prefix as the one used during compression. Prefix is only used once. Reference is discarded at end of frame. End of frame is reached when ZSTD_decompressStream() returns 0.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()). Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary Note 2 : Prefix buffer is referenced. It must outlive decompression. Prefix buffer must remain unmodified up to the end of frame, reached when ZSTD_decompressStream() returns 0. Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. A full dictionary is more costly, as it requires building tables.
Here is the call graph for this function:

◆ ZSTD_sizeof_CCtx()

size_t duckdb_zstd::ZSTD_sizeof_CCtx ( const ZSTD_CCtx * cctx)

ZSTD_sizeof_*() : Requires v1.4.0+ These functions give the current memory usage of selected object. Note that object memory usage can evolve (increase or decrease) over time.

◆ ZSTD_sizeof_DCtx()

size_t duckdb_zstd::ZSTD_sizeof_DCtx ( const ZSTD_DCtx * dctx)

◆ ZSTD_sizeof_CStream()

size_t duckdb_zstd::ZSTD_sizeof_CStream ( const ZSTD_CStream * zcs)

◆ ZSTD_sizeof_DStream()

size_t duckdb_zstd::ZSTD_sizeof_DStream ( const ZSTD_DStream * zds)

◆ ZSTD_sizeof_CDict()

size_t duckdb_zstd::ZSTD_sizeof_CDict ( const ZSTD_CDict * cdict)

◆ ZSTD_sizeof_DDict()

size_t duckdb_zstd::ZSTD_sizeof_DDict ( const ZSTD_DDict * ddict)

◆ ZSTD_findDecompressedSize()

unsigned long long duckdb_zstd::ZSTD_findDecompressedSize ( const void * src,
size_t srcSize )

Frame header and size functions

ZSTD_findDecompressedSize() : src should point to the start of a series of ZSTD encoded and/or skippable frames srcSize must be the exact size of this series (i.e. there should be a frame boundary at src + srcSize)

Returns
: - decompressed size of all data in all successive frames
  • if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
  • if an error occurred: ZSTD_CONTENTSIZE_ERROR

note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. When return==ZSTD_CONTENTSIZE_UNKNOWN, data to decompress could be any size. In which case, it's necessary to use streaming mode to decompress data. note 2 : decompressed size is always present when compression is done with ZSTD_compress() note 3 : decompressed size can be very large (64-bits value), potentially larger than what local system can handle as a single memory segment. In which case, it's necessary to use streaming mode to decompress data. note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. Always ensure result fits within application's authorized limits. Each application can set its own limits. note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to read each contained frame header. This is fast as most of the data is skipped, however it does mean that all frame data must be present and valid.

ZSTD_findDecompressedSize() : srcSize must be the exact length of some number of ZSTD compressed and/or skippable frames note: compatible with legacy mode

Returns
: decompressed size of the frames contained

◆ ZSTD_decompressBound()

unsigned long long duckdb_zstd::ZSTD_decompressBound ( const void * src,
size_t srcSize )

ZSTD_decompressBound() : src should point to the start of a series of ZSTD encoded and/or skippable frames srcSize must be the exact size of this series (i.e. there should be a frame boundary at src + srcSize)

Returns
: - upper-bound for the decompressed size of all data in all successive frames
  • if an error occurred: ZSTD_CONTENTSIZE_ERROR

note 1 : an error can occur if src contains an invalid or incorrectly formatted frame. note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of src. in this case, ZSTD_findDecompressedSize and ZSTD_decompressBound return the same value. note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: upper-bound = # blocks * min(128 KB, Window_Size)

ZSTD_decompressBound() : compatible with legacy mode src must point to the start of a ZSTD frame or a skippeable frame srcSize must be at least as large as the frame contained

Returns
: the maximum decompressed size of the compressed source
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_frameHeaderSize()

size_t duckdb_zstd::ZSTD_frameHeaderSize ( const void * src,
size_t srcSize )

ZSTD_frameHeaderSize() : srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX.

Returns
: size of the Frame Header, or an error code (if srcSize is too small)

ZSTD_frameHeaderSize() : srcSize must be >= ZSTD_frameHeaderSize_prefix.

Returns
: size of the Frame Header, or an error code (if srcSize is too small)

◆ ZSTD_getFrameHeader()

size_t duckdb_zstd::ZSTD_getFrameHeader ( ZSTD_frameHeader * zfhPtr,
const void * src,
size_t srcSize )

ZSTD_getFrameHeader() : decode Frame Header, or requires larger srcSize.

Returns
: 0, zfhPtr is correctly filled, >0, srcSize is too small, value is wanted srcSize amount, or an error code, which can be tested using ZSTD_isError() doesn't consume input

ZSTD_getFrameHeader() : decode Frame Header, or require larger srcSize. note : this function does not consume input, it only reads it.

Returns
: 0, zfhPtr is correctly filled, >0, srcSize is too small, value is wanted srcSize amount, or an error code, which can be tested using ZSTD_isError()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getFrameHeader_advanced()

size_t duckdb_zstd::ZSTD_getFrameHeader_advanced ( ZSTD_frameHeader * zfhPtr,
const void * src,
size_t srcSize,
ZSTD_format_e format )

ZSTD_getFrameHeader_advanced() : same as ZSTD_getFrameHeader(), with added capability to select a format (like ZSTD_f_zstd1_magicless)

ZSTD_getFrameHeader_advanced() : decode Frame Header, or require larger srcSize. note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless

Returns
: 0, zfhPtr is correctly filled, >0, srcSize is too small, value is wanted srcSize amount, or an error code, which can be tested using ZSTD_isError()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_decompressionMargin()

size_t duckdb_zstd::ZSTD_decompressionMargin ( const void * src,
size_t srcSize )

ZSTD_decompressionMargin() : Zstd supports in-place decompression, where the input and output buffers overlap. In this case, the output buffer must be at least (Margin + Output_Size) bytes large, and the input buffer must be at the end of the output buffer.

_______________________ Output Buffer ________________________ | | | ____ Input Buffer ____| | | | v v v |------------------------------------—|--------—|-------—| ^ ^ ^ |___________________ Output_Size ___________________|_ Margin _|

NOTE: See also ZSTD_DECOMPRESSION_MARGIN(). NOTE: This applies only to single-pass decompression through ZSTD_decompress() or ZSTD_decompressDCtx(). NOTE: This function supports multi-frame input.

Parameters
srcThe compressed frame(s)
srcSizeThe size of the compressed frame(s)
Returns
The decompression margin or an error that can be checked with ZSTD_isError().

◆ ZSTD_sequenceBound()

size_t duckdb_zstd::ZSTD_sequenceBound ( size_t srcSize)

ZSTD_sequenceBound() : srcSize : size of the input buffer

Returns
: upper-bound for the number of sequences that can be generated from a buffer of srcSize bytes

note : returns number of sequences - to get bytes, multiply by sizeof(ZSTD_Sequence).

Here is the caller graph for this function:

◆ ZSTD_generateSequences()

size_t duckdb_zstd::ZSTD_generateSequences ( ZSTD_CCtx * zc,
ZSTD_Sequence * outSeqs,
size_t outSeqsSize,
const void * src,
size_t srcSize )

ZSTD_generateSequences() : WARNING: This function is meant for debugging and informational purposes ONLY! Its implementation is flawed, and it will be deleted in a future version. It is not guaranteed to succeed, as there are several cases where it will give up and fail. You should NOT use this function in production code.

This function is deprecated, and will be removed in a future version.

Generate sequences using ZSTD_compress2(), given a source buffer.

Parameters
zcThe compression context to be used for ZSTD_compress2(). Set any compression parameters you need on this context.
outSeqsThe output sequences buffer of size outSeqsSize
outSeqsSizeThe size of the output sequences buffer. ZSTD_sequenceBound(srcSize) is an upper bound on the number of sequences that can be generated.
srcThe source buffer to generate sequences from of size srcSize.
srcSizeThe size of the source buffer.

Each block will end with a dummy sequence with offset == 0, matchLength == 0, and litLength == length of last literals. litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) simply acts as a block delimiter.

Returns
The number of sequences generated, necessarily less than ZSTD_sequenceBound(srcSize), or an error code that can be checked with ZSTD_isError().
Here is the call graph for this function:

◆ ZSTD_mergeBlockDelimiters()

size_t duckdb_zstd::ZSTD_mergeBlockDelimiters ( ZSTD_Sequence * sequences,
size_t seqsSize )

ZSTD_mergeBlockDelimiters() : Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals by merging them into the literals of the next sequence.

As such, the final generated result has no explicit representation of block boundaries, and the final last literals segment is not represented in the sequences.

The output of this function can be fed into ZSTD_compressSequences() with CCtx setting of ZSTD_c_blockDelimiters as ZSTD_sf_noBlockDelimiters

Returns
: number of sequences left after merging

◆ ZSTD_compressSequences()

size_t duckdb_zstd::ZSTD_compressSequences ( ZSTD_CCtx * cctx,
void * dst,
size_t dstSize,
const ZSTD_Sequence * inSeqs,
size_t inSeqsSize,
const void * src,
size_t srcSize )

ZSTD_compressSequences() : Compress an array of ZSTD_Sequence, associated with @src buffer, into dst. @src contains the entire input (not just the literals). If @srcSize > sum(sequence.length), the remaining bytes are considered all literals If a dictionary is included, then the cctx should reference the dict. (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.) The entire source is compressed into a single frame.

The compression behavior changes based on cctx params. In particular: If ZSTD_c_blockDelimiters == ZSTD_sf_noBlockDelimiters, the array of ZSTD_Sequence is expected to contain no block delimiters (defined in ZSTD_Sequence). Block boundaries are roughly determined based on the block size derived from the cctx, and sequences may be split. This is the default setting.

If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided.

If ZSTD_c_validateSequences == 0, this function will blindly accept the sequences provided. Invalid sequences cause undefined behavior. If ZSTD_c_validateSequences == 1, then if sequence is invalid (see doc/zstd_compression_format.md for specifics regarding offset/matchlength requirements) then the function will bail out and return an error.

In addition to the two adjustable experimental params, there are other important cctx params.

  • ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN.
  • ZSTD_c_compressionLevel accordingly adjusts the strength of the entropy coder, as it would in typical compression.
  • ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md

Note: Repcodes are, as of now, always re-calculated within this function, so ZSTD_Sequence::rep is unused. Note 2: Once we integrate ability to ingest repcodes, the explicit block delims mode must respect those repcodes exactly, and cannot emit an RLE block that disagrees with the repcode history

Returns
: final compressed size, or a ZSTD error code.

◆ ZSTD_writeSkippableFrame()

size_t duckdb_zstd::ZSTD_writeSkippableFrame ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
unsigned magicVariant )

ZSTD_writeSkippableFrame() : Generates a zstd skippable frame containing data given by src, and writes it to dst buffer.

Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number, ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. As such, the parameter magicVariant controls the exact skippable frame magic number variant used, so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant.

Returns an error if destination buffer is not large enough, if the source size is not representable with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid).

Returns
: number of bytes written or a ZSTD error.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_readSkippableFrame()

size_t duckdb_zstd::ZSTD_readSkippableFrame ( void * dst,
size_t dstCapacity,
unsigned * magicVariant,
const void * src,
size_t srcSize )

ZSTD_readSkippableFrame() : Retrieves a zstd skippable frame containing data given by src, and writes it to dst buffer.

The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested in the magicVariant.

Returns an error if destination buffer is not large enough, or if the frame is not skippable.

Returns
: number of bytes written or a ZSTD error.

ZSTD_readSkippableFrame() : Retrieves content of a skippable frame, and writes it to dst buffer.

The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested in the magicVariant.

Returns an error if destination buffer is not large enough, or if this is not a valid skippable frame.

Returns
: number of bytes written or a ZSTD error.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_isSkippableFrame()

unsigned duckdb_zstd::ZSTD_isSkippableFrame ( const void * buffer,
size_t size )

ZSTD_isSkippableFrame() : Tells if the content of buffer starts with a valid Frame Identifier for a skippable frame.

ZSTD_isSkippableFrame() : Tells if the content of buffer starts with a valid Frame Identifier for a skippable frame. Note : Frame Identifier is 4 bytes. If size < 4,

Returns
will always be 0.
Here is the caller graph for this function:

◆ ZSTD_estimateCCtxSize()

size_t duckdb_zstd::ZSTD_estimateCCtxSize ( int maxCompressionLevel)

Memory management

ZSTD_estimate*() : These functions make it possible to estimate memory usage of a future {D,C}Ctx, before its creation. This is useful in combination with ZSTD_initStatic(), which makes it possible to employ a static buffer for ZSTD_CCtx* state.

ZSTD_estimateCCtxSize() will provide a memory budget large enough to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2() associated with any compression level up to max specified one. The estimate will assume the input may be arbitrarily large, which is the worst case.

Note that the size estimation is specific for one-shot compression, it is not valid for streaming (see ZSTD_estimateCStreamSize*()) nor other potential ways of using a ZSTD_CCtx* state.

When srcSize can be bound by a known and rather "small" value, this knowledge can be used to provide a tighter budget estimation because the ZSTD_CCtx* state will need less memory for small inputs. This tighter estimation can be provided by employing more advanced functions ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits.

Note : only single-threaded compression is supported. ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.

Here is the call graph for this function:

◆ ZSTD_estimateCCtxSize_usingCParams()

size_t duckdb_zstd::ZSTD_estimateCCtxSize_usingCParams ( ZSTD_compressionParameters cParams)

◆ ZSTD_estimateCCtxSize_usingCCtxParams()

size_t duckdb_zstd::ZSTD_estimateCCtxSize_usingCCtxParams ( const ZSTD_CCtx_params * params)

◆ ZSTD_estimateDCtxSize()

size_t duckdb_zstd::ZSTD_estimateDCtxSize ( void )

◆ ZSTD_estimateCStreamSize()

size_t duckdb_zstd::ZSTD_estimateCStreamSize ( int maxCompressionLevel)

ZSTD_estimateCStreamSize() : ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression using any compression level up to the max specified one. It will also consider src size to be arbitrarily "large", which is a worst case scenario. If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. Note : CStream size estimation is only correct for single-threaded compression. ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. Size estimates assume that no external sequence producer is registered.

ZSTD_DStream memory budget depends on frame's window Size. This information can be passed manually, using ZSTD_estimateDStreamSize, or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); Any frame requesting a window size larger than max specified one will be rejected. Note : if streaming is init with function ZSTD_init?Stream_usingDict(), an internal ?Dict will be created, which additional size is not estimated here. In this case, get total size by adding ZSTD_estimate?DictSize

Here is the call graph for this function:

◆ ZSTD_estimateCStreamSize_usingCParams()

size_t duckdb_zstd::ZSTD_estimateCStreamSize_usingCParams ( ZSTD_compressionParameters cParams)

◆ ZSTD_estimateCStreamSize_usingCCtxParams()

size_t duckdb_zstd::ZSTD_estimateCStreamSize_usingCCtxParams ( const ZSTD_CCtx_params * params)

◆ ZSTD_estimateDStreamSize()

size_t duckdb_zstd::ZSTD_estimateDStreamSize ( size_t maxWindowSize)

◆ ZSTD_estimateDStreamSize_fromFrame()

size_t duckdb_zstd::ZSTD_estimateDStreamSize_fromFrame ( const void * src,
size_t srcSize )

◆ ZSTD_estimateCDictSize()

size_t duckdb_zstd::ZSTD_estimateCDictSize ( size_t dictSize,
int compressionLevel )

ZSTD_estimate?DictSize() : ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). Note : dictionaries created by reference (ZSTD_dlm_byRef) are logically smaller.

Here is the call graph for this function:

◆ ZSTD_estimateCDictSize_advanced()

size_t duckdb_zstd::ZSTD_estimateCDictSize_advanced ( size_t dictSize,
ZSTD_compressionParameters cParams,
ZSTD_dictLoadMethod_e dictLoadMethod )

ZSTD_estimateCDictSize_advanced() : Estimate amount of memory that will be needed to create a dictionary with following arguments

◆ ZSTD_estimateDDictSize()

size_t duckdb_zstd::ZSTD_estimateDDictSize ( size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod )

ZSTD_estimateDDictSize() : Estimate amount of memory that will be needed to create a dictionary for decompression. Note : dictionary created by reference using ZSTD_dlm_byRef are smaller

◆ ZSTD_initStaticCCtx()

ZSTD_CCtx * duckdb_zstd::ZSTD_initStaticCCtx ( void * workspace,
size_t workspaceSize )

ZSTD_initStatic*() : Initialize an object using a pre-allocated fixed-size buffer. workspace: The memory area to emplace the object into. Provided pointer must be 8-bytes aligned. Buffer must outlive object. workspaceSize: Use ZSTD_estimate*Size() to determine how large workspace must be to support target scenario.

Returns
: pointer to object (same address as workspace, just different type), or NULL if error (size too small, incorrect alignment, etc.) Note : zstd will never resize nor malloc() when using a static buffer. If the object requires more memory than available, zstd will just error out (typically ZSTD_error_memory_allocation). Note 2 : there is no corresponding "free" function. Since workspace is allocated externally, it must be freed externally too. Note 3 : cParams : use ZSTD_getCParams() to convert a compression level into its associated cParams. Limitation 1 : currently not compatible with internal dictionary creation, triggered by ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). Limitation 2 : static cctx currently not compatible with multi-threading. Limitation 3 : static dctx is incompatible with legacy support.

◆ ZSTD_initStaticCStream()

ZSTD_CStream * duckdb_zstd::ZSTD_initStaticCStream ( void * workspace,
size_t workspaceSize )

◆ ZSTD_initStaticDCtx()

ZSTD_DCtx * duckdb_zstd::ZSTD_initStaticDCtx ( void * workspace,
size_t workspaceSize )

◆ ZSTD_initStaticDStream()

ZSTD_DStream * duckdb_zstd::ZSTD_initStaticDStream ( void * workspace,
size_t workspaceSize )

same as ZSTD_initStaticDCtx()

◆ ZSTD_initStaticCDict()

const ZSTD_CDict * duckdb_zstd::ZSTD_initStaticCDict ( void * workspace,
size_t workspaceSize,
const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType,
ZSTD_compressionParameters cParams )

ZSTD_initStaticCDict_advanced() : Generate a digested dictionary in provided memory area. workspace: The memory area to emplace the dictionary into. Provided pointer must 8-bytes aligned. It must outlive dictionary usage. workspaceSize: Use ZSTD_estimateCDictSize() to determine how large workspace must be. cParams : use ZSTD_getCParams() to transform a compression level into its relevants cParams.

Returns
: pointer to ZSTD_CDict*, or NULL if error (size too small) Note : there is no corresponding "free" function. Since workspace was allocated externally, it must be freed externally.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_initStaticDDict()

const ZSTD_DDict * duckdb_zstd::ZSTD_initStaticDDict ( void * workspace,
size_t workspaceSize,
const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType )

◆ ZSTD_createCCtx_advanced()

ZSTD_CCtx * duckdb_zstd::ZSTD_createCCtx_advanced ( ZSTD_customMem customMem)

◆ ZSTD_createCStream_advanced()

ZSTD_CStream * duckdb_zstd::ZSTD_createCStream_advanced ( ZSTD_customMem customMem)

◆ ZSTD_createDCtx_advanced()

ZSTD_DCtx * duckdb_zstd::ZSTD_createDCtx_advanced ( ZSTD_customMem customMem)

◆ ZSTD_createDStream_advanced()

ZSTD_DStream * duckdb_zstd::ZSTD_createDStream_advanced ( ZSTD_customMem customMem)

◆ ZSTD_createCDict_advanced()

ZSTD_CDict * duckdb_zstd::ZSTD_createCDict_advanced ( const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType,
ZSTD_compressionParameters cParams,
ZSTD_customMem customMem )

◆ ZSTD_createThreadPool()

POOL_ctx * duckdb_zstd::ZSTD_createThreadPool ( size_t numThreads)

◆ ZSTD_freeThreadPool()

void duckdb_zstd::ZSTD_freeThreadPool ( ZSTD_threadPool * pool)

◆ ZSTD_CCtx_refThreadPool()

size_t duckdb_zstd::ZSTD_CCtx_refThreadPool ( ZSTD_CCtx * cctx,
ZSTD_threadPool * pool )

◆ ZSTD_createCDict_advanced2()

ZSTD_CDict * duckdb_zstd::ZSTD_createCDict_advanced2 ( const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType,
const ZSTD_CCtx_params * cctxParams,
ZSTD_customMem customMem )

◆ ZSTD_createDDict_advanced()

ZSTD_DDict * duckdb_zstd::ZSTD_createDDict_advanced ( const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType,
ZSTD_customMem customMem )

◆ ZSTD_createCDict_byReference()

ZSTD_CDict * duckdb_zstd::ZSTD_createCDict_byReference ( const void * dictBuffer,
size_t dictSize,
int compressionLevel )

Advanced compression functions

ZSTD_createCDict_byReference() : Create a digested dictionary for compression Dictionary content is just referenced, not duplicated. As a consequence, dictBuffer must outlive CDict, and its content must remain unmodified throughout the lifetime of CDict. note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef

◆ ZSTD_getCParams()

ZSTD_compressionParameters duckdb_zstd::ZSTD_getCParams ( int compressionLevel,
unsigned long long srcSizeHint,
size_t dictSize )

ZSTD_getCParams() :

Returns
ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. estimatedSrcSize value is optional, select 0 if not known

ZSTD_getCParams() :

Returns
ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize. Size values are optional, provide 0 if not known or unused
Here is the call graph for this function:

◆ ZSTD_getParams()

ZSTD_parameters duckdb_zstd::ZSTD_getParams ( int compressionLevel,
unsigned long long srcSizeHint,
size_t dictSize )

ZSTD_getParams() : same as ZSTD_getCParams(), but

Returns
a full ZSTD_parameters object instead of sub-component ZSTD_compressionParameters. All fields of ZSTD_frameParameters are set to default : contentSize=1, checksum=0, noDictID=0

ZSTD_getParams() : same idea as ZSTD_getCParams()

Returns
a ZSTD_parameters structure (instead of ZSTD_compressionParameters). Fields of ZSTD_frameParameters are set to default values
Here is the caller graph for this function:

◆ ZSTD_checkCParams()

size_t duckdb_zstd::ZSTD_checkCParams ( ZSTD_compressionParameters cParams)

ZSTD_checkCParams() : Ensure param values remain within authorized range.

Returns
0 on success, or an error code (can be checked with ZSTD_isError())

ZSTD_checkCParams() : control CParam values remain within authorized range.

Returns
: 0, or an error code if one value is beyond authorized range
Here is the caller graph for this function:

◆ ZSTD_adjustCParams()

ZSTD_compressionParameters duckdb_zstd::ZSTD_adjustCParams ( ZSTD_compressionParameters cPar,
unsigned long long srcSize,
size_t dictSize )

ZSTD_adjustCParams() : optimize params for a given srcSize and dictSize. srcSize can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN. dictSize must be 0 when there is no dictionary. cPar can be invalid : all parameters will be clamped within valid range in the

Returns
struct. This function never fails (wide contract)

◆ ZSTD_CCtx_setCParams()

size_t duckdb_zstd::ZSTD_CCtx_setCParams ( ZSTD_CCtx * cctx,
ZSTD_compressionParameters cparams )

ZSTD_CCtx_setCParams() : Set all parameters provided within cparams into the working cctx. Note : if modifying parameters during compression (MT mode only), note that changes to the .windowLog parameter will be ignored.

Returns
0 on success, or an error code (can be checked with ZSTD_isError()). On failure, no parameters are updated.
Here is the caller graph for this function:

◆ ZSTD_CCtx_setFParams()

size_t duckdb_zstd::ZSTD_CCtx_setFParams ( ZSTD_CCtx * cctx,
ZSTD_frameParameters fparams )

ZSTD_CCtx_setFParams() : Set all parameters provided within fparams into the working cctx.

Returns
0 on success, or an error code (can be checked with ZSTD_isError()).
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtx_setParams()

size_t duckdb_zstd::ZSTD_CCtx_setParams ( ZSTD_CCtx * cctx,
ZSTD_parameters params )

ZSTD_CCtx_setParams() : Set all parameters provided within params into the working cctx.

Returns
0 on success, or an error code (can be checked with ZSTD_isError()).
Here is the call graph for this function:

◆ ZSTD_compress_advanced()

size_t duckdb_zstd::ZSTD_compress_advanced ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const void * dict,
size_t dictSize,
ZSTD_parameters params )

ZSTD_compress_advanced() : Note : this function is now DEPRECATED. It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters. This prototype will generate compilation warnings.

◆ ZSTD_compress_usingCDict_advanced()

size_t duckdb_zstd::ZSTD_compress_usingCDict_advanced ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const ZSTD_CDict * cdict,
ZSTD_frameParameters fParams )

ZSTD_compress_usingCDict_advanced() : Note : this function is now DEPRECATED. It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters. This prototype will generate compilation warnings.

ZSTD_compress_usingCDict_advanced(): This function is DEPRECATED.

◆ ZSTD_CCtx_loadDictionary_byReference()

size_t duckdb_zstd::ZSTD_CCtx_loadDictionary_byReference ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize )

ZSTD_CCtx_loadDictionary_byReference() : Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx. It saves some memory, but also requires that dict outlives its usage within cctx

Here is the caller graph for this function:

◆ ZSTD_CCtx_loadDictionary_advanced()

size_t duckdb_zstd::ZSTD_CCtx_loadDictionary_advanced ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType )

ZSTD_CCtx_loadDictionary_advanced() : Same as ZSTD_CCtx_loadDictionary(), but gives finer control over how to load the dictionary (by copy ? by reference ?) and how to interpret it (automatic ? force raw mode ? full mode only ?)

Here is the caller graph for this function:

◆ ZSTD_CCtx_refPrefix_advanced()

size_t duckdb_zstd::ZSTD_CCtx_refPrefix_advanced ( ZSTD_CCtx * cctx,
const void * prefix,
size_t prefixSize,
ZSTD_dictContentType_e dictContentType )

ZSTD_CCtx_refPrefix_advanced() : Same as ZSTD_CCtx_refPrefix(), but gives finer control over how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?)

◆ ZSTD_CCtx_getParameter()

size_t duckdb_zstd::ZSTD_CCtx_getParameter ( const ZSTD_CCtx * cctx,
ZSTD_cParameter param,
int * value )

ZSTD_CCtx_getParameter() : Get the requested compression parameter value, selected by enum ZSTD_cParameter, and store it into int* value.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()).

◆ ZSTD_createCCtxParams()

ZSTD_CCtx_params * duckdb_zstd::ZSTD_createCCtxParams ( void )

ZSTD_CCtx_params : Quick howto :

This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() for static allocation of CCtx for single-threaded compression.

◆ ZSTD_freeCCtxParams()

size_t duckdb_zstd::ZSTD_freeCCtxParams ( ZSTD_CCtx_params * params)

◆ ZSTD_CCtxParams_reset()

size_t duckdb_zstd::ZSTD_CCtxParams_reset ( ZSTD_CCtx_params * params)

ZSTD_CCtxParams_reset() : Reset params to default values.

◆ ZSTD_CCtxParams_init()

size_t duckdb_zstd::ZSTD_CCtxParams_init ( ZSTD_CCtx_params * cctxParams,
int compressionLevel )

ZSTD_CCtxParams_init() : Initializes the compression parameters of cctxParams according to compression level. All other parameters are reset to their default values.

Here is the caller graph for this function:

◆ ZSTD_CCtxParams_init_advanced()

size_t duckdb_zstd::ZSTD_CCtxParams_init_advanced ( ZSTD_CCtx_params * cctxParams,
ZSTD_parameters params )

ZSTD_CCtxParams_init_advanced() : Initializes the compression and frame parameters of cctxParams according to params. All other parameters are reset to their default values.

◆ ZSTD_CCtxParams_setParameter()

size_t duckdb_zstd::ZSTD_CCtxParams_setParameter ( ZSTD_CCtx_params * params,
ZSTD_cParameter param,
int value )

ZSTD_CCtxParams_setParameter() : Requires v1.4.0+ Similar to ZSTD_CCtx_setParameter. Set one compression parameter, selected by enum ZSTD_cParameter. Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams().

Returns
: a code representing success or failure (which can be tested with ZSTD_isError()).

◆ ZSTD_CCtxParams_getParameter()

size_t duckdb_zstd::ZSTD_CCtxParams_getParameter ( const ZSTD_CCtx_params * params,
ZSTD_cParameter param,
int * value )

ZSTD_CCtxParams_getParameter() : Similar to ZSTD_CCtx_getParameter. Get the requested value of one compression parameter, selected by enum ZSTD_cParameter.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()).

◆ ZSTD_CCtx_setParametersUsingCCtxParams()

size_t duckdb_zstd::ZSTD_CCtx_setParametersUsingCCtxParams ( ZSTD_CCtx * cctx,
const ZSTD_CCtx_params * params )

ZSTD_CCtx_setParametersUsingCCtxParams() : Apply a set of ZSTD_CCtx_params to the compression context. This can be done even after compression is started, if nbWorkers==0, this will have no impact until a new compression is started. if nbWorkers>=1, new parameters will be picked up at next job, with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated).

ZSTD_CCtx_setParametersUsingCCtxParams() : just applies params into cctx no action is performed, parameters are merely stored. If ZSTDMT is enabled, parameters are pushed to cctx->mtctx. This is possible even if a compression is ongoing. In which case, new parameters will be applied on the fly, starting with next compression job.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressStream2_simpleArgs()

size_t duckdb_zstd::ZSTD_compressStream2_simpleArgs ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
size_t * dstPos,
const void * src,
size_t srcSize,
size_t * srcPos,
ZSTD_EndDirective endOp )

ZSTD_compressStream2_simpleArgs() : Same as ZSTD_compressStream2(), but using only integral types as arguments. This variant might be helpful for binders from dynamic languages which have troubles handling structures containing memory pointers.

Here is the call graph for this function:

◆ ZSTD_isFrame()

unsigned duckdb_zstd::ZSTD_isFrame ( const void * buffer,
size_t size )

Advanced decompression functions

ZSTD_isFrame() : Tells if the content of buffer starts with a valid Frame Identifier. Note : Frame Identifier is 4 bytes. If size < 4,

Returns
will always be 0. Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. Note 3 : Skippable Frame Identifiers are considered valid.

ZSTD_isFrame() : Tells if the content of buffer starts with a valid Frame Identifier. Note : Frame Identifier is 4 bytes. If size < 4,

Returns
will always be 0. Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. Note 3 : Skippable Frame Identifiers are considered valid.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_createDDict_byReference()

ZSTD_DDict * duckdb_zstd::ZSTD_createDDict_byReference ( const void * dictBuffer,
size_t dictSize )

ZSTD_createDDict_byReference() : Create a digested dictionary, ready to start decompression operation without startup delay. Dictionary content is referenced, and therefore stays in dictBuffer. It is important that dictBuffer outlives DDict, it must remain read accessible throughout the lifetime of DDict

ZSTD_createDDict_byReference() : Create a digested dictionary, to start decompression without startup delay. Dictionary content is simply referenced, it will be accessed during decompression. Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer)

◆ ZSTD_DCtx_loadDictionary_byReference()

size_t duckdb_zstd::ZSTD_DCtx_loadDictionary_byReference ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize )

ZSTD_DCtx_loadDictionary_byReference() : Same as ZSTD_DCtx_loadDictionary(), but references dict content instead of copying it into dctx. This saves memory if dict remains around., However, it's imperative that dict remains accessible (and unmodified) while being used, so it must outlive decompression.

◆ ZSTD_DCtx_loadDictionary_advanced()

size_t duckdb_zstd::ZSTD_DCtx_loadDictionary_advanced ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType )

ZSTD_DCtx_loadDictionary_advanced() : Same as ZSTD_DCtx_loadDictionary(), but gives direct control over how to load the dictionary (by copy ? by reference ?) and how to interpret it (automatic ? force raw mode ? full mode only ?).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_DCtx_refPrefix_advanced()

size_t duckdb_zstd::ZSTD_DCtx_refPrefix_advanced ( ZSTD_DCtx * dctx,
const void * prefix,
size_t prefixSize,
ZSTD_dictContentType_e dictContentType )

ZSTD_DCtx_refPrefix_advanced() : Same as ZSTD_DCtx_refPrefix(), but gives finer control over how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?)

Here is the caller graph for this function:

◆ ZSTD_DCtx_setMaxWindowSize()

size_t duckdb_zstd::ZSTD_DCtx_setMaxWindowSize ( ZSTD_DCtx * dctx,
size_t maxWindowSize )

ZSTD_DCtx_setMaxWindowSize() : Refuses allocating internal buffers for frames requiring a window size larger than provided limit. This protects a decoder context from reserving too much memory for itself (potential attack scenario). This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT)

Returns
: 0, or an error code (which can be tested using ZSTD_isError()).

◆ ZSTD_DCtx_getParameter()

size_t duckdb_zstd::ZSTD_DCtx_getParameter ( ZSTD_DCtx * dctx,
ZSTD_dParameter param,
int * value )

ZSTD_DCtx_getParameter() : Get the requested decompression parameter value, selected by enum ZSTD_dParameter, and store it into int* value.

Returns
: 0, or an error code (which can be tested with ZSTD_isError()).

◆ ZSTD_DCtx_setFormat()

size_t duckdb_zstd::ZSTD_DCtx_setFormat ( ZSTD_DCtx * dctx,
ZSTD_format_e format )

ZSTD_DCtx_setFormat() : This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter(). Instruct the decoder context about what kind of data to decode next. This instruction is mandatory to decode data without a fully-formed header, such ZSTD_f_zstd1_magicless for example.

Returns
: 0, or an error code (which can be tested using ZSTD_isError()).

◆ ZSTD_decompressStream_simpleArgs()

size_t duckdb_zstd::ZSTD_decompressStream_simpleArgs ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
size_t * dstPos,
const void * src,
size_t srcSize,
size_t * srcPos )

ZSTD_decompressStream_simpleArgs() : Same as ZSTD_decompressStream(), but using only integral types as arguments. This can be helpful for binders from dynamic languages which have troubles handling structures containing memory pointers.

◆ ZSTD_initCStream_srcSize()

size_t duckdb_zstd::ZSTD_initCStream_srcSize ( ZSTD_CStream * zcs,
int compressionLevel,
unsigned long long pledgedSrcSize )

Advanced streaming functions Warning : most of these functions are now redundant with the Advanced API. Once Advanced API reaches "stable" status, redundant functions will be deprecated, and then at some point removed.

ZSTD_initCStream_srcSize() : This function is DEPRECATED, and equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);

pledgedSrcSize must be correct. If it is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, "0" also disables frame content size field. It may be enabled in the future. This prototype will generate compilation warnings.

Here is the call graph for this function:

◆ ZSTD_initCStream_usingDict()

size_t duckdb_zstd::ZSTD_initCStream_usingDict ( ZSTD_CStream * zcs,
const void * dict,
size_t dictSize,
int compressionLevel )

ZSTD_initCStream_usingDict() : This function is DEPRECATED, and is equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);

Creates of an internal CDict (incompatible with static CCtx), except if dict == NULL or dictSize < 8, in which case no dict is used. Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy. This prototype will generate compilation warnings.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_initCStream_advanced()

size_t duckdb_zstd::ZSTD_initCStream_advanced ( ZSTD_CStream * zcs,
const void * dict,
size_t dictSize,
ZSTD_parameters params,
unsigned long long pledgedSrcSize )

ZSTD_initCStream_advanced() : This function is DEPRECATED, and is equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_setParams(zcs, params); ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);

dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy. pledgedSrcSize must be correct. If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. This prototype will generate compilation warnings.

◆ ZSTD_initCStream_usingCDict()

size_t duckdb_zstd::ZSTD_initCStream_usingCDict ( ZSTD_CStream * zcs,
const ZSTD_CDict * cdict )

ZSTD_initCStream_usingCDict() : This function is DEPRECATED, and equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_refCDict(zcs, cdict);

note : cdict will just be referenced, and must outlive compression session This prototype will generate compilation warnings.

Here is the call graph for this function:

◆ ZSTD_initCStream_usingCDict_advanced()

size_t duckdb_zstd::ZSTD_initCStream_usingCDict_advanced ( ZSTD_CStream * zcs,
const ZSTD_CDict * cdict,
ZSTD_frameParameters fParams,
unsigned long long pledgedSrcSize )

ZSTD_initCStream_usingCDict_advanced() : This function is DEPRECATED, and is equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_setFParams(zcs, fParams); ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); ZSTD_CCtx_refCDict(zcs, cdict);

same as ZSTD_initCStream_usingCDict(), with control over frame parameters. pledgedSrcSize must be correct. If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. This prototype will generate compilation warnings.

Here is the call graph for this function:

◆ ZSTD_resetCStream()

size_t duckdb_zstd::ZSTD_resetCStream ( ZSTD_CStream * zcs,
unsigned long long pledgedSrcSize )

ZSTD_resetCStream() : This function is DEPRECATED, and is equivalent to: ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); Note: ZSTD_resetCStream() interprets pledgedSrcSize == 0 as ZSTD_CONTENTSIZE_UNKNOWN, but ZSTD_CCtx_setPledgedSrcSize() does not do the same, so ZSTD_CONTENTSIZE_UNKNOWN must be explicitly specified.

start a new frame, using same parameters from previous frame. This is typically useful to skip dictionary loading stage, since it will reuse it in-place. Note that zcs must be init at least once before using ZSTD_resetCStream(). If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN. If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs, but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead.

Returns
: 0, or an error code (which can be tested using ZSTD_isError()) This prototype will generate compilation warnings.

◆ ZSTD_getFrameProgression()

ZSTD_frameProgression duckdb_zstd::ZSTD_getFrameProgression ( const ZSTD_CCtx * cctx)

◆ ZSTD_toFlushNow()

size_t duckdb_zstd::ZSTD_toFlushNow ( ZSTD_CCtx * cctx)

ZSTD_toFlushNow() : Tell how many bytes are ready to be flushed immediately. Useful for multithreading scenarios (nbWorkers >= 1). Probe the oldest active job, defined as oldest job not yet entirely flushed, and check its output buffer.

Returns
: amount of data stored in oldest job and ready to be flushed immediately. if
== 0, it means either :
  • there is no active job (could be checked with ZSTD_frameProgression()), or
  • oldest job is still actively compressing data, but everything it has produced has also been flushed so far, therefore flush speed is limited by production speed of oldest job irrespective of the speed of concurrent (and newer) jobs.

ZSTD_toFlushNow() Only useful for multithreading scenarios currently (nbWorkers >= 1).

◆ ZSTD_initDStream_usingDict()

size_t duckdb_zstd::ZSTD_initDStream_usingDict ( ZSTD_DStream * zds,
const void * dict,
size_t dictSize )

This function is deprecated, and is equivalent to:

ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
ZSTD_DCtx_loadDictionary(zds, dict, dictSize);

note: no dictionary will be used if dict == NULL or dictSize < 8

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_initDStream_usingDDict()

size_t duckdb_zstd::ZSTD_initDStream_usingDDict ( ZSTD_DStream * zds,
const ZSTD_DDict * ddict )

This function is deprecated, and is equivalent to:

ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
ZSTD_DCtx_refDDict(zds, ddict);

note : ddict is referenced, it must outlive decompression session

Here is the call graph for this function:

◆ ZSTD_resetDStream()

size_t duckdb_zstd::ZSTD_resetDStream ( ZSTD_DStream * zds)

This function is deprecated, and is equivalent to:

ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);

reuse decompression parameters from previous init; saves dictionary loading

Here is the call graph for this function:

◆ ZSTD_registerSequenceProducer()

void duckdb_zstd::ZSTD_registerSequenceProducer ( ZSTD_CCtx * cctx,
void * sequenceProducerState,
ZSTD_sequenceProducer_F sequenceProducer )

ZSTD_registerSequenceProducer() : Instruct zstd to use a block-level external sequence producer function.

The sequenceProducerState must be initialized by the caller, and the caller is responsible for managing its lifetime. This parameter is sticky across compressions. It will remain set until the user explicitly resets compression parameters.

Sequence producer registration is considered to be an "advanced parameter", part of the "advanced API". This means it will only have an effect on compression APIs which respect advanced parameters, such as compress2() and compressStream2(). Older compression APIs such as compressCCtx(), which predate the introduction of "advanced parameters", will ignore any external sequence producer setting.

The sequence producer can be "cleared" by registering a NULL function pointer. This removes all limitations described above in the "LIMITATIONS" section of the API docs.

The user is strongly encouraged to read the full API documentation (above) before calling this function.

Here is the call graph for this function:

◆ ZSTD_CCtxParams_registerSequenceProducer()

void duckdb_zstd::ZSTD_CCtxParams_registerSequenceProducer ( ZSTD_CCtx_params * params,
void * sequenceProducerState,
ZSTD_sequenceProducer_F sequenceProducer )

ZSTD_CCtxParams_registerSequenceProducer() : Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params. This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(), which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx().

If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx() is required, then this function is for you. Otherwise, you probably don't need it.

See tests/zstreamtest.c for example usage.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressBegin()

size_t duckdb_zstd::ZSTD_compressBegin ( ZSTD_CCtx * cctx,
int compressionLevel )

Buffer-less and synchronous inner streaming functions (DEPRECATED)

This API is deprecated, and will be removed in a future version. It allows streaming (de)compression with user allocated buffers. However, it is hard to use, and not as well tested as the rest of our API.

Please use the normal streaming API instead: ZSTD_compressStream2, and ZSTD_decompressStream. If there is functionality that you need, but it doesn't provide, please open an issue on our GitHub. Buffer-less streaming compression (synchronous mode)

A ZSTD_CCtx object is required to track streaming operations. Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. ZSTD_CCtx object can be reused multiple times within successive compression operations.

Start by initializing a context. Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression.

Then, consume your input using ZSTD_compressContinue(). There are some important considerations to keep in mind when using this advanced function :

  • ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only.
  • Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks.
  • Caller must ensure there is enough space in dst to store compressed data under worst case scenario. Worst case evaluation is provided by ZSTD_compressBound(). ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
  • ZSTD_compressContinue() presumes prior input is still accessible and unmodified (up to maximum distance size, see WindowLog). It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
  • ZSTD_compressContinue() detects that prior input has been overwritten when src buffer overlaps. In which case, it will "discard" the relevant memory section from its history.

Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.

ZSTD_CCtx object can be reused (ZSTD_compressBegin()) to compress again.

◆ ZSTD_compressBegin_usingDict()

size_t duckdb_zstd::ZSTD_compressBegin_usingDict ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
int compressionLevel )

◆ ZSTD_compressBegin_usingCDict()

size_t duckdb_zstd::ZSTD_compressBegin_usingCDict ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict )

note: fails if cdict==NULL

◆ ZSTD_copyCCtx()

size_t duckdb_zstd::ZSTD_copyCCtx ( ZSTD_CCtx * dstCCtx,
const ZSTD_CCtx * srcCCtx,
unsigned long long pledgedSrcSize )

note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN

ZSTD_copyCCtx() : Duplicate an existing context srcCCtx into another one dstCCtx. Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). pledgedSrcSize==0 means "unknown".

Returns
: 0, or an error code

◆ ZSTD_compressContinue()

size_t duckdb_zstd::ZSTD_compressContinue ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_compressEnd()

size_t duckdb_zstd::ZSTD_compressEnd ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_compressBegin_advanced()

size_t duckdb_zstd::ZSTD_compressBegin_advanced ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
ZSTD_parameters params,
unsigned long long pledgedSrcSize )

pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN

ZSTD_compressBegin_advanced() :

Returns
: 0, or an error code

◆ ZSTD_compressBegin_usingCDict_advanced()

size_t duckdb_zstd::ZSTD_compressBegin_usingCDict_advanced ( ZSTD_CCtx *const cctx,
const ZSTD_CDict *const cdict,
ZSTD_frameParameters const fParams,
unsigned long long const pledgedSrcSize )

◆ ZSTD_decodingBufferSize_min()

size_t duckdb_zstd::ZSTD_decodingBufferSize_min ( unsigned long long windowSize,
unsigned long long frameContentSize )

Buffer-less streaming decompression (synchronous mode)

A ZSTD_DCtx object is required to track streaming operations. Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. A ZSTD_DCtx object can be reused multiple times.

First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. Data fragment must be large enough to ensure successful decoding. ZSTD_frameHeaderSize_max bytes is guaranteed to always be large enough. result : 0 : successful decoding, the ZSTD_frameHeader structure is correctly filled. >0 : srcSize is too small, please provide at least result bytes on next attempt. errorCode, which can be tested using ZSTD_isError().

It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, such as the dictionary ID, content size, or maximum back-reference distance (windowSize). Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. As a consequence, check that values remain within valid application range. For example, do not allocate memory blindly, check that windowSize is within expectation. Each application can set its own limits, depending on local restrictions. For extended interoperability, it is recommended to support windowSize of at least 8 MB.

ZSTD_decompressContinue() needs previous data blocks during decompression, up to windowSize bytes. ZSTD_decompressContinue() is very sensitive to contiguity, if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, or that previous contiguous segment is large enough to properly handle maximum back-reference distance. There are multiple ways to guarantee this condition.

The most memory efficient way is to use a round buffer of sufficient size. Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), which can return an error code if required value is too large for current system (in 32-bits mode). In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, up to the moment there is not enough room left in the buffer to guarantee decoding another full block, which maximum size is provided in ZSTD_frameHeader structure, field blockSizeMax. At which point, decoding can resume from the beginning of the buffer. Note that already decoded data stored in the buffer should be flushed before being overwritten.

There are alternatives possible, for example using two or more buffers of size windowSize each, though they consume more memory.

Finally, if you control the compression process, you can also ignore all buffer size rules, as long as the encoder and decoder progress in "lock-step", aka use exactly the same buffer sizes, break contiguity at the same place, etc.

Once buffers are setup, start decompression, with ZSTD_decompressBegin(). If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().

Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). ZSTD_decompressContinue() requires this exact amount of bytes, or it will fail.

result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. It can also be an error code, which can be tested with ZSTD_isError().

A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. Context can then be reset to start a new decompression.

Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). This information is not required to properly decode a frame.

== Special case : skippable frames ==

Skippable frames allow integration of user-defined data into a flow of concatenated frames. Skippable frames will be ignored (skipped) by decompressor. The format of skippable frames is as follows : a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits c) Frame Content - any content (User Data) of length equal to Frame Size For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN

◆ ZSTD_decompressBegin()

size_t duckdb_zstd::ZSTD_decompressBegin ( ZSTD_DCtx * dctx)

◆ ZSTD_decompressBegin_usingDict()

size_t duckdb_zstd::ZSTD_decompressBegin_usingDict ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize )

◆ ZSTD_decompressBegin_usingDDict()

size_t duckdb_zstd::ZSTD_decompressBegin_usingDDict ( ZSTD_DCtx * dctx,
const ZSTD_DDict * ddict )

◆ ZSTD_nextSrcSizeToDecompress()

size_t duckdb_zstd::ZSTD_nextSrcSizeToDecompress ( ZSTD_DCtx * dctx)

◆ ZSTD_copyDCtx()

void duckdb_zstd::ZSTD_copyDCtx ( ZSTD_DCtx * dctx,
const ZSTD_DCtx * preparedDCtx )

◆ ZSTD_nextInputType()

ZSTD_nextInputType_e duckdb_zstd::ZSTD_nextInputType ( ZSTD_DCtx * dctx)

◆ ZSTD_getBlockSize()

size_t duckdb_zstd::ZSTD_getBlockSize ( const ZSTD_CCtx * cctx)

Block level API (DEPRECATED)

This API is deprecated in favor of the regular compression API. You can get the frame header down to 2 bytes by setting:

  • ZSTD_c_format = ZSTD_f_zstd1_magicless
  • ZSTD_c_contentSizeFlag = 0
  • ZSTD_c_checksumFlag = 0
  • ZSTD_c_dictIDFlag = 0

This API is not as well tested as our normal API, so we recommend not using it. We will be removing it in a future version. If the normal API doesn't provide the functionality you need, please open a GitHub issue.

Block functions produce and decode raw zstd blocks, without frame metadata. Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes). But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes.

A few rules to respect :

  • Compressing and decompressing require a context structure
    • Use ZSTD_createCCtx() and ZSTD_createDCtx()
  • It is necessary to init context before starting
    • compression : any ZSTD_compressBegin*() variant, including with dictionary
    • decompression : any ZSTD_decompressBegin*() variant, including with dictionary
  • Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB
    • If input is larger than a block size, it's necessary to split input data into multiple blocks
    • For inputs larger than a single block, consider using regular ZSTD_compress() instead. Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block.
  • When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) ! ===> In which case, nothing is produced into dst !
    • User must test for such outcome and deal directly with uncompressed data
    • A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0. Doing so would mess up with statistics history, leading to potential data corruption.
    • ZSTD_decompressBlock() doesn't accept uncompressed data as input !!
    • In case of multiple successive blocks, should some of them be uncompressed, decoder must be informed of their existence in order to follow proper history. Use ZSTD_insertBlock() for such a case.
Here is the call graph for this function:

◆ ZSTD_compressBlock()

size_t duckdb_zstd::ZSTD_compressBlock ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_decompressBlock()

size_t duckdb_zstd::ZSTD_decompressBlock ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_insertBlock()

size_t duckdb_zstd::ZSTD_insertBlock ( ZSTD_DCtx * dctx,
const void * blockStart,
size_t blockSize )

insert uncompressed block into dctx history. Useful for multi-blocks decompression.

ZSTD_insertBlock() : insert src block into dctx history. Useful to track uncompressed blocks.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_wrappedPtrDiff()

MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR ptrdiff_t duckdb_zstd::ZSTD_wrappedPtrDiff ( unsigned char const * lhs,
unsigned char const * rhs )

Helper function to perform a wrapped pointer difference without trigging UBSAN.

Returns
lhs - rhs with wrapping
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_wrappedPtrAdd()

MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR unsigned char const * duckdb_zstd::ZSTD_wrappedPtrAdd ( unsigned char const * ptr,
ptrdiff_t add )

Helper function to perform a wrapped pointer add without triggering UBSAN.

Returns
ptr + add with wrapping
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_wrappedPtrSub()

MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR unsigned char const * duckdb_zstd::ZSTD_wrappedPtrSub ( unsigned char const * ptr,
ptrdiff_t sub )

Helper function to perform a wrapped pointer subtraction without triggering UBSAN.

Returns
ptr - sub with wrapping
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_maybeNullPtrAdd()

MEM_STATIC unsigned char * duckdb_zstd::ZSTD_maybeNullPtrAdd ( unsigned char * ptr,
ptrdiff_t add )

Helper function to add to a pointer that works around C's undefined behavior of adding 0 to NULL.

Returns
ptr + add except it defines NULL + 0 == NULL.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MEM_32bits()

MEM_STATIC unsigned duckdb_zstd::MEM_32bits ( void )

◆ MEM_64bits()

MEM_STATIC unsigned duckdb_zstd::MEM_64bits ( void )

◆ MEM_isLittleEndian()

MEM_STATIC unsigned duckdb_zstd::MEM_isLittleEndian ( void )

◆ MEM_read16()

MEM_STATIC U16 duckdb_zstd::MEM_read16 ( const void * memPtr)

◆ MEM_read32()

MEM_STATIC U32 duckdb_zstd::MEM_read32 ( const void * memPtr)

◆ MEM_read64()

MEM_STATIC U64 duckdb_zstd::MEM_read64 ( const void * memPtr)

◆ MEM_readST()

MEM_STATIC size_t duckdb_zstd::MEM_readST ( const void * memPtr)

◆ MEM_write16()

MEM_STATIC void duckdb_zstd::MEM_write16 ( void * memPtr,
U16 value )

◆ MEM_write32()

MEM_STATIC void duckdb_zstd::MEM_write32 ( void * memPtr,
U32 value )

◆ MEM_write64()

MEM_STATIC void duckdb_zstd::MEM_write64 ( void * memPtr,
U64 value )

◆ MEM_readLE16()

MEM_STATIC U16 duckdb_zstd::MEM_readLE16 ( const void * memPtr)

◆ MEM_readLE24()

MEM_STATIC U32 duckdb_zstd::MEM_readLE24 ( const void * memPtr)

◆ MEM_readLE32()

MEM_STATIC U32 duckdb_zstd::MEM_readLE32 ( const void * memPtr)

◆ MEM_readLE64()

MEM_STATIC U64 duckdb_zstd::MEM_readLE64 ( const void * memPtr)

◆ MEM_readLEST()

MEM_STATIC size_t duckdb_zstd::MEM_readLEST ( const void * memPtr)

◆ MEM_writeLE16()

MEM_STATIC void duckdb_zstd::MEM_writeLE16 ( void * memPtr,
U16 val )

◆ MEM_writeLE24()

MEM_STATIC void duckdb_zstd::MEM_writeLE24 ( void * memPtr,
U32 val )

◆ MEM_writeLE32()

MEM_STATIC void duckdb_zstd::MEM_writeLE32 ( void * memPtr,
U32 val32 )

◆ MEM_writeLE64()

MEM_STATIC void duckdb_zstd::MEM_writeLE64 ( void * memPtr,
U64 val64 )

◆ MEM_writeLEST()

MEM_STATIC void duckdb_zstd::MEM_writeLEST ( void * memPtr,
size_t val )

◆ MEM_readBE32()

MEM_STATIC U32 duckdb_zstd::MEM_readBE32 ( const void * memPtr)

◆ MEM_readBE64()

MEM_STATIC U64 duckdb_zstd::MEM_readBE64 ( const void * memPtr)

◆ MEM_readBEST()

MEM_STATIC size_t duckdb_zstd::MEM_readBEST ( const void * memPtr)

◆ MEM_writeBE32()

MEM_STATIC void duckdb_zstd::MEM_writeBE32 ( void * memPtr,
U32 val32 )

◆ MEM_writeBE64()

MEM_STATIC void duckdb_zstd::MEM_writeBE64 ( void * memPtr,
U64 val64 )

◆ MEM_writeBEST()

MEM_STATIC void duckdb_zstd::MEM_writeBEST ( void * memPtr,
size_t val )

◆ MEM_swap32()

MEM_STATIC U32 duckdb_zstd::MEM_swap32 ( U32 in)

◆ MEM_swap64()

MEM_STATIC U64 duckdb_zstd::MEM_swap64 ( U64 in)

◆ MEM_swapST()

MEM_STATIC size_t duckdb_zstd::MEM_swapST ( size_t in)

◆ MEM_swap32_fallback()

MEM_STATIC U32 duckdb_zstd::MEM_swap32_fallback ( U32 in)

◆ MEM_swap64_fallback()

MEM_STATIC U64 duckdb_zstd::MEM_swap64_fallback ( U64 in)

◆ MEM_check()

MEM_STATIC void duckdb_zstd::MEM_check ( void )

◆ ZSTD_getErrorCode()

ZSTD_ErrorCode duckdb_zstd::ZSTD_getErrorCode ( size_t code)

ZSTD_getErrorCode() : convert a size_t function result into a ZSTD_ErrorCode enum type, which can be used to compare with enum list published above

ZSTD_getError() : convert a size_t function result into a proper ZSTD_errorCode enum

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getErrorString()

const char * duckdb_zstd::ZSTD_getErrorString ( ZSTD_ErrorCode code)

Same as ZSTD_getErrorName, but using a ZSTD_ErrorCode enum argument

ZSTD_getErrorString() : provides error code string from enum

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ERR_isError()

ERR_STATIC unsigned duckdb_zstd::ERR_isError ( size_t code)

◆ ERR_getErrorCode()

ERR_STATIC ERR_enum duckdb_zstd::ERR_getErrorCode ( size_t code)

◆ ERR_getErrorString()

const char * duckdb_zstd::ERR_getErrorString ( ERR_enum code)

◆ ERR_getErrorName()

ERR_STATIC const char * duckdb_zstd::ERR_getErrorName ( size_t code)

◆ _force_has_format_string()

INLINE_KEYWORD UNUSED_ATTR void duckdb_zstd::_force_has_format_string ( const char * format,
... )
static

Ignore: this is an internal helper.

This is a helper function to help force C99-correctness during compilation. Under strict compilation modes, variadic macro arguments can't be empty. However, variadic function arguments can be. Using a function therefore lets us statically check that at least one (string) argument was passed, independent of the compilation flags.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_versionNumber()

unsigned duckdb_zstd::FSE_versionNumber ( void )

library version number; to be used when checking dll version

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_compressBound()

size_t duckdb_zstd::FSE_compressBound ( size_t size)

◆ FSE_isError()

unsigned duckdb_zstd::FSE_isError ( size_t code)

◆ FSE_getErrorName()

const char * duckdb_zstd::FSE_getErrorName ( size_t code)

◆ FSE_optimalTableLog()

unsigned duckdb_zstd::FSE_optimalTableLog ( unsigned maxTableLog,
size_t srcSize,
unsigned maxSymbolValue )

FSE_compress() does the following:

  1. count symbol occurrence from source[] into table count[] (see hist.h)
  2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
  3. save normalized counters to memory buffer using writeNCount()
  4. build encoding table 'CTable' from normalized counters
  5. encode the data stream using encoding table 'CTable'

FSE_decompress() does the following:

  1. read normalized counters with readNCount()
  2. build decoding table 'DTable' from normalized counters
  3. decode the data stream using decoding table 'DTable'

The following API allows targeting specific sub-functions for advanced tasks. For example, it's possible to compress several blocks using the same 'CTable', or to save and provide normalized distribution using external method.

FSE_optimalTableLog(): dynamically downsize 'tableLog' when conditions are met. It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.

Returns
: recommended tableLog (necessarily <= 'maxTableLog')
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_normalizeCount()

size_t duckdb_zstd::FSE_normalizeCount ( short * normalizedCounter,
unsigned tableLog,
const unsigned * count,
size_t srcSize,
unsigned maxSymbolValue,
unsigned useLowProbCount )

FSE_normalizeCount(): normalize counts so that sum(count[]) == Power_of_2 (2^tableLog) 'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1). useLowProbCount is a boolean parameter which trades off compressed size for faster header decoding. When it is set to 1, the compressed data will be slightly smaller. And when it is set to 0, FSE_readNCount() and FSE_buildDTable() will be faster. If you are compressing a small amount of data (< 2 KB) then useLowProbCount=0 is a good default, since header deserialization makes a big speed difference. Otherwise, useLowProbCount=1 is a good default, since the speed difference is small.

Returns
: tableLog, or an errorCode, which can be tested using FSE_isError()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_NCountWriteBound()

size_t duckdb_zstd::FSE_NCountWriteBound ( unsigned maxSymbolValue,
unsigned tableLog )

FSE_NCountWriteBound(): Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'. Typically useful for allocation purpose.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_writeNCount()

size_t duckdb_zstd::FSE_writeNCount ( void * buffer,
size_t bufferSize,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog )

FSE_writeNCount(): Compactly save 'normalizedCounter' into 'buffer'.

Returns
: size of the compressed table, or an errorCode, which can be tested using FSE_isError().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_buildCTable()

FSE_PUBLIC_API size_t duckdb_zstd::FSE_buildCTable ( FSE_CTable * ct,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog )

FSE_buildCTable(): Builds ct, which must be already allocated, using FSE_createCTable().

Returns
: 0, or an errorCode, which can be tested using FSE_isError()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_compress_usingCTable()

size_t duckdb_zstd::FSE_compress_usingCTable ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const FSE_CTable * ct )

FSE_compress_usingCTable(): Compress src using ct into dst which must be already allocated.

Returns
: size of compressed data (<= dstCapacity), or 0 if compressed data could not fit into dst, or an errorCode, which can be tested using FSE_isError()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_readNCount()

size_t duckdb_zstd::FSE_readNCount ( short * normalizedCounter,
unsigned * maxSymbolValuePtr,
unsigned * tableLogPtr,
const void * rBuffer,
size_t rBuffSize )

Tutorial :

The first step is to count all symbols. FSE_count() does this job very fast. Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells. 'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0] maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value) FSE_count() will return the number of occurrence of the most frequent symbol. This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility. If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).

The next step is to normalize the frequencies. FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'. It also guarantees a minimum of 1 to any Symbol with frequency >= 1. You can use 'tableLog'==0 to mean "use default tableLog value". If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(), which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").

The result of FSE_normalizeCount() will be saved into a table, called 'normalizedCounter', which is a table of signed short. 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells. The return value is tableLog if everything proceeded as expected. It is 0 if there is a single symbol within distribution. If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).

'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount(). 'buffer' must be already allocated. For guaranteed success, buffer size must be at least FSE_headerBound(). The result of the function is the number of bytes written into 'buffer'. If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).

'normalizedCounter' can then be used to create the compression table 'CTable'. The space required by 'CTable' must be already allocated, using FSE_createCTable(). You can then use FSE_buildCTable() to fill 'CTable'. If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).

'CTable' can then be used to compress 'src', with FSE_compress_usingCTable(). Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize' The function returns the size of compressed data (without header), necessarily <= dstCapacity. If it returns '0', compressed data could not fit into 'dst'. If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).

FSE_readNCount(): Read compactly saved 'normalizedCounter' from 'rBuffer'.

Returns
: size read from 'rBuffer', or an errorCode, which can be tested using FSE_isError(). maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_readNCount_bmi2()

size_t duckdb_zstd::FSE_readNCount_bmi2 ( short * normalizedCounter,
unsigned * maxSymbolValuePtr,
unsigned * tableLogPtr,
const void * rBuffer,
size_t rBuffSize,
int bmi2 )

FSE_readNCount_bmi2(): Same as FSE_readNCount() but pass bmi2=1 when your CPU supports BMI2 and 0 otherwise.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_countTrailingZeros32_fallback()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countTrailingZeros32_fallback ( U32 val)

◆ ZSTD_countTrailingZeros32()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countTrailingZeros32 ( U32 val)

◆ ZSTD_countLeadingZeros32_fallback()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countLeadingZeros32_fallback ( U32 val)

◆ ZSTD_countLeadingZeros32()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countLeadingZeros32 ( U32 val)

◆ ZSTD_countTrailingZeros64()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countTrailingZeros64 ( U64 val)

◆ ZSTD_countLeadingZeros64()

MEM_STATIC unsigned duckdb_zstd::ZSTD_countLeadingZeros64 ( U64 val)

◆ ZSTD_NbCommonBytes()

MEM_STATIC unsigned duckdb_zstd::ZSTD_NbCommonBytes ( size_t val)

◆ ZSTD_highbit32()

MEM_STATIC unsigned duckdb_zstd::ZSTD_highbit32 ( U32 val)

◆ ZSTD_rotateRight_U64()

MEM_STATIC U64 duckdb_zstd::ZSTD_rotateRight_U64 ( U64 const value,
U32 count )

◆ ZSTD_rotateRight_U32()

MEM_STATIC U32 duckdb_zstd::ZSTD_rotateRight_U32 ( U32 const value,
U32 count )

◆ ZSTD_rotateRight_U16()

MEM_STATIC U16 duckdb_zstd::ZSTD_rotateRight_U16 ( U16 const value,
U32 count )

◆ BIT_initCStream()

MEM_STATIC size_t duckdb_zstd::BIT_initCStream ( BIT_CStream_t * bitC,
void * startPtr,
size_t dstCapacity )

BIT_initCStream() : dstCapacity must be > sizeof(size_t)

Returns
: 0 if success, otherwise an error code (can be tested using ERR_isError())
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_addBits()

MEM_STATIC void duckdb_zstd::BIT_addBits ( BIT_CStream_t * bitC,
size_t value,
unsigned nbBits )

BIT_addBits() : can add up to 31 bits into bitC. Note : does not check for register overflow !

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_flushBits()

MEM_STATIC void duckdb_zstd::BIT_flushBits ( BIT_CStream_t * bitC)

BIT_flushBits() : assumption : bitContainer has not overflowed safe version; check for buffer overflow, and prevents it. note : does not signal buffer overflow. overflow will be revealed later on using BIT_closeCStream()

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_closeCStream()

MEM_STATIC size_t duckdb_zstd::BIT_closeCStream ( BIT_CStream_t * bitC)

BIT_closeCStream() :

Returns
: size of CStream, in bytes, or 0 if it could not fit into dstBuffer
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_initDStream()

MEM_STATIC size_t duckdb_zstd::BIT_initDStream ( BIT_DStream_t * bitD,
const void * srcBuffer,
size_t srcSize )

BIT_initDStream() : Initialize a BIT_DStream_t. bitD : a pointer to an already allocated BIT_DStream_t structure. srcSize must be the exact size of the bitStream, in bytes.

Returns
: size of stream (== srcSize), or an errorCode if a problem is detected
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_readBits()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::BIT_readBits ( BIT_DStream_t * bitD,
unsigned nbBits )

BIT_readBits() : Read (consume) next n bits from local register and update. Pay attention to not read more than nbBits contained into local register.

Returns
: extracted value.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_reloadDStream()

FORCE_INLINE_TEMPLATE BIT_DStream_status duckdb_zstd::BIT_reloadDStream ( BIT_DStream_t * bitD)

BIT_reloadDStream() : Refill bitD from buffer previously set in BIT_initDStream() . This function is safe, it guarantees it will not never beyond src buffer.

Returns
: status of BIT_DStream_t internal register. when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_endOfDStream()

MEM_STATIC unsigned duckdb_zstd::BIT_endOfDStream ( const BIT_DStream_t * DStream)

BIT_endOfDStream() :

Returns
: 1 if DStream has exactly reached its end (all bits consumed).
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_addBitsFast()

MEM_STATIC void duckdb_zstd::BIT_addBitsFast ( BIT_CStream_t * bitC,
size_t value,
unsigned nbBits )

BIT_addBitsFast() : works only if value is clean, meaning all high bits above nbBits are 0

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_flushBitsFast()

MEM_STATIC void duckdb_zstd::BIT_flushBitsFast ( BIT_CStream_t * bitC)

BIT_flushBitsFast() : assumption : bitContainer has not overflowed unsafe version; does not check buffer overflow

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_readBitsFast()

MEM_STATIC size_t duckdb_zstd::BIT_readBitsFast ( BIT_DStream_t * bitD,
unsigned nbBits )

BIT_readBitsFast() : unsafe version; only works if nbBits >= 1

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_getLowerBits()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::BIT_getLowerBits ( size_t bitContainer,
U32 const nbBits )

◆ BIT_getUpperBits()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::BIT_getUpperBits ( BitContainerType bitContainer,
U32 const start )

◆ BIT_getMiddleBits()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::BIT_getMiddleBits ( BitContainerType bitContainer,
U32 const start,
U32 const nbBits )

◆ BIT_lookBits()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::BIT_lookBits ( const BIT_DStream_t * bitD,
U32 nbBits )

BIT_lookBits() : Provides next n bits from local register. local register is not modified. On 32-bits, maxNbBits==24. On 64-bits, maxNbBits==56.

Returns
: value extracted
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_lookBitsFast()

MEM_STATIC size_t duckdb_zstd::BIT_lookBitsFast ( const BIT_DStream_t * bitD,
U32 nbBits )

BIT_lookBitsFast() : unsafe version; only works if nbBits >= 1

Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_skipBits()

FORCE_INLINE_TEMPLATE void duckdb_zstd::BIT_skipBits ( BIT_DStream_t * bitD,
U32 nbBits )

◆ BIT_reloadDStream_internal()

MEM_STATIC BIT_DStream_status duckdb_zstd::BIT_reloadDStream_internal ( BIT_DStream_t * bitD)

BIT_reloadDStream_internal() : Simple variant of BIT_reloadDStream(), with two conditions:

  1. bitstream is valid : bitsConsumed <= sizeof(bitD->bitContainer)*8
  2. look window is valid after shifted down : bitD->ptr >= bitD->start
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BIT_reloadDStreamFast()

MEM_STATIC BIT_DStream_status duckdb_zstd::BIT_reloadDStreamFast ( BIT_DStream_t * bitD)

BIT_reloadDStreamFast() : Similar to BIT_reloadDStream(), but with two differences:

  1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold!
  2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this point you must use BIT_reloadDStream() to reload.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_optimalTableLog_internal()

unsigned duckdb_zstd::FSE_optimalTableLog_internal ( unsigned maxTableLog,
size_t srcSize,
unsigned maxSymbolValue,
unsigned minus )

same as FSE_optimalTableLog(), which used minus==2

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_buildCTable_rle()

size_t duckdb_zstd::FSE_buildCTable_rle ( FSE_CTable * ct,
unsigned char symbolValue )

build a fake FSE_CTable, designed to compress always the same symbolValue

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_buildCTable_wksp()

size_t duckdb_zstd::FSE_buildCTable_wksp ( FSE_CTable * ct,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
void * workSpace,
size_t wkspSize )

◆ FSE_buildDTable_wksp()

size_t duckdb_zstd::FSE_buildDTable_wksp ( FSE_DTable * dt,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
void * workSpace,
size_t wkspSize )

Same as FSE_buildDTable(), using an externally allocated workspace produced with FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxSymbolValue)

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_decompress_wksp_bmi2()

size_t duckdb_zstd::FSE_decompress_wksp_bmi2 ( void * dst,
size_t dstCapacity,
const void * cSrc,
size_t cSrcSize,
unsigned maxLog,
void * workSpace,
size_t wkspSize,
int bmi2 )

same as FSE_decompress(), using an externally allocated workSpace produced with FSE_DECOMPRESS_WKSP_SIZE_U32(maxLog, maxSymbolValue). Set bmi2 to 1 if your CPU supports BMI2 or 0 if it doesn't

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_initCState()

MEM_STATIC void duckdb_zstd::FSE_initCState ( FSE_CState_t * CStatePtr,
const FSE_CTable * ct )
static

◆ FSE_encodeSymbol()

MEM_STATIC void duckdb_zstd::FSE_encodeSymbol ( BIT_CStream_t * bitC,
FSE_CState_t * CStatePtr,
unsigned symbol )
static

◆ FSE_flushCState()

MEM_STATIC void duckdb_zstd::FSE_flushCState ( BIT_CStream_t * bitC,
const FSE_CState_t * CStatePtr )
static

These functions are inner components of FSE_compress_usingCTable(). They allow the creation of custom streams, mixing multiple tables and bit sources.

A key property to keep in mind is that encoding and decoding are done in reverse direction. So the first symbol you will encode is the last you will decode, like a LIFO stack.

You will need a few variables to track your CStream. They are :

FSE_CTable ct; // Provided by FSE_buildCTable() BIT_CStream_t bitStream; // bitStream tracking structure FSE_CState_t state; // State tracking structure (can have several)

The first thing to do is to init bitStream and state. size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize); FSE_initCState(&state, ct);

Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError(); You can then encode your input data, byte after byte. FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time. Remember decoding will be done in reverse direction. FSE_encodeByte(&bitStream, &state, symbol);

At any time, you can also add any bit sequence. Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders BIT_addBits(&bitStream, bitField, nbBits);

The above methods don't commit data to memory, they just store it into local register, for speed. Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t). Writing data to memory is a manual operation, performed by the flushBits function. BIT_flushBits(&bitStream);

Your last FSE encoding operation shall be to flush your last state value(s). FSE_flushState(&bitStream, &state);

Finally, you must close the bitStream. The function returns the size of CStream in bytes. If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible) If there is an error, it returns an errorCode (which can be tested using FSE_isError()). size_t size = BIT_closeCStream(&bitStream);

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_initDState()

MEM_STATIC void duckdb_zstd::FSE_initDState ( FSE_DState_t * DStatePtr,
BIT_DStream_t * bitD,
const FSE_DTable * dt )
static

◆ FSE_decodeSymbol()

MEM_STATIC BYTE duckdb_zstd::FSE_decodeSymbol ( FSE_DState_t * DStatePtr,
BIT_DStream_t * bitD )
static

◆ FSE_endOfDState()

MEM_STATIC unsigned duckdb_zstd::FSE_endOfDState ( const FSE_DState_t * DStatePtr)
static

Let's now decompose FSE_decompress_usingDTable() into its unitary components. You will decode FSE-encoded symbols from the bitStream, and also any other bitFields you put in, in reverse order.

You will need a few variables to track your bitStream. They are :

BIT_DStream_t DStream; // Stream context FSE_DState_t DState; // State context. Multiple ones are possible FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable()

The first thing to do is to init the bitStream. errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);

You should then retrieve your initial state(s) (in reverse flushing order if you have several ones) : errorCode = FSE_initDState(&DState, &DStream, DTablePtr);

You can then decode your data, symbol after symbol. For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'. Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out). unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);

You can retrieve any bitfield you eventually stored into the bitStream (in reverse order) Note : maximum allowed nbBits is 25, for 32-bits compatibility size_t bitField = BIT_readBits(&DStream, nbBits);

All above operations only read from local register (which size depends on size_t). Refueling the register from memory is manually performed by the reload method. endSignal = FSE_reloadDStream(&DStream);

BIT_reloadDStream() result tells if there is still some more data to read from DStream. BIT_DStream_unfinished : there is still some data left into the DStream. BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled. BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed. BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.

When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop, to properly detect the exact end of stream. After each decoded symbol, check if DStream is fully consumed using this simple test : BIT_reloadDStream(&DStream) >= BIT_DStream_completed

When it's done, verify decompression is fully completed, by checking both DStream and the relevant states. Checking if DStream has reached its end is performed by : BIT_endOfDStream(&DStream); Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible. FSE_endOfDState(&DState);

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_decodeSymbolFast()

MEM_STATIC BYTE duckdb_zstd::FSE_decodeSymbolFast ( FSE_DState_t * DStatePtr,
BIT_DStream_t * bitD )
static

FSE_decodeSymbolFast() : unsafe, only works if no symbol has a probability > 50%

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_initCState2()

MEM_STATIC void duckdb_zstd::FSE_initCState2 ( FSE_CState_t * statePtr,
const FSE_CTable * ct,
U32 symbol )

FSE_initCState2() : Same as FSE_initCState(), but the first symbol to include (which will be the last to be read) uses the smallest state value possible, saving the cost of this symbol

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_getMaxNbBits()

MEM_STATIC U32 duckdb_zstd::FSE_getMaxNbBits ( const void * symbolTTPtr,
U32 symbolValue )

◆ FSE_bitCost()

MEM_STATIC U32 duckdb_zstd::FSE_bitCost ( const void * symbolTTPtr,
U32 tableLog,
U32 symbolValue,
U32 accuracyLog )

◆ FSE_peekSymbol()

MEM_STATIC BYTE duckdb_zstd::FSE_peekSymbol ( const FSE_DState_t * DStatePtr)

◆ FSE_updateState()

MEM_STATIC void duckdb_zstd::FSE_updateState ( FSE_DState_t * DStatePtr,
BIT_DStream_t * bitD )

◆ HUF_compressBound()

size_t duckdb_zstd::HUF_compressBound ( size_t size)

maximum compressed size (worst case)

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_isError()

unsigned duckdb_zstd::HUF_isError ( size_t code)

tells if a return value is an error code

Here is the caller graph for this function:

◆ HUF_getErrorName()

const char * duckdb_zstd::HUF_getErrorName ( size_t code)

provides error code string (useful for debugging)

Here is the call graph for this function:

◆ HUF_minTableLog()

unsigned duckdb_zstd::HUF_minTableLog ( unsigned symbolCardinality)

HUF_compress() does the following:

  1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h")
  2. (optional) refine tableLog using HUF_optimalTableLog()
  3. build Huffman table from count using HUF_buildCTable()
  4. save Huffman table to memory buffer using HUF_writeCTable()
  5. encode the data stream using HUF_compress4X_usingCTable()

The following API allows targeting specific sub-functions for advanced tasks. For example, it's possible to compress several blocks using the same 'CTable', or to save and regenerate 'CTable' using external methods.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_cardinality()

unsigned duckdb_zstd::HUF_cardinality ( const unsigned * count,
unsigned maxSymbolValue )

◆ HUF_optimalTableLog()

unsigned duckdb_zstd::HUF_optimalTableLog ( unsigned maxTableLog,
size_t srcSize,
unsigned maxSymbolValue,
void * workSpace,
size_t wkspSize,
HUF_CElt * table,
const unsigned * count,
int flags )

◆ HUF_writeCTable_wksp()

size_t duckdb_zstd::HUF_writeCTable_wksp ( void * dst,
size_t maxDstSize,
const HUF_CElt * CTable,
unsigned maxSymbolValue,
unsigned huffLog,
void * workspace,
size_t workspaceSize )

◆ HUF_compress4X_usingCTable()

size_t duckdb_zstd::HUF_compress4X_usingCTable ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const HUF_CElt * CTable,
int flags )

◆ HUF_estimateCompressedSize()

size_t duckdb_zstd::HUF_estimateCompressedSize ( const HUF_CElt * CTable,
const unsigned * count,
unsigned maxSymbolValue )

◆ HUF_validateCTable()

int duckdb_zstd::HUF_validateCTable ( const HUF_CElt * CTable,
const unsigned * count,
unsigned maxSymbolValue )

◆ HUF_compress4X_repeat()

size_t duckdb_zstd::HUF_compress4X_repeat ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
unsigned maxSymbolValue,
unsigned tableLog,
void * workSpace,
size_t wkspSize,
HUF_CElt * hufTable,
HUF_repeat * repeat,
int flags )

HUF_compress4X_repeat() : Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. If it uses hufTable it does not modify hufTable or repeat. If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. If preferRepeat then the old table will always be used if valid. If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding

Parameters
wkspSizeworkSpace must be aligned on 4-bytes boundaries, wkspSize must be >= HUF_WORKSPACE_SIZE
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_buildCTable_wksp()

size_t duckdb_zstd::HUF_buildCTable_wksp ( HUF_CElt * tree,
const unsigned * count,
U32 maxSymbolValue,
U32 maxNbBits,
void * workSpace,
size_t wkspSize )

◆ HUF_readStats()

size_t duckdb_zstd::HUF_readStats ( BYTE * huffWeight,
size_t hwSize,
U32 * rankStats,
U32 * nbSymbolsPtr,
U32 * tableLogPtr,
const void * src,
size_t srcSize )

HUF_readStats() : Read compact Huffman tree, saved by HUF_writeCTable(). huffWeight is destination buffer.

Returns
: size read from src , or an error Code . Note : Needed by HUF_readCTable() and HUF_readDTableXn() .

HUF_readStats() : Read compact Huffman tree, saved by HUF_writeCTable(). huffWeight is destination buffer. rankStats is assumed to be a table of at least HUF_TABLELOG_MAX U32.

Returns
: size read from src , or an error Code . Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_readStats_wksp()

size_t duckdb_zstd::HUF_readStats_wksp ( BYTE * huffWeight,
size_t hwSize,
U32 * rankStats,
U32 * nbSymbolsPtr,
U32 * tableLogPtr,
const void * src,
size_t srcSize,
void * workspace,
size_t wkspSize,
int flags )

◆ HUF_readCTable()

size_t duckdb_zstd::HUF_readCTable ( HUF_CElt * CTable,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize,
unsigned * hasZeroWeights )

HUF_readCTable() : Loading a CTable saved with HUF_writeCTable()

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_getNbBitsFromCTable()

U32 duckdb_zstd::HUF_getNbBitsFromCTable ( const HUF_CElt * symbolTable,
U32 symbolValue )

HUF_getNbBitsFromCTable() : Read nbBits from CTable symbolTable, for symbol symbolValue presumed <= HUF_SYMBOLVALUE_MAX Note 1 : If symbolValue > HUF_readCTableHeader(symbolTable).maxSymbolValue, returns 0 Note 2 : is not inlined, as HUF_CElt definition is private

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_readCTableHeader()

HUF_CTableHeader duckdb_zstd::HUF_readCTableHeader ( HUF_CElt const * ctable)

HUF_readCTableHeader() :

Returns
The header from the CTable specifying the tableLog and the maxSymbolValue.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_selectDecoder()

U32 duckdb_zstd::HUF_selectDecoder ( size_t dstSize,
size_t cSrcSize )

HUF_selectDecoder() : Tells which decoder is likely to decode faster, based on a set of pre-computed metrics.

Returns
: 0==HUF_decompress4X1, 1==HUF_decompress4X2 . Assumption : 0 < dstSize <= 128 KB
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_compress1X_usingCTable()

size_t duckdb_zstd::HUF_compress1X_usingCTable ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const HUF_CElt * CTable,
int flags )

◆ HUF_compress1X_repeat()

size_t duckdb_zstd::HUF_compress1X_repeat ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
unsigned maxSymbolValue,
unsigned tableLog,
void * workSpace,
size_t wkspSize,
HUF_CElt * hufTable,
HUF_repeat * repeat,
int flags )

HUF_compress1X_repeat() : Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. If it uses hufTable it does not modify hufTable or repeat. If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. If preferRepeat then the old table will always be used if valid. If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding

Parameters
wkspSizeworkSpace must be aligned on 4-bytes boundaries, wkspSize must be >= HUF_WORKSPACE_SIZE
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_decompress1X_DCtx_wksp()

size_t duckdb_zstd::HUF_decompress1X_DCtx_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )

◆ HUF_decompress1X2_DCtx_wksp()

size_t duckdb_zstd::HUF_decompress1X2_DCtx_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )

double-symbols decoder

◆ HUF_decompress1X_usingDTable()

size_t duckdb_zstd::HUF_decompress1X_usingDTable ( void * dst,
size_t maxDstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable,
int flags )

◆ HUF_decompress1X1_DCtx_wksp()

size_t duckdb_zstd::HUF_decompress1X1_DCtx_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )

◆ HUF_decompress4X_usingDTable()

size_t duckdb_zstd::HUF_decompress4X_usingDTable ( void * dst,
size_t maxDstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable,
int flags )

◆ HUF_decompress4X_hufOnly_wksp()

size_t duckdb_zstd::HUF_decompress4X_hufOnly_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )

◆ HUF_readDTableX1_wksp()

size_t duckdb_zstd::HUF_readDTableX1_wksp ( HUF_DTable * DTable,
const void * src,
size_t srcSize,
void * workSpace,
size_t wkspSize,
int flags )

◆ HUF_readDTableX2_wksp()

size_t duckdb_zstd::HUF_readDTableX2_wksp ( HUF_DTable * DTable,
const void * src,
size_t srcSize,
void * workSpace,
size_t wkspSize,
int flags )

◆ FSE_readNCount_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::FSE_readNCount_body ( short * normalizedCounter,
unsigned * maxSVPtr,
unsigned * tableLogPtr,
const void * headerBuffer,
size_t hbSize )

◆ FSE_readNCount_body_default()

size_t duckdb_zstd::FSE_readNCount_body_default ( short * normalizedCounter,
unsigned * maxSVPtr,
unsigned * tableLogPtr,
const void * headerBuffer,
size_t hbSize )
static

◆ HUF_readStats_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_readStats_body ( BYTE * huffWeight,
size_t hwSize,
U32 * rankStats,
U32 * nbSymbolsPtr,
U32 * tableLogPtr,
const void * src,
size_t srcSize,
void * workSpace,
size_t wkspSize,
int bmi2 )

◆ HUF_readStats_body_default()

size_t duckdb_zstd::HUF_readStats_body_default ( BYTE * huffWeight,
size_t hwSize,
U32 * rankStats,
U32 * nbSymbolsPtr,
U32 * tableLogPtr,
const void * src,
size_t srcSize,
void * workSpace,
size_t wkspSize )
static

◆ FSE_buildDTable_internal()

size_t duckdb_zstd::FSE_buildDTable_internal ( FSE_DTable * dt,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
void * workSpace,
size_t wkspSize )
static

◆ FSE_decompress_usingDTable_generic()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::FSE_decompress_usingDTable_generic ( void * dst,
size_t maxDstSize,
const void * cSrc,
size_t cSrcSize,
const FSE_DTable * dt,
const unsigned fast )

◆ FSE_decompress_wksp_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::FSE_decompress_wksp_body ( void * dst,
size_t dstCapacity,
const void * cSrc,
size_t cSrcSize,
unsigned maxLog,
void * workSpace,
size_t wkspSize,
int bmi2 )

◆ FSE_decompress_wksp_body_default()

size_t duckdb_zstd::FSE_decompress_wksp_body_default ( void * dst,
size_t dstCapacity,
const void * cSrc,
size_t cSrcSize,
unsigned maxLog,
void * workSpace,
size_t wkspSize )
static

◆ ZSTD_customMalloc()

MEM_STATIC void * duckdb_zstd::ZSTD_customMalloc ( size_t size,
ZSTD_customMem customMem )

◆ ZSTD_customCalloc()

MEM_STATIC void * duckdb_zstd::ZSTD_customCalloc ( size_t size,
ZSTD_customMem customMem )

◆ ZSTD_customFree()

MEM_STATIC void duckdb_zstd::ZSTD_customFree ( void * ptr,
ZSTD_customMem customMem )

◆ POOL_create()

POOL_ctx * duckdb_zstd::POOL_create ( size_t numThreads,
size_t queueSize )

POOL_create() : Create a thread pool with at most numThreads threads. numThreads must be at least 1. The maximum number of queued jobs before blocking is queueSize.

Returns
: POOL_ctx pointer on success, else NULL.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_create_advanced()

POOL_ctx * duckdb_zstd::POOL_create_advanced ( size_t numThreads,
size_t queueSize,
ZSTD_customMem customMem )

◆ POOL_free()

void duckdb_zstd::POOL_free ( POOL_ctx * ctx)

POOL_free() : Free a thread pool returned by POOL_create().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_joinJobs()

void duckdb_zstd::POOL_joinJobs ( POOL_ctx * ctx)

POOL_joinJobs() : Waits for all queued jobs to finish executing.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_resize()

int duckdb_zstd::POOL_resize ( POOL_ctx * ctx,
size_t numThreads )

POOL_resize() : Expands or shrinks pool's number of threads. This is more efficient than releasing + creating a new context, since it tries to preserve and reuse existing threads. numThreads must be at least 1.

Returns
: 0 when resize was successful, !0 (typically 1) if there is an error. note : only numThreads can be resized, queueSize remains unchanged.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_sizeof()

size_t duckdb_zstd::POOL_sizeof ( const POOL_ctx * ctx)

POOL_sizeof() :

Returns
threadpool memory usage note : compatible with NULL (returns 0 in this case)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_add()

void duckdb_zstd::POOL_add ( POOL_ctx * ctx,
POOL_function function,
void * opaque )

POOL_add() : Add the job function(opaque) to the thread pool. ctx must be valid. Possibly blocks until there is room in the queue. Note : The function may be executed asynchronously, therefore, opaque must live until function has been completed.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_tryAdd()

int duckdb_zstd::POOL_tryAdd ( POOL_ctx * ctx,
POOL_function function,
void * opaque )

POOL_tryAdd() : Add the job function(opaque) to thread pool if a queue slot is available. Returns immediately even if not (does not block).

Returns
: 1 if successful, 0 if not.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_thread()

void * duckdb_zstd::POOL_thread ( void * opaque)
static

◆ POOL_join()

void duckdb_zstd::POOL_join ( POOL_ctx * ctx)
static

POOL_join() : Shutdown the queue, wake any sleeping threads, and join all of the threads.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_resize_internal()

int duckdb_zstd::POOL_resize_internal ( POOL_ctx * ctx,
size_t numThreads )
static

◆ isQueueFull()

int duckdb_zstd::isQueueFull ( POOL_ctx const * ctx)
static

Returns 1 if the queue is full and 0 otherwise.

When queueSize is 1 (pool was created with an intended queueSize of 0), then a queue is empty if there is a thread free and no job is waiting.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ POOL_add_internal()

void duckdb_zstd::POOL_add_internal ( POOL_ctx * ctx,
POOL_function function,
void * opaque )
static

◆ XXH_versionNumber()

XXH_PUBLIC_API unsigned duckdb_zstd::XXH_versionNumber ( void )

◆ XXH32()

XXH_PUBLIC_API unsigned int duckdb_zstd::XXH32 ( const void * input,
size_t length,
unsigned int seed )

◆ XXH64()

XXH_PUBLIC_API unsigned long long duckdb_zstd::XXH64 ( const void * input,
size_t length,
unsigned long long seed )

◆ XXH32_createState()

XXH_PUBLIC_API XXH32_state_t * duckdb_zstd::XXH32_createState ( void )

State allocation, compatible with dynamic libraries

Here is the call graph for this function:
Here is the caller graph for this function:

◆ XXH32_freeState()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH32_freeState ( XXH32_state_t * statePtr)

◆ XXH64_createState()

XXH_PUBLIC_API XXH64_state_t * duckdb_zstd::XXH64_createState ( void )

◆ XXH64_freeState()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH64_freeState ( XXH64_state_t * statePtr)

◆ XXH32_reset()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH32_reset ( XXH32_state_t * statePtr,
unsigned int seed )

◆ XXH32_update()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH32_update ( XXH32_state_t * statePtr,
const void * input,
size_t length )

◆ XXH32_digest()

XXH_PUBLIC_API unsigned int duckdb_zstd::XXH32_digest ( const XXH32_state_t * statePtr)

◆ XXH64_reset()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH64_reset ( XXH64_state_t * statePtr,
unsigned long long seed )

◆ XXH64_update()

XXH_PUBLIC_API XXH_errorcode duckdb_zstd::XXH64_update ( XXH64_state_t * statePtr,
const void * input,
size_t length )

◆ XXH64_digest()

XXH_PUBLIC_API unsigned long long duckdb_zstd::XXH64_digest ( const XXH64_state_t * statePtr)

◆ XXH32_copyState()

XXH_PUBLIC_API void duckdb_zstd::XXH32_copyState ( XXH32_state_t *__restrict dst_state,
const XXH32_state_t *__restrict src_state )

◆ XXH64_copyState()

XXH_PUBLIC_API void duckdb_zstd::XXH64_copyState ( XXH64_state_t *__restrict dst_state,
const XXH64_state_t *__restrict src_state )

◆ XXH32_canonicalFromHash()

XXH_PUBLIC_API void duckdb_zstd::XXH32_canonicalFromHash ( XXH32_canonical_t * dst,
XXH32_hash_t hash )

Default XXH result types are basic unsigned 32 and 64 bits. The canonical representation follows human-readable write convention, aka big-endian (large digits first). These functions allow transformation of hash result into and from its canonical format. This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ XXH64_canonicalFromHash()

XXH_PUBLIC_API void duckdb_zstd::XXH64_canonicalFromHash ( XXH64_canonical_t * dst,
XXH64_hash_t hash )

◆ XXH32_hashFromCanonical()

XXH_PUBLIC_API XXH32_hash_t duckdb_zstd::XXH32_hashFromCanonical ( const XXH32_canonical_t * src)

◆ XXH64_hashFromCanonical()

XXH_PUBLIC_API XXH64_hash_t duckdb_zstd::XXH64_hashFromCanonical ( const XXH64_canonical_t * src)

◆ XXH_malloc()

void * duckdb_zstd::XXH_malloc ( size_t s)
static

◆ XXH_free()

void duckdb_zstd::XXH_free ( void * p)
static

◆ XXH_memcpy()

void * duckdb_zstd::XXH_memcpy ( void * dest,
const void * src,
size_t size )
static

◆ XXH_read32()

U32 duckdb_zstd::XXH_read32 ( const void * memPtr)
static

◆ XXH_read64()

U64 duckdb_zstd::XXH_read64 ( const void * memPtr)
static

◆ XXH_swap32()

U32 duckdb_zstd::XXH_swap32 ( U32 x)
static

◆ XXH_swap64()

U64 duckdb_zstd::XXH_swap64 ( U64 x)
static

◆ XXH_readLE32_align()

XXHASH_FORCE_INLINE_TEMPLATE U32 duckdb_zstd::XXH_readLE32_align ( const void * ptr,
XXH_endianess endian,
XXH_alignment align )

◆ XXH_readLE32()

XXHASH_FORCE_INLINE_TEMPLATE U32 duckdb_zstd::XXH_readLE32 ( const void * ptr,
XXH_endianess endian )

◆ XXH_readBE32()

U32 duckdb_zstd::XXH_readBE32 ( const void * ptr)
static

◆ XXH_readLE64_align()

XXHASH_FORCE_INLINE_TEMPLATE U64 duckdb_zstd::XXH_readLE64_align ( const void * ptr,
XXH_endianess endian,
XXH_alignment align )

◆ XXH_readLE64()

XXHASH_FORCE_INLINE_TEMPLATE U64 duckdb_zstd::XXH_readLE64 ( const void * ptr,
XXH_endianess endian )

◆ XXH_readBE64()

U64 duckdb_zstd::XXH_readBE64 ( const void * ptr)
static

◆ XXH32_round()

U32 duckdb_zstd::XXH32_round ( U32 seed,
U32 input )
static

◆ XXH32_endian_align()

XXHASH_FORCE_INLINE_TEMPLATE U32 duckdb_zstd::XXH32_endian_align ( const void * input,
size_t len,
U32 seed,
XXH_endianess endian,
XXH_alignment align )

◆ XXH64_round()

U64 duckdb_zstd::XXH64_round ( U64 acc,
U64 input )
static

◆ XXH64_mergeRound()

U64 duckdb_zstd::XXH64_mergeRound ( U64 acc,
U64 val )
static

◆ XXH64_endian_align()

XXHASH_FORCE_INLINE_TEMPLATE U64 duckdb_zstd::XXH64_endian_align ( const void * input,
size_t len,
U64 seed,
XXH_endianess endian,
XXH_alignment align )

◆ XXH32_update_endian()

XXHASH_FORCE_INLINE_TEMPLATE XXH_errorcode duckdb_zstd::XXH32_update_endian ( XXH32_state_t * state,
const void * input,
size_t len,
XXH_endianess endian )

◆ XXH32_digest_endian()

XXHASH_FORCE_INLINE_TEMPLATE U32 duckdb_zstd::XXH32_digest_endian ( const XXH32_state_t * state,
XXH_endianess endian )

◆ XXH64_update_endian()

XXHASH_FORCE_INLINE_TEMPLATE XXH_errorcode duckdb_zstd::XXH64_update_endian ( XXH64_state_t * state,
const void * input,
size_t len,
XXH_endianess endian )

◆ XXH64_digest_endian()

XXHASH_FORCE_INLINE_TEMPLATE U64 duckdb_zstd::XXH64_digest_endian ( const XXH64_state_t * state,
XXH_endianess endian )

◆ ZSTD_cpuid()

MEM_STATIC ZSTD_cpuid_t duckdb_zstd::ZSTD_cpuid ( void )

◆ ZSTD_copy8()

void duckdb_zstd::ZSTD_copy8 ( void * dst,
const void * src )
static

◆ ZSTD_copy16()

void duckdb_zstd::ZSTD_copy16 ( void * dst,
const void * src )
static

◆ ZSTD_wildcopy()

MEM_STATIC FORCE_INLINE_ATTR void duckdb_zstd::ZSTD_wildcopy ( void * dst,
const void * src,
ptrdiff_t length,
ZSTD_overlap_e const ovtype )

ZSTD_wildcopy() : Custom version of ZSTD_memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)

Parameters
ovtypecontrols the overlap detection
  • ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  • ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart. The src buffer must be before the dst buffer.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_limitCopy()

MEM_STATIC size_t duckdb_zstd::ZSTD_limitCopy ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_getSequenceLength()

MEM_STATIC ZSTD_sequenceLength duckdb_zstd::ZSTD_getSequenceLength ( seqStore_t const * seqStore,
seqDef const * seq )

Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getSeqStore()

const seqStore_t * duckdb_zstd::ZSTD_getSeqStore ( const ZSTD_CCtx * ctx)

◆ ZSTD_seqToCodes()

int duckdb_zstd::ZSTD_seqToCodes ( const seqStore_t * seqStorePtr)

◆ ZSTD_invalidateRepCodes()

void duckdb_zstd::ZSTD_invalidateRepCodes ( ZSTD_CCtx * cctx)

◆ ZSTD_getcBlockSize()

size_t duckdb_zstd::ZSTD_getcBlockSize ( const void * src,
size_t srcSize,
blockProperties_t * bpPtr )

ZSTD_getcBlockSize() : Provides the size of compressed block from block header src

641785size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
641786 blockProperties_t* bpPtr)
641787{
641788 RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");
641789
641790 { U32 const cBlockHeader = MEM_readLE24(src);
641791 U32 const cSize = cBlockHeader >> 3;
641792 bpPtr->lastBlock = cBlockHeader & 1;
size_t ZSTD_getcBlockSize(const void *src, size_t srcSize, blockProperties_t *bpPtr)
Definition duckdb.cpp:641778
Here is the caller graph for this function:

◆ ZSTD_decodeSeqHeaders()

size_t duckdb_zstd::ZSTD_decodeSeqHeaders ( ZSTD_DCtx * dctx,
int * nbSeqPtr,
const void * src,
size_t srcSize )

ZSTD_decodeSeqHeaders() : decode sequence header from src

642411 :
642412 assert(0);
642413 RETURN_ERROR(GENERIC, "impossible");
642414 }
642415}
642416
642417size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
642418 const void* src, size_t srcSize)
642419{
642420 const BYTE* const istart = (const BYTE*)src;
642421 const BYTE* const iend = istart + srcSize;
642422 const BYTE* ip = istart;
642423 int nbSeq;
642424 DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
642425
642426 /* check */
642427 RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
642428
642429 /* SeqHead */
642430 nbSeq = *ip++;
642431 if (nbSeq > 0x7F) {
642432 if (nbSeq == 0xFF) {
642433 RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
642434 nbSeq = MEM_readLE16(ip) + LONGNBSEQ;
642435 ip+=2;
642436 } else {
642437 RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
642438 nbSeq = ((nbSeq-0x80)<<8) + *ip++;
642439 }
642440 }
642441 *nbSeqPtr = nbSeq;
642442
642443 if (nbSeq == 0) {
642444 /* No sequence : section ends immediately */
642445 RETURN_ERROR_IF(ip != iend, corruption_detected,
642446 "extraneous data present in the Sequences section");
642447 return (size_t)(ip - istart);
642448 }
642449
642450 /* FSE table descriptors */
642451 RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
642452 RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */
642453 { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
642454 symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
642455 symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
642456 ip++;
642457
642458 /* Build DTables */
642459 { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
642460 LLtype, MaxLL, LLFSELog,
642461 ip, iend-ip,
642462 LL_base, LL_bits,
642463 LL_defaultDTable, dctx->fseEntropy,
642464 dctx->ddictIsCold, nbSeq,
642465 dctx->workspace, sizeof(dctx->workspace),
642466 ZSTD_DCtx_get_bmi2(dctx));
642467 RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
642468 ip += llhSize;
642469 }
642470
642471 { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
642472 OFtype, MaxOff, OffFSELog,
642473 ip, iend-ip,
642474 OF_base, OF_bits,
642475 OF_defaultDTable, dctx->fseEntropy,
642476 dctx->ddictIsCold, nbSeq,
642477 dctx->workspace, sizeof(dctx->workspace),
642478 ZSTD_DCtx_get_bmi2(dctx));
642479 RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
642480 ip += ofhSize;
642481 }
642482
642483 { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
642484 MLtype, MaxML, MLFSELog,
642485 ip, iend-ip,
642486 ML_base, ML_bits,
642487 ML_defaultDTable, dctx->fseEntropy,
642488 dctx->ddictIsCold, nbSeq,
642489 dctx->workspace, sizeof(dctx->workspace),
642490 ZSTD_DCtx_get_bmi2(dctx));
size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx *dctx, int *nbSeqPtr, const void *src, size_t srcSize)
Definition duckdb.cpp:642410
static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol *DTableSpace, const ZSTD_seqSymbol **DTablePtr, symbolEncodingType_e type, unsigned max, U32 maxLog, const void *src, size_t srcSize, const U32 *baseValue, const U8 *nbAdditionalBits, const ZSTD_seqSymbol *defaultTable, U32 flagRepeatTable, int ddictIsCold, int nbSeq, U32 *wksp, size_t wkspSize, int bmi2)
Definition duckdb.cpp:642362
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cpuSupportsBmi2()

MEM_STATIC int duckdb_zstd::ZSTD_cpuSupportsBmi2 ( void )
Returns
true iff the CPU supports dynamic BMI2 dispatch.
614298{
614299 ZSTD_cpuid_t cpuid = ZSTD_cpuid();
614300 return ZSTD_cpuid_bmi1(cpuid) && ZSTD_cpuid_bmi2(cpuid);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_count()

size_t duckdb_zstd::HIST_count ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize )

HIST_count(): Provides the precise count of each byte within a table 'count'. 'count' is a table of unsigned int, of minimum size (*maxSymbolValuePtr+1). Updates *maxSymbolValuePtr with actual largest symbol value detected.

Returns
: count of the most frequent symbol (which isn't identified). or an error code, which can be tested using HIST_isError(). note : if return == srcSize, there is only one symbol.
615253{
615254 unsigned tmpCounters[HIST_WKSP_SIZE_U32];
615255 return HIST_count_wksp(count, maxSymbolValuePtr, src, srcSize, tmpCounters, sizeof(tmpCounters));
size_t HIST_count_wksp(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, void *workSpace, size_t workSpaceSize)
Definition duckdb.cpp:615229
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_isError()

unsigned duckdb_zstd::HIST_isError ( size_t code)

tells if a return value is an error code

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_count_wksp()

size_t duckdb_zstd::HIST_count_wksp ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize,
void * workSpace,
size_t workSpaceSize )

HIST_count_wksp() : Same as HIST_count(), but using an externally provided scratch buffer. Benefit is this function will use very little stack space. workSpace is a writable buffer which must be 4-bytes aligned, workSpaceSize must be >= HIST_WKSP_SIZE

615233{
615234 if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
615235 if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall);
615236 if (*maxSymbolValuePtr < 255)
615237 return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, checkMaxSymbolValue, (U32*)workSpace);
615238 *maxSymbolValuePtr = 255;
615239 return HIST_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, workSpace, workSpaceSize);
size_t HIST_countFast_wksp(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, void *workSpace, size_t workSpaceSize)
Definition duckdb.cpp:615215
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_countFast()

size_t duckdb_zstd::HIST_countFast ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize )

HIST_countFast() : same as HIST_count(), but blindly trusts that all byte values within src are <= *maxSymbolValuePtr. This function is unsafe, and will segfault if any value within src is > *maxSymbolValuePtr

615246{
615247 unsigned tmpCounters[HIST_WKSP_SIZE_U32];
615248 return HIST_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, tmpCounters, sizeof(tmpCounters));
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_countFast_wksp()

size_t duckdb_zstd::HIST_countFast_wksp ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize,
void * workSpace,
size_t workSpaceSize )

HIST_countFast_wksp() : Same as HIST_countFast(), but using an externally provided scratch buffer. workSpace is a writable buffer which must be 4-bytes aligned, workSpaceSize must be >= HIST_WKSP_SIZE

615219{
615220 if (sourceSize < 1500) /* heuristic threshold */
615221 return HIST_count_simple(count, maxSymbolValuePtr, source, sourceSize);
615222 if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
615223 if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall);
615224 return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, trustInput, (U32*)workSpace);
unsigned HIST_count_simple(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize)
Definition duckdb.cpp:615104
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HIST_count_simple()

unsigned duckdb_zstd::HIST_count_simple ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * src,
size_t srcSize )

HIST_count_simple() : Same as HIST_countFast(), this function is unsafe, and will segfault if any value within src is > *maxSymbolValuePtr. It is also a bit slower for large inputs. However, it does not need any additional memory (not even on stack).

Returns
: count of the most frequent symbol. Note this function doesn't produce any error (i.e. it must succeed).
615107{
615108 const BYTE* ip = (const BYTE*)src;
615109 const BYTE* const end = ip + srcSize;
615110 unsigned maxSymbolValue = *maxSymbolValuePtr;
615111 unsigned largestCount=0;
615112
615113 ZSTD_memset(count, 0, (maxSymbolValue+1) * sizeof(*count));
615114 if (srcSize==0) { *maxSymbolValuePtr = 0; return 0; }
615115
615116 while (ip<end) {
615117 assert(*ip <= maxSymbolValue);
615118 count[*ip++]++;
615119 }
615120
615121 while (!count[maxSymbolValue]) maxSymbolValue--;
615122 *maxSymbolValuePtr = maxSymbolValue;
615123
615124 { U32 s;
615125 for (s=0; s<=maxSymbolValue; s++)
615126 if (count[s] > largestCount) largestCount = count[s];
615127 }
615128
615129 return largestCount;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FSE_writeNCount_generic()

size_t duckdb_zstd::FSE_writeNCount_generic ( void * header,
size_t headerBufferSize,
const short * normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
unsigned writeIsSafe )
static
614676{
614677 BYTE* const ostart = (BYTE*) header;
614678 BYTE* out = ostart;
614679 BYTE* const oend = ostart + headerBufferSize;
614680 int nbBits;
614681 const int tableSize = 1 << tableLog;
614682 int remaining;
614683 int threshold;
614684 U32 bitStream = 0;
614685 int bitCount = 0;
614686 unsigned symbol = 0;
614687 unsigned const alphabetSize = maxSymbolValue + 1;
614688 int previousIs0 = 0;
614689
614690 /* Table Size */
614691 bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
614692 bitCount += 4;
614693
614694 /* Init */
614695 remaining = tableSize+1; /* +1 for extra accuracy */
614696 threshold = tableSize;
614697 nbBits = (int)tableLog+1;
614698
614699 while ((symbol < alphabetSize) && (remaining>1)) { /* stops at 1 */
614700 if (previousIs0) {
614701 unsigned start = symbol;
614702 while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
614703 if (symbol == alphabetSize) break; /* incorrect distribution */
614704 while (symbol >= start+24) {
614705 start+=24;
614706 bitStream += 0xFFFFU << bitCount;
614707 if ((!writeIsSafe) && (out > oend-2))
614708 return ERROR(dstSize_tooSmall); /* Buffer overflow */
614709 out[0] = (BYTE) bitStream;
614710 out[1] = (BYTE)(bitStream>>8);
614711 out+=2;
614712 bitStream>>=16;
614713 }
614714 while (symbol >= start+3) {
614715 start+=3;
614716 bitStream += 3U << bitCount;
614717 bitCount += 2;
614718 }
614719 bitStream += (symbol-start) << bitCount;
614720 bitCount += 2;
614721 if (bitCount>16) {
614722 if ((!writeIsSafe) && (out > oend - 2))
614723 return ERROR(dstSize_tooSmall); /* Buffer overflow */
614724 out[0] = (BYTE)bitStream;
614725 out[1] = (BYTE)(bitStream>>8);
614726 out += 2;
614727 bitStream >>= 16;
614728 bitCount -= 16;
614729 } }
614730 { int count = normalizedCounter[symbol++];
614731 int const max = (2*threshold-1) - remaining;
614732 remaining -= count < 0 ? -count : count;
614733 count++; /* +1 for extra accuracy */
614734 if (count>=threshold)
614735 count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
614736 bitStream += (U32)count << bitCount;
614737 bitCount += nbBits;
614738 bitCount -= (count<max);
614739 previousIs0 = (count==1);
614740 if (remaining<1) return ERROR(GENERIC);
614741 while (remaining<threshold) { nbBits--; threshold>>=1; }
614742 }
614743 if (bitCount>16) {
614744 if ((!writeIsSafe) && (out > oend - 2))
614745 return ERROR(dstSize_tooSmall); /* Buffer overflow */
614746 out[0] = (BYTE)bitStream;
614747 out[1] = (BYTE)(bitStream>>8);
614748 out += 2;
614749 bitStream >>= 16;
614750 bitCount -= 16;
614751 } }
614752
614753 if (remaining != 1)
614754 return ERROR(GENERIC); /* incorrect normalized distribution */
614755 assert(symbol <= alphabetSize);
614756
614757 /* flush remaining bitStream */
614758 if ((!writeIsSafe) && (out > oend - 2))
614759 return ERROR(dstSize_tooSmall); /* Buffer overflow */
614760 out[0] = (BYTE)bitStream;
614761 out[1] = (BYTE)(bitStream>>8);
614762 out+= (bitCount+7) /8;
614763
614764 assert(out >= ostart);
614765 return (size_t)(out-ostart);

◆ FSE_minTableLog()

unsigned duckdb_zstd::FSE_minTableLog ( size_t srcSize,
unsigned maxSymbolValue )
static
614788{
614789 U32 minBitsSrc = ZSTD_highbit32((U32)(srcSize)) + 1;
614790 U32 minBitsSymbols = ZSTD_highbit32(maxSymbolValue) + 2;
614791 U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
614792 assert(srcSize > 1); /* Not supported, RLE should be used instead */
614793 return minBits;

◆ FSE_normalizeM2()

size_t duckdb_zstd::FSE_normalizeM2 ( short * norm,
U32 tableLog,
const unsigned * count,
size_t total,
U32 maxSymbolValue,
short lowProbCount )
static
614819{
614820 short const NOT_YET_ASSIGNED = -2;
614821 U32 s;
614822 U32 distributed = 0;
614823 U32 ToDistribute;
614824
614825 /* Init */
614826 U32 const lowThreshold = (U32)(total >> tableLog);
614827 U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
614828
614829 for (s=0; s<=maxSymbolValue; s++) {
614830 if (count[s] == 0) {
614831 norm[s]=0;
614832 continue;
614833 }
614834 if (count[s] <= lowThreshold) {
614835 norm[s] = lowProbCount;
614836 distributed++;
614837 total -= count[s];
614838 continue;
614839 }
614840 if (count[s] <= lowOne) {
614841 norm[s] = 1;
614842 distributed++;
614843 total -= count[s];
614844 continue;
614845 }
614846
614847 norm[s]=NOT_YET_ASSIGNED;
614848 }
614849 ToDistribute = (1 << tableLog) - distributed;
614850
614851 if (ToDistribute == 0)
614852 return 0;
614853
614854 if ((total / ToDistribute) > lowOne) {
614855 /* risk of rounding to zero */
614856 lowOne = (U32)((total * 3) / (ToDistribute * 2));
614857 for (s=0; s<=maxSymbolValue; s++) {
614858 if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
614859 norm[s] = 1;
614860 distributed++;
614861 total -= count[s];
614862 continue;
614863 } }
614864 ToDistribute = (1 << tableLog) - distributed;
614865 }
614866
614867 if (distributed == maxSymbolValue+1) {
614868 /* all values are pretty poor;
614869 probably incompressible data (should have already been detected);
614870 find max, then give all remaining points to max */
614871 U32 maxV = 0, maxC = 0;
614872 for (s=0; s<=maxSymbolValue; s++)
614873 if (count[s] > maxC) { maxV=s; maxC=count[s]; }
614874 norm[maxV] += (short)ToDistribute;
614875 return 0;
614876 }
614877
614878 if (total == 0) {
614879 /* all of the symbols were low enough for the lowOne or lowThreshold */
614880 for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
614881 if (norm[s] > 0) { ToDistribute--; norm[s]++; }
614882 return 0;
614883 }
614884
614885 { U64 const vStepLog = 62 - tableLog;
614886 U64 const mid = (1ULL << (vStepLog-1)) - 1;
614887 U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total); /* scale on remaining */
614888 U64 tmpTotal = mid;
614889 for (s=0; s<=maxSymbolValue; s++) {
614890 if (norm[s]==NOT_YET_ASSIGNED) {
614891 U64 const end = tmpTotal + (count[s] * rStep);
614892 U32 const sStart = (U32)(tmpTotal >> vStepLog);
614893 U32 const sEnd = (U32)(end >> vStepLog);
614894 U32 const weight = sEnd - sStart;
614895 if (weight < 1)
614896 return ERROR(GENERIC);
614897 norm[s] = (short)weight;
614898 tmpTotal = end;
614899 } } }
614900
614901 return 0;
double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray())

◆ FSE_compress_usingCTable_generic()

size_t duckdb_zstd::FSE_compress_usingCTable_generic ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const FSE_CTable * ct,
const unsigned fast )
static
614993{
614994 const BYTE* const istart = (const BYTE*) src;
614995 const BYTE* const iend = istart + srcSize;
614996 const BYTE* ip=iend;
614997
614998 BIT_CStream_t bitC;
614999 FSE_CState_t CState1, CState2;
615000
615001 /* init */
615002 if (srcSize <= 2) return 0;
615003 { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
615004 if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
615005
615006#define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
615007
615008 if (srcSize & 1) {
615009 FSE_initCState2(&CState1, ct, *--ip);
615010 FSE_initCState2(&CState2, ct, *--ip);
615011 FSE_encodeSymbol(&bitC, &CState1, *--ip);
615012 FSE_FLUSHBITS(&bitC);
615013 } else {
615014 FSE_initCState2(&CState2, ct, *--ip);
615015 FSE_initCState2(&CState1, ct, *--ip);
615016 }
615017
615018 /* join to mod 4 */
615019 srcSize -= 2;
615020 if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
615021 FSE_encodeSymbol(&bitC, &CState2, *--ip);
615022 FSE_encodeSymbol(&bitC, &CState1, *--ip);
615023 FSE_FLUSHBITS(&bitC);
615024 }
615025
615026 /* 2 or 4 encoding per loop */
615027 while ( ip>istart ) {
615028
615029 FSE_encodeSymbol(&bitC, &CState2, *--ip);
615030
615031 if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
615032 FSE_FLUSHBITS(&bitC);
615033
615034 FSE_encodeSymbol(&bitC, &CState1, *--ip);
615035
615036 if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
615037 FSE_encodeSymbol(&bitC, &CState2, *--ip);
615038 FSE_encodeSymbol(&bitC, &CState1, *--ip);
615039 }
615040
615041 FSE_FLUSHBITS(&bitC);
615042 }
615043
615044 FSE_flushCState(&bitC, &CState2);
615045 FSE_flushCState(&bitC, &CState1);
615046 return BIT_closeCStream(&bitC);
MEM_STATIC size_t BIT_initCStream(BIT_CStream_t *bitC, void *dstBuffer, size_t dstCapacity)
Definition duckdb.cpp:609654
MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t *bitC)
Definition duckdb.cpp:609735
MEM_STATIC void FSE_initCState2(FSE_CState_t *statePtr, const FSE_CTable *ct, U32 symbol)
Definition duckdb.cpp:610175
static void FSE_flushCState(BIT_CStream_t *bitC, const FSE_CState_t *CStatePtr)
Definition duckdb.cpp:610195
Definition duckdb.cpp:610023

◆ HIST_count_parallel_wksp()

size_t duckdb_zstd::HIST_count_parallel_wksp ( unsigned * count,
unsigned * maxSymbolValuePtr,
const void * source,
size_t sourceSize,
HIST_checkInput_e check,
U32 *const workSpace )
static
615147{
615148 const BYTE* ip = (const BYTE*)source;
615149 const BYTE* const iend = ip+sourceSize;
615150 size_t const countSize = (*maxSymbolValuePtr + 1) * sizeof(*count);
615151 unsigned max=0;
615152 U32* const Counting1 = workSpace;
615153 U32* const Counting2 = Counting1 + 256;
615154 U32* const Counting3 = Counting2 + 256;
615155 U32* const Counting4 = Counting3 + 256;
615156
615157 /* safety checks */
615158 assert(*maxSymbolValuePtr <= 255);
615159 if (!sourceSize) {
615160 ZSTD_memset(count, 0, countSize);
615161 *maxSymbolValuePtr = 0;
615162 return 0;
615163 }
615164 ZSTD_memset(workSpace, 0, 4*256*sizeof(unsigned));
615165
615166 /* by stripes of 16 bytes */
615167 { U32 cached = MEM_read32(ip); ip += 4;
615168 while (ip < iend-15) {
615169 U32 c = cached; cached = MEM_read32(ip); ip += 4;
615170 Counting1[(BYTE) c ]++;
615171 Counting2[(BYTE)(c>>8) ]++;
615172 Counting3[(BYTE)(c>>16)]++;
615173 Counting4[ c>>24 ]++;
615174 c = cached; cached = MEM_read32(ip); ip += 4;
615175 Counting1[(BYTE) c ]++;
615176 Counting2[(BYTE)(c>>8) ]++;
615177 Counting3[(BYTE)(c>>16)]++;
615178 Counting4[ c>>24 ]++;
615179 c = cached; cached = MEM_read32(ip); ip += 4;
615180 Counting1[(BYTE) c ]++;
615181 Counting2[(BYTE)(c>>8) ]++;
615182 Counting3[(BYTE)(c>>16)]++;
615183 Counting4[ c>>24 ]++;
615184 c = cached; cached = MEM_read32(ip); ip += 4;
615185 Counting1[(BYTE) c ]++;
615186 Counting2[(BYTE)(c>>8) ]++;
615187 Counting3[(BYTE)(c>>16)]++;
615188 Counting4[ c>>24 ]++;
615189 }
615190 ip-=4;
615191 }
615192
615193 /* finish last symbols */
615194 while (ip<iend) Counting1[*ip++]++;
615195
615196 { U32 s;
615197 for (s=0; s<256; s++) {
615198 Counting1[s] += Counting2[s] + Counting3[s] + Counting4[s];
615199 if (Counting1[s] > max) max = Counting1[s];
615200 } }
615201
615202 { unsigned maxSymbolValue = 255;
615203 while (!Counting1[maxSymbolValue]) maxSymbolValue--;
615204 if (check && maxSymbolValue > *maxSymbolValuePtr) return ERROR(maxSymbolValue_tooSmall);
615205 *maxSymbolValuePtr = maxSymbolValue;
615206 ZSTD_memmove(count, Counting1, countSize); /* in case count & Counting1 are overlapping */
615207 }
615208 return (size_t)max;
void max(InputArray src1, InputArray src2, OutputArray dst)

◆ HUF_alignUpWorkspace()

void * duckdb_zstd::HUF_alignUpWorkspace ( void * workspace,
size_t * workspaceSizePtr,
size_t align )
static
615382{
615383 size_t const mask = align - 1;
615384 size_t const rem = (size_t)workspace & mask;
615385 size_t const add = (align - rem) & mask;
615386 BYTE* const aligned = (BYTE*)workspace + add;
615387 assert((align & (align - 1)) == 0); /* pow 2 */
615388 assert(align <= HUF_WORKSPACE_MAX_ALIGNMENT);
615389 if (*workspaceSizePtr >= add) {
615390 assert(add < align);
615391 assert(((size_t)aligned & mask) == 0);
615392 *workspaceSizePtr -= add;
615393 return aligned;
615394 } else {
615395 *workspaceSizePtr = 0;
615396 return NULL;
615397 }
GMat mask(const GMat &src, const GMat &mask)

◆ HUF_compressWeights()

size_t duckdb_zstd::HUF_compressWeights ( void * dst,
size_t dstSize,
const void * weightTable,
size_t wtSize,
void * workspace,
size_t workspaceSize )
static
615419{
615420 BYTE* const ostart = (BYTE*) dst;
615421 BYTE* op = ostart;
615422 BYTE* const oend = ostart + dstSize;
615423
615424 unsigned maxSymbolValue = HUF_TABLELOG_MAX;
615425 U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
615426 HUF_CompressWeightsWksp* wksp = (HUF_CompressWeightsWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));
615427
615428 if (workspaceSize < sizeof(HUF_CompressWeightsWksp)) return ERROR(GENERIC);
615429
615430 /* init conditions */
615431 if (wtSize <= 1) return 0; /* Not compressible */
615432
615433 /* Scan input and build symbol stats */
615434 { unsigned const maxCount = HIST_count_simple(wksp->count, &maxSymbolValue, weightTable, wtSize); /* never fails */
615435 if (maxCount == wtSize) return 1; /* only a single symbol in src : rle */
615436 if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
615437 }
615438
615439 tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
615440 CHECK_F( FSE_normalizeCount(wksp->norm, tableLog, wksp->count, wtSize, maxSymbolValue, /* useLowProbCount */ 0) );
615441
615442 /* Write table description header */
615443 { CHECK_V_F(hSize, FSE_writeNCount(op, (size_t)(oend-op), wksp->norm, maxSymbolValue, tableLog) );
615444 op += hSize;
615445 }
615446
615447 /* Compress */
615448 CHECK_F( FSE_buildCTable_wksp(wksp->CTable, wksp->norm, maxSymbolValue, tableLog, wksp->scratchBuffer, sizeof(wksp->scratchBuffer)) );
615449 { CHECK_V_F(cSize, FSE_compress_usingCTable(op, (size_t)(oend - op), weightTable, wtSize, wksp->CTable) );
615450 if (cSize == 0) return 0; /* not enough space for compressed data */
615451 op += cSize;
615452 }
615453
615454 return (size_t)(op-ostart);
FSE_PUBLIC_API size_t FSE_writeNCount(void *buffer, size_t bufferSize, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
Definition duckdb.cpp:614768
FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
Definition duckdb.cpp:614809
FSE_PUBLIC_API size_t FSE_compress_usingCTable(void *dst, size_t dstCapacity, const void *src, size_t srcSize, const FSE_CTable *ct)
Definition duckdb.cpp:615048
FSE_PUBLIC_API size_t FSE_normalizeCount(short *normalizedCounter, unsigned tableLog, const unsigned *count, size_t srcSize, unsigned maxSymbolValue, unsigned useLowProbCount)
Definition duckdb.cpp:614903
Definition duckdb.cpp:615407

◆ HUF_getNbBits()

size_t duckdb_zstd::HUF_getNbBits ( HUF_CElt elt)
static
615458{
615459 return elt & 0xFF;

◆ HUF_getNbBitsFast()

size_t duckdb_zstd::HUF_getNbBitsFast ( HUF_CElt elt)
static
615463{
615464 return elt;

◆ HUF_getValue()

size_t duckdb_zstd::HUF_getValue ( HUF_CElt elt)
static
615468{
615469 return elt & ~(size_t)0xFF;

◆ HUF_getValueFast()

size_t duckdb_zstd::HUF_getValueFast ( HUF_CElt elt)
static
615473{
615474 return elt;

◆ HUF_setNbBits()

void duckdb_zstd::HUF_setNbBits ( HUF_CElt * elt,
size_t nbBits )
static
615478{
615479 assert(nbBits <= HUF_TABLELOG_ABSOLUTEMAX);
615480 *elt = nbBits;

◆ HUF_setValue()

void duckdb_zstd::HUF_setValue ( HUF_CElt * elt,
size_t value )
static
615484{
615485 size_t const nbBits = HUF_getNbBits(*elt);
615486 if (nbBits > 0) {
615487 assert((value >> nbBits) == 0);
615488 *elt |= value << (sizeof(HUF_CElt) * 8 - nbBits);
615489 }

◆ HUF_writeCTableHeader()

void duckdb_zstd::HUF_writeCTableHeader ( HUF_CElt * ctable,
U32 tableLog,
U32 maxSymbolValue )
static
615500{
615501 HUF_CTableHeader header;
615502 HUF_STATIC_ASSERT(sizeof(ctable[0]) == sizeof(header));
615503 ZSTD_memset(&header, 0, sizeof(header));
615504 assert(tableLog < 256);
615505 header.tableLog = (BYTE)tableLog;
615506 assert(maxSymbolValue < 256);
615507 header.maxSymbolValue = (BYTE)maxSymbolValue;
615508 ZSTD_memcpy(ctable, &header, sizeof(header));

◆ HUF_setMaxHeight()

U32 duckdb_zstd::HUF_setMaxHeight ( nodeElt * huffNode,
U32 lastNonNull,
U32 targetNbBits )
static

HUF_setMaxHeight(): Try to enforce @targetNbBits on the Huffman tree described in @huffNode.

It attempts to convert all nodes with nbBits > @targetNbBits to employ @targetNbBits instead. Then it adjusts the tree so that it remains a valid canonical Huffman tree.

Precondition
The sum of the ranks of each symbol == 2^largestBits, where largestBits == huffNode[lastNonNull].nbBits.
Postcondition
The sum of the ranks of each symbol == 2^largestBits, where largestBits is the return value (expected <= targetNbBits).
Parameters
huffNodeThe Huffman tree modified in place to enforce targetNbBits. It's presumed sorted, from most frequent to rarest symbol.
lastNonNullThe symbol with the lowest count in the Huffman tree.
targetNbBitsThe allowed number of bits, which the Huffman tree may not respect. After this function the Huffman tree will respect targetNbBits.
Returns
The maximum number of bits of the Huffman tree after adjustment.
615646{
615647 const U32 largestBits = huffNode[lastNonNull].nbBits;
615648 /* early exit : no elt > targetNbBits, so the tree is already valid. */
615649 if (largestBits <= targetNbBits) return largestBits;
615650
615651 DEBUGLOG(5, "HUF_setMaxHeight (targetNbBits = %u)", targetNbBits);
615652
615653 /* there are several too large elements (at least >= 2) */
615654 { int totalCost = 0;
615655 const U32 baseCost = 1 << (largestBits - targetNbBits);
615656 int n = (int)lastNonNull;
615657
615658 /* Adjust any ranks > targetNbBits to targetNbBits.
615659 * Compute totalCost, which is how far the sum of the ranks is
615660 * we are over 2^largestBits after adjust the offending ranks.
615661 */
615662 while (huffNode[n].nbBits > targetNbBits) {
615663 totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
615664 huffNode[n].nbBits = (BYTE)targetNbBits;
615665 n--;
615666 }
615667 /* n stops at huffNode[n].nbBits <= targetNbBits */
615668 assert(huffNode[n].nbBits <= targetNbBits);
615669 /* n end at index of smallest symbol using < targetNbBits */
615670 while (huffNode[n].nbBits == targetNbBits) --n;
615671
615672 /* renorm totalCost from 2^largestBits to 2^targetNbBits
615673 * note : totalCost is necessarily a multiple of baseCost */
615674 assert(((U32)totalCost & (baseCost - 1)) == 0);
615675 totalCost >>= (largestBits - targetNbBits);
615676 assert(totalCost > 0);
615677
615678 /* repay normalized cost */
615679 { U32 const noSymbol = 0xF0F0F0F0;
615680 U32 rankLast[HUF_TABLELOG_MAX+2];
615681
615682 /* Get pos of last (smallest = lowest cum. count) symbol per rank */
615683 ZSTD_memset(rankLast, 0xF0, sizeof(rankLast));
615684 { U32 currentNbBits = targetNbBits;
615685 int pos;
615686 for (pos=n ; pos >= 0; pos--) {
615687 if (huffNode[pos].nbBits >= currentNbBits) continue;
615688 currentNbBits = huffNode[pos].nbBits; /* < targetNbBits */
615689 rankLast[targetNbBits-currentNbBits] = (U32)pos;
615690 } }
615691
615692 while (totalCost > 0) {
615693 /* Try to reduce the next power of 2 above totalCost because we
615694 * gain back half the rank.
615695 */
615696 U32 nBitsToDecrease = ZSTD_highbit32((U32)totalCost) + 1;
615697 for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {
615698 U32 const highPos = rankLast[nBitsToDecrease];
615699 U32 const lowPos = rankLast[nBitsToDecrease-1];
615700 if (highPos == noSymbol) continue;
615701 /* Decrease highPos if no symbols of lowPos or if it is
615702 * not cheaper to remove 2 lowPos than highPos.
615703 */
615704 if (lowPos == noSymbol) break;
615705 { U32 const highTotal = huffNode[highPos].count;
615706 U32 const lowTotal = 2 * huffNode[lowPos].count;
615707 if (highTotal <= lowTotal) break;
615708 } }
615709 /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
615710 assert(rankLast[nBitsToDecrease] != noSymbol || nBitsToDecrease == 1);
615711 /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
615712 while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
615713 nBitsToDecrease++;
615714 assert(rankLast[nBitsToDecrease] != noSymbol);
615715 /* Increase the number of bits to gain back half the rank cost. */
615716 totalCost -= 1 << (nBitsToDecrease-1);
615717 huffNode[rankLast[nBitsToDecrease]].nbBits++;
615718
615719 /* Fix up the new rank.
615720 * If the new rank was empty, this symbol is now its smallest.
615721 * Otherwise, this symbol will be the largest in the new rank so no adjustment.
615722 */
615723 if (rankLast[nBitsToDecrease-1] == noSymbol)
615724 rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease];
615725 /* Fix up the old rank.
615726 * If the symbol was at position 0, meaning it was the highest weight symbol in the tree,
615727 * it must be the only symbol in its rank, so the old rank now has no symbols.
615728 * Otherwise, since the Huffman nodes are sorted by count, the previous position is now
615729 * the smallest node in the rank. If the previous position belongs to a different rank,
615730 * then the rank is now empty.
615731 */
615732 if (rankLast[nBitsToDecrease] == 0) /* special case, reached largest symbol */
615733 rankLast[nBitsToDecrease] = noSymbol;
615734 else {
615735 rankLast[nBitsToDecrease]--;
615736 if (huffNode[rankLast[nBitsToDecrease]].nbBits != targetNbBits-nBitsToDecrease)
615737 rankLast[nBitsToDecrease] = noSymbol; /* this rank is now empty */
615738 }
615739 } /* while (totalCost > 0) */
615740
615741 /* If we've removed too much weight, then we have to add it back.
615742 * To avoid overshooting again, we only adjust the smallest rank.
615743 * We take the largest nodes from the lowest rank 0 and move them
615744 * to rank 1. There's guaranteed to be enough rank 0 symbols because
615745 * TODO.
615746 */
615747 while (totalCost < 0) { /* Sometimes, cost correction overshoot */
615748 /* special case : no rank 1 symbol (using targetNbBits-1);
615749 * let's create one from largest rank 0 (using targetNbBits).
615750 */
615751 if (rankLast[1] == noSymbol) {
615752 while (huffNode[n].nbBits == targetNbBits) n--;
615753 huffNode[n+1].nbBits--;
615754 assert(n >= 0);
615755 rankLast[1] = (U32)(n+1);
615756 totalCost++;
615757 continue;
615758 }
615759 huffNode[ rankLast[1] + 1 ].nbBits--;
615760 rankLast[1]++;
615761 totalCost ++;
615762 }
615763 } /* repay normalized cost */
615764 } /* there are several too large elements (at least >= 2) */
615765
615766 return targetNbBits;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_getIndex()

U32 duckdb_zstd::HUF_getIndex ( U32 const count)
static
615799 {
615800 return (count < RANK_POSITION_DISTINCT_COUNT_CUTOFF)
615801 ? count
615802 : ZSTD_highbit32(count) + RANK_POSITION_LOG_BUCKETS_BEGIN;

◆ HUF_swapNodes()

void duckdb_zstd::HUF_swapNodes ( nodeElt * a,
nodeElt * b )
static
615806 {
615807 nodeElt tmp = *a;
615808 *a = *b;
615809 *b = tmp;

◆ HUF_isSorted()

MEM_STATIC int duckdb_zstd::HUF_isSorted ( nodeElt huffNode[],
U32 const maxSymbolValue1 )
615813 {
615814 U32 i;
615815 for (i = 1; i < maxSymbolValue1; ++i) {
615816 if (huffNode[i].count > huffNode[i-1].count) {
615817 return 0;
615818 }
615819 }
615820 return 1;

◆ HUF_insertionSort()

HINT_INLINE void duckdb_zstd::HUF_insertionSort ( nodeElt huffNode[],
int const low,
int const high )
615824 {
615825 int i;
615826 int const size = high-low+1;
615827 huffNode += low;
615828 for (i = 1; i < size; ++i) {
615829 nodeElt const key = huffNode[i];
615830 int j = i - 1;
615831 while (j >= 0 && huffNode[j].count < key.count) {
615832 huffNode[j + 1] = huffNode[j];
615833 j--;
615834 }
615835 huffNode[j + 1] = key;
615836 }

◆ HUF_quickSortPartition()

int duckdb_zstd::HUF_quickSortPartition ( nodeElt arr[],
int const low,
int const high )
static
615840 {
615841 /* Simply select rightmost element as pivot. "Better" selectors like
615842 * median-of-three don't experimentally appear to have any benefit.
615843 */
615844 U32 const pivot = arr[high].count;
615845 int i = low - 1;
615846 int j = low;
615847 for ( ; j < high; j++) {
615848 if (arr[j].count > pivot) {
615849 i++;
615850 HUF_swapNodes(&arr[i], &arr[j]);
615851 }
615852 }
615853 HUF_swapNodes(&arr[i + 1], &arr[high]);
615854 return i + 1;

◆ HUF_simpleQuickSort()

void duckdb_zstd::HUF_simpleQuickSort ( nodeElt arr[],
int low,
int high )
static
615860 {
615861 int const kInsertionSortThreshold = 8;
615862 if (high - low < kInsertionSortThreshold) {
615863 HUF_insertionSort(arr, low, high);
615864 return;
615865 }
615866 while (low < high) {
615867 int const idx = HUF_quickSortPartition(arr, low, high);
615868 if (idx - low < high - idx) {
615869 HUF_simpleQuickSort(arr, low, idx - 1);
615870 low = idx + 1;
615871 } else {
615872 HUF_simpleQuickSort(arr, idx + 1, high);
615873 high = idx - 1;
615874 }
615875 }

◆ HUF_sort()

void duckdb_zstd::HUF_sort ( nodeElt huffNode[],
const unsigned count[],
U32 const maxSymbolValue,
rankPos rankPosition[] )
static

HUF_sort(): Sorts the symbols [0, maxSymbolValue] by count[symbol] in decreasing order. This is a typical bucket sorting strategy that uses either quicksort or insertion sort to sort each bucket.

Parameters
[out]huffNodeSorted symbols by decreasing count. Only members .count and .byte are filled. Must have (maxSymbolValue + 1) entries.
[in]countHistogram of the symbols.
[in]maxSymbolValueMaximum symbol value.
rankPositionThis is a scratch workspace. Must have RANK_POSITION_TABLE_SIZE entries.
615889 {
615890 U32 n;
615891 U32 const maxSymbolValue1 = maxSymbolValue+1;
615892
615893 /* Compute base and set curr to base.
615894 * For symbol s let lowerRank = HUF_getIndex(count[n]) and rank = lowerRank + 1.
615895 * See HUF_getIndex to see bucketing strategy.
615896 * We attribute each symbol to lowerRank's base value, because we want to know where
615897 * each rank begins in the output, so for rank R we want to count ranks R+1 and above.
615898 */
615899 ZSTD_memset(rankPosition, 0, sizeof(*rankPosition) * RANK_POSITION_TABLE_SIZE);
615900 for (n = 0; n < maxSymbolValue1; ++n) {
615901 U32 lowerRank = HUF_getIndex(count[n]);
615902 assert(lowerRank < RANK_POSITION_TABLE_SIZE - 1);
615903 rankPosition[lowerRank].base++;
615904 }
615905
615906 assert(rankPosition[RANK_POSITION_TABLE_SIZE - 1].base == 0);
615907 /* Set up the rankPosition table */
615908 for (n = RANK_POSITION_TABLE_SIZE - 1; n > 0; --n) {
615909 rankPosition[n-1].base += rankPosition[n].base;
615910 rankPosition[n-1].curr = rankPosition[n-1].base;
615911 }
615912
615913 /* Insert each symbol into their appropriate bucket, setting up rankPosition table. */
615914 for (n = 0; n < maxSymbolValue1; ++n) {
615915 U32 const c = count[n];
615916 U32 const r = HUF_getIndex(c) + 1;
615917 U32 const pos = rankPosition[r].curr++;
615918 assert(pos < maxSymbolValue1);
615919 huffNode[pos].count = c;
615920 huffNode[pos].byte = (BYTE)n;
615921 }
615922
615923 /* Sort each bucket. */
615924 for (n = RANK_POSITION_DISTINCT_COUNT_CUTOFF; n < RANK_POSITION_TABLE_SIZE - 1; ++n) {
615925 int const bucketSize = rankPosition[n].curr - rankPosition[n].base;
615926 U32 const bucketStartIdx = rankPosition[n].base;
615927 if (bucketSize > 1) {
615928 assert(bucketStartIdx < maxSymbolValue1);
615929 HUF_simpleQuickSort(huffNode + bucketStartIdx, 0, bucketSize-1);
615930 }
615931 }
615932
615933 assert(HUF_isSorted(huffNode, maxSymbolValue1));
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_buildTree()

int duckdb_zstd::HUF_buildTree ( nodeElt * huffNode,
U32 maxSymbolValue )
static
615951{
615952 nodeElt* const huffNode0 = huffNode - 1;
615953 int nonNullRank;
615954 int lowS, lowN;
615955 int nodeNb = STARTNODE;
615956 int n, nodeRoot;
615957 DEBUGLOG(5, "HUF_buildTree (alphabet size = %u)", maxSymbolValue + 1);
615958 /* init for parents */
615959 nonNullRank = (int)maxSymbolValue;
615960 while(huffNode[nonNullRank].count == 0) nonNullRank--;
615961 lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;
615962 huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;
615963 huffNode[lowS].parent = huffNode[lowS-1].parent = (U16)nodeNb;
615964 nodeNb++; lowS-=2;
615965 for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);
615966 huffNode0[0].count = (U32)(1U<<31); /* fake entry, strong barrier */
615967
615968 /* create parents */
615969 while (nodeNb <= nodeRoot) {
615970 int const n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
615971 int const n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
615972 huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
615973 huffNode[n1].parent = huffNode[n2].parent = (U16)nodeNb;
615974 nodeNb++;
615975 }
615976
615977 /* distribute weights (unlimited tree height) */
615978 huffNode[nodeRoot].nbBits = 0;
615979 for (n=nodeRoot-1; n>=STARTNODE; n--)
615980 huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
615981 for (n=0; n<=nonNullRank; n++)
615982 huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
615983
615984 DEBUGLOG(6, "Initial distribution of bits completed (%zu sorted symbols)", showHNodeBits(huffNode, maxSymbolValue+1));
615985
615986 return nonNullRank;
#define STARTNODE
Definition duckdb.cpp:615940

◆ HUF_buildCTableFromTree()

void duckdb_zstd::HUF_buildCTableFromTree ( HUF_CElt * CTable,
nodeElt const * huffNode,
int nonNullRank,
U32 maxSymbolValue,
U32 maxNbBits )
static

HUF_buildCTableFromTree(): Build the CTable given the Huffman tree in huffNode.

Parameters
[out]CTableThe output Huffman CTable.
huffNodeThe Huffman tree.
nonNullRankThe last and smallest node in the Huffman tree.
maxSymbolValueThe maximum symbol value.
maxNbBitsThe exact maximum number of bits used in the Huffman tree.
616000{
616001 HUF_CElt* const ct = CTable + 1;
616002 /* fill result into ctable (val, nbBits) */
616003 int n;
616004 U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};
616005 U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};
616006 int const alphabetSize = (int)(maxSymbolValue + 1);
616007 for (n=0; n<=nonNullRank; n++)
616008 nbPerRank[huffNode[n].nbBits]++;
616009 /* determine starting value per rank */
616010 { U16 min = 0;
616011 for (n=(int)maxNbBits; n>0; n--) {
616012 valPerRank[n] = min; /* get starting value within each rank */
616013 min += nbPerRank[n];
616014 min >>= 1;
616015 } }
616016 for (n=0; n<alphabetSize; n++)
616017 HUF_setNbBits(ct + huffNode[n].byte, huffNode[n].nbBits); /* push nbBits per symbol, symbol order */
616018 for (n=0; n<alphabetSize; n++)
616019 HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); /* assign value within rank, symbol order */
616020
616021 HUF_writeCTableHeader(CTable, maxNbBits, maxSymbolValue);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_initCStream()

size_t duckdb_zstd::HUF_initCStream ( HUF_CStream_t * bitC,
void * startPtr,
size_t dstCapacity )
static

! HUF_initCStream(): Initializes the bitstream.

Returns
0 or an error code.
616127{
616128 ZSTD_memset(bitC, 0, sizeof(*bitC));
616129 bitC->startPtr = (BYTE*)startPtr;
616130 bitC->ptr = bitC->startPtr;
616131 bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer[0]);
616132 if (dstCapacity <= sizeof(bitC->bitContainer[0])) return ERROR(dstSize_tooSmall);
616133 return 0;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_addBits()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_addBits ( HUF_CStream_t * bitC,
HUF_CElt elt,
int idx,
int kFast )

HUF_addBits(): Adds the symbol stored in HUF_CElt elt to the bitstream.

Parameters
eltThe element we're adding. This is a (nbBits, value) pair. See the HUF_CStream_t docs for the format.
idxInsert into the bitstream at this idx.
kFastThis is a template parameter. If the bitstream is guaranteed to have at least 4 unused bits after this call it may be 1, otherwise it must be 0. HUF_addBits() is faster when fast is set.
616147{
616148 assert(idx <= 1);
616149 assert(HUF_getNbBits(elt) <= HUF_TABLELOG_ABSOLUTEMAX);
616150 /* This is efficient on x86-64 with BMI2 because shrx
616151 * only reads the low 6 bits of the register. The compiler
616152 * knows this and elides the mask. When fast is set,
616153 * every operation can use the same value loaded from elt.
616154 */
616155 bitC->bitContainer[idx] >>= HUF_getNbBits(elt);
616156 bitC->bitContainer[idx] |= kFast ? HUF_getValueFast(elt) : HUF_getValue(elt);
616157 /* We only read the low 8 bits of bitC->bitPos[idx] so it
616158 * doesn't matter that the high bits have noise from the value.
616159 */
616160 bitC->bitPos[idx] += HUF_getNbBitsFast(elt);
616161 assert((bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
616162 /* The last 4-bits of elt are dirty if fast is set,
616163 * so we must not be overwriting bits that have already been
616164 * inserted into the bit container.
616165 */
616166#if DEBUGLEVEL >= 1
616167 {
616168 size_t const nbBits = HUF_getNbBits(elt);
616169 size_t const dirtyBits = nbBits == 0 ? 0 : ZSTD_highbit32((U32)nbBits) + 1;
616170 (void)dirtyBits;
616171 /* Middle bits are 0. */
616172 assert(((elt >> dirtyBits) << (dirtyBits + nbBits)) == 0);
616173 /* We didn't overwrite any bits in the bit container. */
616174 assert(!kFast || (bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
616175 (void)dirtyBits;
616176 }
616177#endif
#define HUF_BITS_IN_CONTAINER
Definition duckdb.cpp:616109
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_zeroIndex1()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_zeroIndex1 ( HUF_CStream_t * bitC)
616181{
616182 bitC->bitContainer[1] = 0;
616183 bitC->bitPos[1] = 0;

◆ HUF_mergeIndex1()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_mergeIndex1 ( HUF_CStream_t * bitC)

HUF_mergeIndex1() : Merges the bit container @ index 1 into the bit container @ index 0 and zeros the bit container @ index 1.

616191{
616192 assert((bitC->bitPos[1] & 0xFF) < HUF_BITS_IN_CONTAINER);
616193 bitC->bitContainer[0] >>= (bitC->bitPos[1] & 0xFF);
616194 bitC->bitContainer[0] |= bitC->bitContainer[1];
616195 bitC->bitPos[0] += bitC->bitPos[1];
616196 assert((bitC->bitPos[0] & 0xFF) <= HUF_BITS_IN_CONTAINER);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_flushBits()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_flushBits ( HUF_CStream_t * bitC,
int kFast )

HUF_flushBits() : Flushes the bits in the bit container @ index 0.

Postcondition
bitPos will be < 8.
Parameters
kFastIf kFast is set then we must know a-priori that the bit container will not overflow.
616207{
616208 /* The upper bits of bitPos are noisy, so we must mask by 0xFF. */
616209 size_t const nbBits = bitC->bitPos[0] & 0xFF;
616210 size_t const nbBytes = nbBits >> 3;
616211 /* The top nbBits bits of bitContainer are the ones we need. */
616212 size_t const bitContainer = bitC->bitContainer[0] >> (HUF_BITS_IN_CONTAINER - nbBits);
616213 /* Mask bitPos to account for the bytes we consumed. */
616214 bitC->bitPos[0] &= 7;
616215 assert(nbBits > 0);
616216 assert(nbBits <= sizeof(bitC->bitContainer[0]) * 8);
616217 assert(bitC->ptr <= bitC->endPtr);
616218 MEM_writeLEST(bitC->ptr, bitContainer);
616219 bitC->ptr += nbBytes;
616220 assert(!kFast || bitC->ptr <= bitC->endPtr);
616221 if (!kFast && bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
616222 /* bitContainer doesn't need to be modified because the leftover
616223 * bits are already the top bitPos bits. And we don't care about
616224 * noise in the lower values.
616225 */
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_endMark()

HUF_CElt duckdb_zstd::HUF_endMark ( void )
static

HUF_endMark()

Returns
The Huffman stream end mark: A 1-bit value = 1.
616232{
616233 HUF_CElt endMark;
616234 HUF_setNbBits(&endMark, 1);
616235 HUF_setValue(&endMark, 1);
616236 return endMark;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_closeCStream()

size_t duckdb_zstd::HUF_closeCStream ( HUF_CStream_t * bitC)
static

HUF_closeCStream() :

Returns
Size of CStream, in bytes, or 0 if it could not fit into dstBuffer
616243{
616244 HUF_addBits(bitC, HUF_endMark(), /* idx */ 0, /* kFast */ 0);
616245 HUF_flushBits(bitC, /* kFast */ 0);
616246 {
616247 size_t const nbBits = bitC->bitPos[0] & 0xFF;
616248 if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
616249 return (size_t)(bitC->ptr - bitC->startPtr) + (nbBits > 0);
616250 }
static HUF_CElt HUF_endMark(void)
Definition duckdb.cpp:616230
FORCE_INLINE_TEMPLATE void HUF_addBits(HUF_CStream_t *bitC, HUF_CElt elt, int idx, int kFast)
Definition duckdb.cpp:616145
FORCE_INLINE_TEMPLATE void HUF_flushBits(HUF_CStream_t *bitC, int kFast)
Definition duckdb.cpp:616205
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_encodeSymbol()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_encodeSymbol ( HUF_CStream_t * bitCPtr,
U32 symbol,
const HUF_CElt * CTable,
int idx,
int fast )
616255{
616256 HUF_addBits(bitCPtr, CTable[symbol], idx, fast);

◆ HUF_compress1X_usingCTable_internal_body_loop()

FORCE_INLINE_TEMPLATE void duckdb_zstd::HUF_compress1X_usingCTable_internal_body_loop ( HUF_CStream_t * bitC,
const BYTE * ip,
size_t srcSize,
const HUF_CElt * ct,
int kUnroll,
int kFastFlush,
int kLastFast )
616264{
616265 /* Join to kUnroll */
616266 int n = (int)srcSize;
616267 int rem = n % kUnroll;
616268 if (rem > 0) {
616269 for (; rem > 0; --rem) {
616270 HUF_encodeSymbol(bitC, ip[--n], ct, 0, /* fast */ 0);
616271 }
616272 HUF_flushBits(bitC, kFastFlush);
616273 }
616274 assert(n % kUnroll == 0);
616275
616276 /* Join to 2 * kUnroll */
616277 if (n % (2 * kUnroll)) {
616278 int u;
616279 for (u = 1; u < kUnroll; ++u) {
616280 HUF_encodeSymbol(bitC, ip[n - u], ct, 0, 1);
616281 }
616282 HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, 0, kLastFast);
616283 HUF_flushBits(bitC, kFastFlush);
616284 n -= kUnroll;
616285 }
616286 assert(n % (2 * kUnroll) == 0);
616287
616288 for (; n>0; n-= 2 * kUnroll) {
616289 /* Encode kUnroll symbols into the bitstream @ index 0. */
616290 int u;
616291 for (u = 1; u < kUnroll; ++u) {
616292 HUF_encodeSymbol(bitC, ip[n - u], ct, /* idx */ 0, /* fast */ 1);
616293 }
616294 HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, /* idx */ 0, /* fast */ kLastFast);
616295 HUF_flushBits(bitC, kFastFlush);
616296 /* Encode kUnroll symbols into the bitstream @ index 1.
616297 * This allows us to start filling the bit container
616298 * without any data dependencies.
616299 */
616300 HUF_zeroIndex1(bitC);
616301 for (u = 1; u < kUnroll; ++u) {
616302 HUF_encodeSymbol(bitC, ip[n - kUnroll - u], ct, /* idx */ 1, /* fast */ 1);
616303 }
616304 HUF_encodeSymbol(bitC, ip[n - kUnroll - kUnroll], ct, /* idx */ 1, /* fast */ kLastFast);
616305 /* Merge bitstream @ index 1 into the bitstream @ index 0 */
616306 HUF_mergeIndex1(bitC);
616307 HUF_flushBits(bitC, kFastFlush);
616308 }
616309 assert(n == 0);
616310
FORCE_INLINE_TEMPLATE void HUF_mergeIndex1(HUF_CStream_t *bitC)
Definition duckdb.cpp:616189

◆ HUF_tightCompressBound()

size_t duckdb_zstd::HUF_tightCompressBound ( size_t srcSize,
size_t tableLog )
static

Returns a tight upper bound on the output space needed by Huffman with 8 bytes buffer to handle over-writes. If the output is at least this large we don't need to do bounds checks during Huffman encoding.

616319{
616320 return ((srcSize * tableLog) >> 3) + 8;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_compress1X_usingCTable_internal_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_compress1X_usingCTable_internal_body ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const HUF_CElt * CTable )
616328{
616329 U32 const tableLog = HUF_readCTableHeader(CTable).tableLog;
616330 HUF_CElt const* ct = CTable + 1;
616331 const BYTE* ip = (const BYTE*) src;
616332 BYTE* const ostart = (BYTE*)dst;
616333 BYTE* const oend = ostart + dstSize;
616334 HUF_CStream_t bitC;
616335
616336 /* init */
616337 if (dstSize < 8) return 0; /* not enough space to compress */
616338 { BYTE* op = ostart;
616339 size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));
616340 if (HUF_isError(initErr)) return 0; }
616341
616342 if (dstSize < HUF_tightCompressBound(srcSize, (size_t)tableLog) || tableLog > 11)
616343 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ MEM_32bits() ? 2 : 4, /* kFast */ 0, /* kLastFast */ 0);
616344 else {
616345 if (MEM_32bits()) {
616346 switch (tableLog) {
616347 case 11:
616348 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 0);
616349 break;
616350 case 10: ZSTD_FALLTHROUGH;
616351 case 9: ZSTD_FALLTHROUGH;
616352 case 8:
616353 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 1);
616354 break;
616355 case 7: ZSTD_FALLTHROUGH;
616356 default:
616357 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 3, /* kFastFlush */ 1, /* kLastFast */ 1);
616358 break;
616359 }
616360 } else {
616361 switch (tableLog) {
616362 case 11:
616363 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 0);
616364 break;
616365 case 10:
616366 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 1);
616367 break;
616368 case 9:
616369 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 6, /* kFastFlush */ 1, /* kLastFast */ 0);
616370 break;
616371 case 8:
616372 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 7, /* kFastFlush */ 1, /* kLastFast */ 0);
616373 break;
616374 case 7:
616375 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 8, /* kFastFlush */ 1, /* kLastFast */ 0);
616376 break;
616377 case 6: ZSTD_FALLTHROUGH;
616378 default:
616379 HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 9, /* kFastFlush */ 1, /* kLastFast */ 1);
616380 break;
616381 }
616382 }
616383 }
616384 assert(bitC.ptr <= bitC.endPtr);
616385
616386 return HUF_closeCStream(&bitC);
static size_t HUF_closeCStream(HUF_CStream_t *bitC)
Definition duckdb.cpp:616241
static size_t HUF_tightCompressBound(size_t srcSize, size_t tableLog)
Definition duckdb.cpp:616317
static size_t HUF_initCStream(HUF_CStream_t *bitC, void *startPtr, size_t dstCapacity)
Definition duckdb.cpp:616124
Definition duckdb.cpp:616111

◆ HUF_compress1X_usingCTable_internal()

size_t duckdb_zstd::HUF_compress1X_usingCTable_internal ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const HUF_CElt * CTable,
const int flags )
static
616424{
616425 (void)flags;
616426 return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);

◆ HUF_compress4X_usingCTable_internal()

size_t duckdb_zstd::HUF_compress4X_usingCTable_internal ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
const HUF_CElt * CTable,
int flags )
static
616440{
616441 size_t const segmentSize = (srcSize+3)/4; /* first 3 segments */
616442 const BYTE* ip = (const BYTE*) src;
616443 const BYTE* const iend = ip + srcSize;
616444 BYTE* const ostart = (BYTE*) dst;
616445 BYTE* const oend = ostart + dstSize;
616446 BYTE* op = ostart;
616447
616448 if (dstSize < 6 + 1 + 1 + 1 + 8) return 0; /* minimum space to compress successfully */
616449 if (srcSize < 12) return 0; /* no saving possible : too small input */
616450 op += 6; /* jumpTable */
616451
616452 assert(op <= oend);
616453 { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
616454 if (cSize == 0 || cSize > 65535) return 0;
616455 MEM_writeLE16(ostart, (U16)cSize);
616456 op += cSize;
616457 }
616458
616459 ip += segmentSize;
616460 assert(op <= oend);
616461 { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
616462 if (cSize == 0 || cSize > 65535) return 0;
616463 MEM_writeLE16(ostart+2, (U16)cSize);
616464 op += cSize;
616465 }
616466
616467 ip += segmentSize;
616468 assert(op <= oend);
616469 { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
616470 if (cSize == 0 || cSize > 65535) return 0;
616471 MEM_writeLE16(ostart+4, (U16)cSize);
616472 op += cSize;
616473 }
616474
616475 ip += segmentSize;
616476 assert(op <= oend);
616477 assert(ip <= iend);
616478 { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, (size_t)(iend-ip), CTable, flags) );
616479 if (cSize == 0 || cSize > 65535) return 0;
616480 op += cSize;
616481 }
616482
616483 return (size_t)(op-ostart);

◆ HUF_compressCTable_internal()

size_t duckdb_zstd::HUF_compressCTable_internal ( BYTE *const ostart,
BYTE * op,
BYTE *const oend,
const void * src,
size_t srcSize,
HUF_nbStreams_e nbStreams,
const HUF_CElt * CTable,
const int flags )
static
616497{
616498 size_t const cSize = (nbStreams==HUF_singleStream) ?
616499 HUF_compress1X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags) :
616500 HUF_compress4X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags);
616501 if (HUF_isError(cSize)) { return cSize; }
616502 if (cSize==0) { return 0; } /* uncompressible */
616503 op += cSize;
616504 /* check compressibility */
616505 assert(op >= ostart);
616506 if ((size_t)(op-ostart) >= srcSize-1) { return 0; }
616507 return (size_t)(op-ostart);

◆ HUF_compress_internal()

size_t duckdb_zstd::HUF_compress_internal ( void * dst,
size_t dstSize,
const void * src,
size_t srcSize,
unsigned maxSymbolValue,
unsigned huffLog,
HUF_nbStreams_e nbStreams,
void * workSpace,
size_t wkspSize,
HUF_CElt * oldHufTable,
HUF_repeat * repeat,
int flags )
static
616608{
616609 HUF_compress_tables_t* const table = (HUF_compress_tables_t*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(size_t));
616610 BYTE* const ostart = (BYTE*)dst;
616611 BYTE* const oend = ostart + dstSize;
616612 BYTE* op = ostart;
616613
616614 DEBUGLOG(5, "HUF_compress_internal (srcSize=%zu)", srcSize);
616615 HUF_STATIC_ASSERT(sizeof(*table) + HUF_WORKSPACE_MAX_ALIGNMENT <= HUF_WORKSPACE_SIZE);
616616
616617 /* checks & inits */
616618 if (wkspSize < sizeof(*table)) return ERROR(workSpace_tooSmall);
616619 if (!srcSize) return 0; /* Uncompressed */
616620 if (!dstSize) return 0; /* cannot fit anything within dst budget */
616621 if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong); /* current block size limit */
616622 if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
616623 if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
616624 if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;
616625 if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;
616626
616627 /* Heuristic : If old table is valid, use it for small inputs */
616628 if ((flags & HUF_flags_preferRepeat) && repeat && *repeat == HUF_repeat_valid) {
616629 return HUF_compressCTable_internal(ostart, op, oend,
616630 src, srcSize,
616631 nbStreams, oldHufTable, flags);
616632 }
616633
616634 /* If uncompressible data is suspected, do a smaller sampling first */
616635 DEBUG_STATIC_ASSERT(SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO >= 2);
616636 if ((flags & HUF_flags_suspectUncompressible) && srcSize >= (SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE * SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO)) {
616637 size_t largestTotal = 0;
616638 DEBUGLOG(5, "input suspected incompressible : sampling to check");
616639 { unsigned maxSymbolValueBegin = maxSymbolValue;
616640 CHECK_V_F(largestBegin, HIST_count_simple (table->count, &maxSymbolValueBegin, (const BYTE*)src, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
616641 largestTotal += largestBegin;
616642 }
616643 { unsigned maxSymbolValueEnd = maxSymbolValue;
616644 CHECK_V_F(largestEnd, HIST_count_simple (table->count, &maxSymbolValueEnd, (const BYTE*)src + srcSize - SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
616645 largestTotal += largestEnd;
616646 }
616647 if (largestTotal <= ((2 * SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) >> 7)+4) return 0; /* heuristic : probably not compressible enough */
616648 }
616649
616650 /* Scan input and build symbol stats */
616651 { CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, table->wksps.hist_wksp, sizeof(table->wksps.hist_wksp)) );
616652 if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; } /* single symbol, rle */
616653 if (largest <= (srcSize >> 7)+4) return 0; /* heuristic : probably not compressible enough */
616654 }
616655 DEBUGLOG(6, "histogram detail completed (%zu symbols)", showU32(table->count, maxSymbolValue+1));
616656
616657 /* Check validity of previous table */
616658 if ( repeat
616659 && *repeat == HUF_repeat_check
616660 && !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {
616662 }
616663 /* Heuristic : use existing table for small inputs */
616664 if ((flags & HUF_flags_preferRepeat) && repeat && *repeat != HUF_repeat_none) {
616665 return HUF_compressCTable_internal(ostart, op, oend,
616666 src, srcSize,
616667 nbStreams, oldHufTable, flags);
616668 }
616669
616670 /* Build Huffman Tree */
616671 huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, &table->wksps, sizeof(table->wksps), table->CTable, table->count, flags);
616672 { size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,
616673 maxSymbolValue, huffLog,
616674 &table->wksps.buildCTable_wksp, sizeof(table->wksps.buildCTable_wksp));
616675 CHECK_F(maxBits);
616676 huffLog = (U32)maxBits;
616677 DEBUGLOG(6, "bit distribution completed (%zu symbols)", showCTableBits(table->CTable + 1, maxSymbolValue+1));
616678 }
616679
616680 /* Write table description header */
616681 { CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog,
616682 &table->wksps.writeCTable_wksp, sizeof(table->wksps.writeCTable_wksp)) );
616683 /* Check if using previous huffman table is beneficial */
616684 if (repeat && *repeat != HUF_repeat_none) {
616685 size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);
616686 size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);
616687 if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
616688 return HUF_compressCTable_internal(ostart, op, oend,
616689 src, srcSize,
616690 nbStreams, oldHufTable, flags);
616691 } }
616692
616693 /* Use the new huffman table */
616694 if (hSize + 12ul >= srcSize) { return 0; }
616695 op += hSize;
616696 if (repeat) { *repeat = HUF_repeat_none; }
616697 if (oldHufTable)
616698 ZSTD_memcpy(oldHufTable, table->CTable, sizeof(table->CTable)); /* Save new table */
616699 }
616700 return HUF_compressCTable_internal(ostart, op, oend,
616701 src, srcSize,
616702 nbStreams, table->CTable, flags);
#define HUF_BLOCKSIZE_MAX
Definition duckdb.cpp:610397
Definition duckdb.cpp:616509

◆ ZSTD_cwksp_available_space()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_available_space ( ZSTD_cwksp * ws)
617396 {
617397 return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);

◆ ZSTD_cwksp_initialAllocStart()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_initialAllocStart ( ZSTD_cwksp * ws)

Returns the initial value for allocStart which is used to determine the position from which we can allocate from the end of the workspace.

617052 {
617053 return (void*)((size_t)ws->workspaceEnd & ~(ZSTD_CWKSP_ALIGNMENT_BYTES-1));
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_assert_internal_consistency()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_assert_internal_consistency ( ZSTD_cwksp * ws)
616976 {
616977 (void)ws;
616978 assert(ws->workspace <= ws->objectEnd);
616979 assert(ws->objectEnd <= ws->tableEnd);
616980 assert(ws->objectEnd <= ws->tableValidEnd);
616981 assert(ws->tableEnd <= ws->allocStart);
616982 assert(ws->tableValidEnd <= ws->allocStart);
616983 assert(ws->allocStart <= ws->workspaceEnd);
616984 assert(ws->initOnceStart <= ZSTD_cwksp_initialAllocStart(ws));
616985 assert(ws->workspace <= ws->initOnceStart);
MEM_STATIC void * ZSTD_cwksp_initialAllocStart(ZSTD_cwksp *ws)
Definition duckdb.cpp:617051

◆ ZSTD_cwksp_align()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_align ( size_t size,
size_t const align )

Align must be a power of 2.

616991 {
616992 size_t const mask = align - 1;
616993 assert((align & mask) == 0);
616994 return (size + mask) & ~mask;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_alloc_size()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_alloc_size ( size_t size)

Use this to determine how much space in the workspace we will consume to allocate this object. (Normally it should be exactly the size of the object, but under special conditions, like ASAN, where we pad each object, it might be larger.)

Since tables aren't currently redzoned, you don't need to call through this to figure out how much space you need for the matchState tables. Everything else is though.

Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned_alloc_size().

617009 {
617010 if (size == 0)
617011 return 0;
617012 return size;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_aligned_alloc_size()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_aligned_alloc_size ( size_t size)

Returns an adjusted alloc size that is the nearest larger multiple of 64 bytes. Used to determine the number of bytes required for a given "aligned".

617019 {
617020 return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, ZSTD_CWKSP_ALIGNMENT_BYTES));
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_slack_space_required()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_slack_space_required ( void )

Returns the amount of additional space the cwksp must allocate for internal purposes (currently only alignment).

617027 {
617028 /* For alignment, the wksp will always allocate an additional 2*ZSTD_CWKSP_ALIGNMENT_BYTES
617029 * bytes to align the beginning of tables section and end of buffers;
617030 */
617031 size_t const slackSpace = ZSTD_CWKSP_ALIGNMENT_BYTES * 2;
617032 return slackSpace;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_bytes_to_align_ptr()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_bytes_to_align_ptr ( void * ptr,
const size_t alignBytes )

Return the number of additional bytes required to align a pointer to the given number of bytes. alignBytes must be a power of two.

617040 {
617041 size_t const alignBytesMask = alignBytes - 1;
617042 size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask;
617043 assert((alignBytes & alignBytesMask) == 0);
617044 assert(bytes < alignBytes);
617045 return bytes;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_internal_buffer_space()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_internal_buffer_space ( ZSTD_cwksp * ws,
size_t const bytes )

Internal function. Do not use directly. Reserves the given number of bytes within the aligned/buffer segment of the wksp, which counts from the end of the wksp (as opposed to the object/table segment).

Returns a pointer to the beginning of that space.

617065{
617066 void* const alloc = (BYTE*)ws->allocStart - bytes;
617067 void* const bottom = ws->tableEnd;
617068 DEBUGLOG(5, "cwksp: reserving %p %zd bytes, %zd bytes remaining",
617069 alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
617070 ZSTD_cwksp_assert_internal_consistency(ws);
617071 assert(alloc >= bottom);
617072 if (alloc < bottom) {
617073 DEBUGLOG(4, "cwksp: alloc failed!");
617074 ws->allocFailed = 1;
617075 return NULL;
617076 }
617077 /* the area is reserved from the end of wksp.
617078 * If it overlaps with tableValidEnd, it voids guarantees on values' range */
617079 if (alloc < ws->tableValidEnd) {
617080 ws->tableValidEnd = alloc;
617081 }
617082 ws->allocStart = alloc;
617083 return alloc;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_internal_advance_phase()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_internal_advance_phase ( ZSTD_cwksp * ws,
ZSTD_cwksp_alloc_phase_e phase )

Moves the cwksp to the next phase, and does any necessary allocations. cwksp initialization must necessarily go through each phase in order. Returns a 0 on success, or zstd error

617093{
617094 assert(phase >= ws->phase);
617095 if (phase > ws->phase) {
617096 /* Going from allocating objects to allocating initOnce / tables */
617097 if (ws->phase < ZSTD_cwksp_alloc_aligned_init_once &&
617098 phase >= ZSTD_cwksp_alloc_aligned_init_once) {
617099 ws->tableValidEnd = ws->objectEnd;
617100 ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
617101
617102 { /* Align the start of the tables to 64 bytes. Use [0, 63] bytes */
617103 void *const alloc = ws->objectEnd;
617104 size_t const bytesToAlign = ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES);
617105 void *const objectEnd = (BYTE *) alloc + bytesToAlign;
617106 DEBUGLOG(5, "reserving table alignment addtl space: %zu", bytesToAlign);
617107 RETURN_ERROR_IF(objectEnd > ws->workspaceEnd, memory_allocation,
617108 "table phase - alignment initial allocation failed!");
617109 ws->objectEnd = objectEnd;
617110 ws->tableEnd = objectEnd; /* table area starts being empty */
617111 if (ws->tableValidEnd < ws->tableEnd) {
617112 ws->tableValidEnd = ws->tableEnd;
617113 }
617114 }
617115 }
617116 ws->phase = phase;
617117 ZSTD_cwksp_assert_internal_consistency(ws);
617118 }
617119 return 0;
void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees=false)
MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void *ptr, const size_t alignBytes)
Definition duckdb.cpp:617039
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_owns_buffer()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_owns_buffer ( const ZSTD_cwksp * ws,
const void * ptr )

Returns whether this object/buffer/etc was allocated in this workspace.

617126{
617127 return (ptr != NULL) && (ws->workspace <= ptr) && (ptr < ws->workspaceEnd);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_internal()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_internal ( ZSTD_cwksp * ws,
size_t bytes,
ZSTD_cwksp_alloc_phase_e phase )

Internal function. Do not use directly.

617135{
617136 void* alloc;
617137 if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0) {
617138 return NULL;
617139 }
617140
617141 alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
617142 return alloc;
MEM_STATIC void * ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp *ws, size_t const bytes)
Definition duckdb.cpp:617063
MEM_STATIC size_t ZSTD_cwksp_internal_advance_phase(ZSTD_cwksp *ws, ZSTD_cwksp_alloc_phase_e phase)
Definition duckdb.cpp:617091
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_buffer()

MEM_STATIC BYTE * duckdb_zstd::ZSTD_cwksp_reserve_buffer ( ZSTD_cwksp * ws,
size_t bytes )

Reserves and returns unaligned memory.

617149{
617150 return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
MEM_STATIC void * ZSTD_cwksp_reserve_internal(ZSTD_cwksp *ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase)
Definition duckdb.cpp:617133
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_aligned_init_once()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_aligned_init_once ( ZSTD_cwksp * ws,
size_t bytes )

Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes). This memory has been initialized at least once in the past. This doesn't mean it has been initialized this time, and it might contain data from previous operations. The main usage is for algorithms that might need read access into uninitialized memory. The algorithm must maintain safety under these conditions and must make sure it doesn't leak any of the past data (directly or in side channels).

617163{
617164 size_t const alignedBytes = ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES);
617165 void* ptr = ZSTD_cwksp_reserve_internal(ws, alignedBytes, ZSTD_cwksp_alloc_aligned_init_once);
617166 assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
617167 if(ptr && ptr < ws->initOnceStart) {
617168 /* We assume the memory following the current allocation is either:
617169 * 1. Not usable as initOnce memory (end of workspace)
617170 * 2. Another initOnce buffer that has been allocated before (and so was previously memset)
617171 * 3. An ASAN redzone, in which case we don't want to write on it
617172 * For these reasons it should be fine to not explicitly zero every byte up to ws->initOnceStart.
617173 * Note that we assume here that MSAN and ASAN cannot run in the same time. */
617174 ZSTD_memset(ptr, 0, MIN((size_t)((U8*)ws->initOnceStart - (U8*)ptr), alignedBytes));
617175 ws->initOnceStart = ptr;
617176 }
617177#if ZSTD_MEMORY_SANITIZER
617178 assert(__msan_test_shadow(ptr, bytes) == -1);
617179#endif
617180 return ptr;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_aligned()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_aligned ( ZSTD_cwksp * ws,
size_t bytes )

Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).

617187{
617188 void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
617189 ZSTD_cwksp_alloc_aligned);
617190 assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
617191 return ptr;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_table()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_table ( ZSTD_cwksp * ws,
size_t bytes )

Aligned on 64 bytes. These buffers have the special property that their values remain constrained, allowing us to reuse them without memset()-ing them.

617200{
617201 const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned_init_once;
617202 void* alloc;
617203 void* end;
617204 void* top;
617205
617206 /* We can only start allocating tables after we are done reserving space for objects at the
617207 * start of the workspace */
617208 if(ws->phase < phase) {
617210 return NULL;
617211 }
617212 }
617213 alloc = ws->tableEnd;
617214 end = (BYTE *)alloc + bytes;
617215 top = ws->allocStart;
617216
617217 DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
617218 alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
617219 assert((bytes & (sizeof(U32)-1)) == 0);
617220 ZSTD_cwksp_assert_internal_consistency(ws);
617221 assert(end <= top);
617222 if (end > top) {
617223 DEBUGLOG(4, "cwksp: table alloc failed!");
617224 ws->allocFailed = 1;
617225 return NULL;
617226 }
617227 ws->tableEnd = end;
617228
617229 assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
617230 assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
617231 return alloc;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_object()

MEM_STATIC void * duckdb_zstd::ZSTD_cwksp_reserve_object ( ZSTD_cwksp * ws,
size_t bytes )

Aligned on sizeof(void*). Note : should happen only once, at workspace first initialization

617239{
617240 size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
617241 void* alloc = ws->objectEnd;
617242 void* end = (BYTE*)alloc + roundedBytes;
617243
617244 DEBUGLOG(4,
617245 "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
617246 alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
617247 assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0);
617248 assert(bytes % ZSTD_ALIGNOF(void*) == 0);
617249 ZSTD_cwksp_assert_internal_consistency(ws);
617250 /* we must be in the first phase, no advance is possible */
617251 if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
617252 DEBUGLOG(3, "cwksp: object alloc failed!");
617253 ws->allocFailed = 1;
617254 return NULL;
617255 }
617256 ws->objectEnd = end;
617257 ws->tableEnd = end;
617258 ws->tableValidEnd = end;
617259
617260 return alloc;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_mark_tables_dirty()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_mark_tables_dirty ( ZSTD_cwksp * ws)
617264{
617265 DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
617266
617267 assert(ws->tableValidEnd >= ws->objectEnd);
617268 assert(ws->tableValidEnd <= ws->allocStart);
617269 ws->tableValidEnd = ws->objectEnd;
617270 ZSTD_cwksp_assert_internal_consistency(ws);

◆ ZSTD_cwksp_mark_tables_clean()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_mark_tables_clean ( ZSTD_cwksp * ws)
617273 {
617274 DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
617275 assert(ws->tableValidEnd >= ws->objectEnd);
617276 assert(ws->tableValidEnd <= ws->allocStart);
617277 if (ws->tableValidEnd < ws->tableEnd) {
617278 ws->tableValidEnd = ws->tableEnd;
617279 }
617280 ZSTD_cwksp_assert_internal_consistency(ws);

◆ ZSTD_cwksp_clean_tables()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_clean_tables ( ZSTD_cwksp * ws)

Zero the part of the allocated tables not already marked clean.

617286 {
617287 DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
617288 assert(ws->tableValidEnd >= ws->objectEnd);
617289 assert(ws->tableValidEnd <= ws->allocStart);
617290 if (ws->tableValidEnd < ws->tableEnd) {
617291 ZSTD_memset(ws->tableValidEnd, 0, (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd));
617292 }
617293 ZSTD_cwksp_mark_tables_clean(ws);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_clear_tables()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_clear_tables ( ZSTD_cwksp * ws)

Invalidates table allocations. All other allocations remain valid.

617300 {
617301 DEBUGLOG(4, "cwksp: clearing tables!");
617302
617303 ws->tableEnd = ws->objectEnd;
617304 ZSTD_cwksp_assert_internal_consistency(ws);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_clear()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_clear ( ZSTD_cwksp * ws)

Invalidates all buffer, aligned, and table allocations. Object allocations remain valid.

617311 {
617312 DEBUGLOG(4, "cwksp: clearing!");
617313
617314 ws->tableEnd = ws->objectEnd;
617315 ws->allocStart = ZSTD_cwksp_initialAllocStart(ws);
617316 ws->allocFailed = 0;
617317 if (ws->phase > ZSTD_cwksp_alloc_aligned_init_once) {
617318 ws->phase = ZSTD_cwksp_alloc_aligned_init_once;
617319 }
617320 ZSTD_cwksp_assert_internal_consistency(ws);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_sizeof()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_sizeof ( const ZSTD_cwksp * ws)
617323 {
617324 return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);

◆ ZSTD_cwksp_used()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_used ( const ZSTD_cwksp * ws)
617327 {
617328 return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
617329 + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);

◆ ZSTD_cwksp_init()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_init ( ZSTD_cwksp * ws,
void * start,
size_t size,
ZSTD_cwksp_static_alloc_e isStatic )

The provided workspace takes ownership of the buffer [start, start+size). Any existing values in the workspace are ignored (the previously managed buffer, if present, must be separately freed).

617337 {
617338 DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
617339 assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
617340 ws->workspace = start;
617341 ws->workspaceEnd = (BYTE*)start + size;
617342 ws->objectEnd = ws->workspace;
617343 ws->tableValidEnd = ws->objectEnd;
617344 ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
617345 ws->phase = ZSTD_cwksp_alloc_objects;
617346 ws->isStatic = isStatic;
617347 ZSTD_cwksp_clear(ws);
617348 ws->workspaceOversizedDuration = 0;
617349 ZSTD_cwksp_assert_internal_consistency(ws);
MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp *ws)
Definition duckdb.cpp:617310
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_create()

MEM_STATIC size_t duckdb_zstd::ZSTD_cwksp_create ( ZSTD_cwksp * ws,
size_t size,
ZSTD_customMem customMem )
617352 {
617353 void* workspace = ZSTD_customMalloc(size, customMem);
617354 DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
617355 RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
617356 ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
617357 return 0;

◆ ZSTD_cwksp_free()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_free ( ZSTD_cwksp * ws,
ZSTD_customMem customMem )
617360 {
617361 void *ptr = ws->workspace;
617362 DEBUGLOG(4, "cwksp: freeing workspace");
617363 ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
617364 ZSTD_customFree(ptr, customMem);

◆ ZSTD_cwksp_move()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_move ( ZSTD_cwksp * dst,
ZSTD_cwksp * src )

Moves the management of a workspace from one cwksp to another. The src cwksp is left in an invalid state (src must be re-init()'ed before it's used again).

617371 {
617372 *dst = *src;
617373 ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_cwksp_reserve_failed()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_reserve_failed ( const ZSTD_cwksp * ws)
617376 {
617377 return ws->allocFailed;

◆ ZSTD_cwksp_estimated_space_within_bounds()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_estimated_space_within_bounds ( const ZSTD_cwksp *const ws,
size_t const estimatedSpace )
617388 {
617389 /* We have an alignment space between objects and tables between tables and buffers, so we can have up to twice
617390 * the alignment bytes difference between estimation and actual usage */
617391 return (estimatedSpace - ZSTD_cwksp_slack_space_required()) <= ZSTD_cwksp_used(ws) &&
617392 ZSTD_cwksp_used(ws) <= estimatedSpace;
MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void)
Definition duckdb.cpp:617026

◆ ZSTD_cwksp_check_available()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_check_available ( ZSTD_cwksp * ws,
size_t additionalNeededSpace )
617400 {
617401 return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;

◆ ZSTD_cwksp_check_too_large()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_check_too_large ( ZSTD_cwksp * ws,
size_t additionalNeededSpace )
617404 {
617405 return ZSTD_cwksp_check_available(
617406 ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);

◆ ZSTD_cwksp_check_wasteful()

MEM_STATIC int duckdb_zstd::ZSTD_cwksp_check_wasteful ( ZSTD_cwksp * ws,
size_t additionalNeededSpace )
617409 {
617410 return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
617411 && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;

◆ ZSTD_cwksp_bump_oversized_duration()

MEM_STATIC void duckdb_zstd::ZSTD_cwksp_bump_oversized_duration ( ZSTD_cwksp * ws,
size_t additionalNeededSpace )
617415 {
617416 if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
617417 ws->workspaceOversizedDuration++;
617418 } else {
617419 ws->workspaceOversizedDuration = 0;
617420 }

◆ ZSTDMT_createCCtx_advanced()

ZSTDMT_CCtx * duckdb_zstd::ZSTDMT_createCCtx_advanced ( unsigned nbWorkers,
ZSTD_customMem cMem,
ZSTD_threadPool * pool )
635821{
635822#ifdef ZSTD_MULTITHREAD
635823 return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);

◆ ZSTDMT_freeCCtx()

size_t duckdb_zstd::ZSTDMT_freeCCtx ( ZSTDMT_CCtx * mtctx)
635873{
635874 if (mtctx==NULL) return 0; /* compatible with free on NULL */
635875 if (!mtctx->providedFactory)
635876 POOL_free(mtctx->factory); /* stop and free worker threads */
635877 ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
635878 ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
635879 ZSTDMT_freeBufferPool(mtctx->bufPool);
635880 ZSTDMT_freeCCtxPool(mtctx->cctxPool);
635881 ZSTDMT_freeSeqPool(mtctx->seqPool);

◆ ZSTDMT_sizeof_CCtx()

size_t duckdb_zstd::ZSTDMT_sizeof_CCtx ( ZSTDMT_CCtx * mtctx)
635891{
635892 if (mtctx == NULL) return 0; /* supports sizeof NULL */
635893 return sizeof(*mtctx)
635894 + POOL_sizeof(mtctx->factory)
size_t POOL_sizeof(const POOL_ctx *ctx)
Definition duckdb.cpp:611917

◆ ZSTDMT_nextInputSizeHint()

size_t duckdb_zstd::ZSTDMT_nextInputSizeHint ( const ZSTDMT_CCtx * mtctx)

◆ ZSTDMT_initCStream_internal()

size_t duckdb_zstd::ZSTDMT_initCStream_internal ( ZSTDMT_CCtx * mtctx,
const void * dict,
size_t dictSize,
ZSTD_dictContentType_e dictContentType,
const ZSTD_CDict * cdict,
ZSTD_CCtx_params params,
unsigned long long pledgedSrcSize )

ZSTDMT_initCStream_internal() : Private use only. Init streaming operation. expects params to be valid. must receive dict, or cdict, or none, but not both. mtctx can be freshly constructed or reused from a prior compression. If mtctx is reused, memory allocations from the prior compression may not be freed, even if they are not needed for the current compression.

Returns
: 0, or an error code
636070 : (size_t)1 << ovLog;
636071}
636072
636073/* ====================================== */
636074/* ======= Streaming API ======= */
636075/* ====================================== */
636076
636078 ZSTDMT_CCtx* mtctx,
636079 const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
636080 const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
636081 unsigned long long pledgedSrcSize)
636082{
636083 DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
636084 (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
636085
636086 /* params supposed partially fully validated at this point */
636088 assert(!((dict) && (cdict))); /* either dict or cdict, not both */
636089
636090 /* init */
636091 if (params.nbWorkers != mtctx->params.nbWorkers)
636092 FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, params.nbWorkers) , "");
636093
636094 if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
636095 if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;
636096
636097 DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
636098
636099 if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */
636100 ZSTDMT_waitForAllJobsCompleted(mtctx);
636101 ZSTDMT_releaseAllJobResources(mtctx);
636102 mtctx->allJobsCompleted = 1;
636103 }
636104
636105 mtctx->params = params;
636106 mtctx->frameContentSize = pledgedSrcSize;
636107 if (dict) {
636108 ZSTD_freeCDict(mtctx->cdictLocal);
636109 mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
636110 ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
636111 params.cParams, mtctx->cMem);
636112 mtctx->cdict = mtctx->cdictLocal;
636113 if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
636114 } else {
636115 ZSTD_freeCDict(mtctx->cdictLocal);
636116 mtctx->cdictLocal = NULL;
636117 mtctx->cdict = cdict;
636118 }
636119
636120 mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(&params);
636121 DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
636122 mtctx->targetSectionSize = params.jobSize;
636123 if (mtctx->targetSectionSize == 0) {
636124 mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(&params);
636125 }
636126 assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);
636127
636128 if (params.rsyncable) {
636129 /* Aim for the targetsectionSize as the average job size. */
636130 U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);
636131 U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);
636132 /* We refuse to create jobs < RSYNC_MIN_BLOCK_SIZE bytes, so make sure our
636133 * expected job size is at least 4x larger. */
636134 assert(rsyncBits >= RSYNC_MIN_BLOCK_LOG + 2);
636135 DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
636136 mtctx->rsync.hash = 0;
636137 mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
636138 mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
636139 }
636140 if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */
636141 DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
636142 DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
636143 ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
636144 {
636145 /* If ldm is enabled we need windowSize space. */
636146 size_t const windowSize = mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable ? (1U << mtctx->params.cParams.windowLog) : 0;
636147 /* Two buffers of slack, plus extra space for the overlap
636148 * This is the minimum slack that LDM works with. One extra because
636149 * flush might waste up to targetSectionSize-1 bytes. Another extra
636150 * for the overlap (if > 0), then one to fill which doesn't overlap
636151 * with the LDM window.
636152 */
636153 size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
636154 size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
636155 /* Compute the total size, and always have enough slack */
636156 size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
636157 size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
636158 size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
636159 if (mtctx->roundBuff.capacity < capacity) {
636160 if (mtctx->roundBuff.buffer)
636161 ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
636162 mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);
636163 if (mtctx->roundBuff.buffer == NULL) {
636164 mtctx->roundBuff.capacity = 0;
636165 return ERROR(memory_allocation);
636166 }
636167 mtctx->roundBuff.capacity = capacity;
636168 }
636169 }
636170 DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
636171 mtctx->roundBuff.pos = 0;
636172 mtctx->inBuff.buffer = g_nullBuffer;
636173 mtctx->inBuff.filled = 0;
636174 mtctx->inBuff.prefix = kNullRange;
636175 mtctx->doneJobID = 0;
636176 mtctx->nextJobID = 0;
636177 mtctx->frameEnded = 0;
636178 mtctx->allJobsCompleted = 0;
MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
Definition duckdb.cpp:618416
size_t ZSTDMT_initCStream_internal(ZSTDMT_CCtx *mtctx, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, const ZSTD_CDict *cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
Definition duckdb.cpp:636070

◆ ZSTDMT_compressStream_generic()

size_t duckdb_zstd::ZSTDMT_compressStream_generic ( ZSTDMT_CCtx * mtctx,
ZSTD_outBuffer * output,
ZSTD_inBuffer * input,
ZSTD_EndDirective endOp )

ZSTDMT_compressStream_generic() : Combines ZSTDMT_compressStream() with optional ZSTDMT_flushStream() or ZSTDMT_endStream() depending on flush directive.

Returns
: minimum amount of data still to be flushed 0 if fully flushed or an error code note : needs to be init using any ZSTD_initCStream*() variant

ZSTDMT_compressStream_generic() : internal use only - exposed to be invoked from zstd_compress.c assumption : output and input are valid (pos <= size)

Returns
: minimum amount of data remaining to flush, 0 if none
636660{
636661 unsigned forwardInputProgress = 0;
636662 DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
636663 (U32)endOp, (U32)(input->size - input->pos));
636664 assert(output->pos <= output->size);
636665 assert(input->pos <= input->size);
636666
636667 if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
636668 /* current frame being ended. Only flush/end are allowed */
636669 return ERROR(stage_wrong);
636670 }
636671
636672 /* fill input buffer */
636673 if ( (!mtctx->jobReady)
636674 && (input->size > input->pos) ) { /* support NULL input */
636675 if (mtctx->inBuff.buffer.start == NULL) {
636676 assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
636677 if (!ZSTDMT_tryGetInputRange(mtctx)) {
636678 /* It is only possible for this operation to fail if there are
636679 * still compression jobs ongoing.
636680 */
636681 DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
636682 assert(mtctx->doneJobID != mtctx->nextJobID);
636683 } else
636684 DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
636685 }
636686 if (mtctx->inBuff.buffer.start != NULL) {
636687 syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
636688 if (syncPoint.flush && endOp == ZSTD_e_continue) {
636689 endOp = ZSTD_e_flush;
636690 }
636691 assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
636692 DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
636693 (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
636694 ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
636695 input->pos += syncPoint.toLoad;
636696 mtctx->inBuff.filled += syncPoint.toLoad;
636697 forwardInputProgress = syncPoint.toLoad>0;
636698 }
636699 }
636700 if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {
636701 /* Can't end yet because the input is not fully consumed.
636702 * We are in one of these cases:
636703 * - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.
636704 * - We filled the input buffer: flush this job but don't end the frame.
636705 * - We hit a synchronization point: flush this job but don't end the frame.
636706 */
636707 assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);
636708 endOp = ZSTD_e_flush;
636709 }
636710
636711 if ( (mtctx->jobReady)
636712 || (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */
636713 || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */
636714 || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */
636715 size_t const jobSize = mtctx->inBuff.filled;
636716 assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
636717 FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");
636718 }
636719
static syncPoint_t findSynchronizationPoint(ZSTDMT_CCtx const *mtctx, ZSTD_inBuffer const input)
Definition duckdb.cpp:636542
static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx *mtctx)
Definition duckdb.cpp:636476
Definition duckdb.cpp:636530

◆ ZSTDMT_toFlushNow()

size_t duckdb_zstd::ZSTDMT_toFlushNow ( ZSTDMT_CCtx * mtctx)

ZSTDMT_toFlushNow() Tell how many bytes are ready to be flushed immediately. Probe the oldest active job (not yet entirely flushed) and check its output buffer. If return 0, it means there is no active job, or, it means oldest job is still active, but everything produced has been flushed so far, therefore flushing is limited by speed of oldest job.

635976{
635977 size_t toFlush;
635978 unsigned const jobID = mtctx->doneJobID;
635979 assert(jobID <= mtctx->nextJobID);
635980 if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */
635981
635982 /* look into oldest non-fully-flushed job */
635983 { unsigned const wJobID = jobID & mtctx->jobIDMask;
635984 ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
635985 ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
635986 { size_t const cResult = jobPtr->cSize;
635987 size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
635988 size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
635989 assert(flushed <= produced);
635990 assert(jobPtr->consumed <= jobPtr->src.size);
635991 toFlush = produced - flushed;
635992 /* if toFlush==0, nothing is available to flush.
635993 * However, jobID is expected to still be active:
635994 * if jobID was already completed and fully flushed,
635995 * ZSTDMT_flushProduced() should have already moved onto next job.
635996 * Therefore, some input has not yet been consumed. */
635997 if (toFlush==0) {
635998 assert(jobPtr->consumed < jobPtr->src.size);
Definition duckdb.cpp:635489

◆ ZSTDMT_updateCParams_whileCompressing()

void duckdb_zstd::ZSTDMT_updateCParams_whileCompressing ( ZSTDMT_CCtx * mtctx,
const ZSTD_CCtx_params * cctxParams )

ZSTDMT_updateCParams_whileCompressing() : Updates only a selected set of compression parameters, to remain compatible with current frame. New parameters will be applied to next compression job.

ZSTDMT_updateCParams_whileCompressing() : Updates a selected set of compression parameters, remaining compatible with currently active frame. New parameters will be applied to next compression job.

635925{
635926 U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */
635927 int const compressionLevel = cctxParams->compressionLevel;
635928 DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",

◆ ZSTDMT_getFrameProgression()

ZSTD_frameProgression duckdb_zstd::ZSTDMT_getFrameProgression ( ZSTDMT_CCtx * mtctx)

ZSTDMT_getFrameProgression(): tells how much data has been consumed (input) and produced (output) for current frame. able to count progression inside worker threads.

635942{
635944 DEBUGLOG(5, "ZSTDMT_getFrameProgression");
635945 fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
635946 fps.consumed = mtctx->consumed;
635947 fps.produced = fps.flushed = mtctx->produced;
635948 fps.currentJobID = mtctx->nextJobID;
635949 fps.nbActiveWorkers = 0;
635950 { unsigned jobNb;
635951 unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
635952 DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
635953 mtctx->doneJobID, lastJobNb, mtctx->jobReady);
635954 for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
635955 unsigned const wJobID = jobNb & mtctx->jobIDMask;
635956 ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
635957 ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
635958 { size_t const cResult = jobPtr->cSize;
635959 size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
635960 size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
635961 assert(flushed <= produced);
635962 fps.ingested += jobPtr->src.size;
635963 fps.consumed += jobPtr->consumed;
635964 fps.produced += produced;
635965 fps.flushed += flushed;
Definition duckdb.cpp:409758

◆ ZSTD_buildBlockEntropyStats()

size_t duckdb_zstd::ZSTD_buildBlockEntropyStats ( const seqStore_t * seqStorePtr,
const ZSTD_entropyCTables_t * prevEntropy,
ZSTD_entropyCTables_t * nextEntropy,
const ZSTD_CCtx_params * cctxParams,
ZSTD_entropyCTablesMetadata_t * entropyMetadata,
void * workspace,
size_t wkspSize )

ZSTD_buildBlockEntropyStats() : Builds entropy for the block.

Returns
: 0 on success or error code

ZSTD_buildBlockEntropyStats() : Builds entropy for the block. Requires workspace size ENTROPY_WORKSPACE_SIZE

Returns
: 0 on success, or an error code Note : also employed in superblock
623441{
623442 size_t const litSize = (size_t)(seqStorePtr->lit - seqStorePtr->litStart);
623443 int const huf_useOptDepth = (cctxParams->cParams.strategy >= HUF_OPTIMAL_DEPTH_THRESHOLD);
623444 int const hufFlags = huf_useOptDepth ? HUF_flags_optimalDepth : 0;
623445
623446 entropyMetadata->hufMetadata.hufDesSize =
623447 ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,
623448 &prevEntropy->huf, &nextEntropy->huf,
623449 &entropyMetadata->hufMetadata,
623450 ZSTD_literalsCompressionIsDisabled(cctxParams),
623451 workspace, wkspSize, hufFlags);
623452
623453 FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");
623454 entropyMetadata->fseMetadata.fseTablesSize =
static size_t ZSTD_buildBlockEntropyStats_sequences(const seqStore_t *seqStorePtr, const ZSTD_fseCTables_t *prevEntropy, ZSTD_fseCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, ZSTD_fseCTablesMetadata_t *fseMetadata, void *workspace, size_t wkspSize)
Definition duckdb.cpp:623388
static size_t ZSTD_buildBlockEntropyStats_literals(void *const src, size_t srcSize, const ZSTD_hufCTables_t *prevHuf, ZSTD_hufCTables_t *nextHuf, ZSTD_hufCTablesMetadata_t *hufMetadata, const int literalsCompressionIsDisabled, void *workspace, size_t wkspSize, int hufFlags)
Definition duckdb.cpp:623262
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_selectBlockCompressor()

ZSTD_blockCompressor duckdb_zstd::ZSTD_selectBlockCompressor ( ZSTD_strategy strat,
ZSTD_paramSwitch_e rowMatchfinderMode,
ZSTD_dictMode_e dictMode )
622736{
622737 static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
622738 { ZSTD_compressBlock_fast /* default for 0 */,
622739 ZSTD_compressBlock_fast,
622740 ZSTD_COMPRESSBLOCK_DOUBLEFAST,
622741 ZSTD_COMPRESSBLOCK_GREEDY,
622742 ZSTD_COMPRESSBLOCK_LAZY,
622743 ZSTD_COMPRESSBLOCK_LAZY2,
622744 ZSTD_COMPRESSBLOCK_BTLAZY2,
622745 ZSTD_COMPRESSBLOCK_BTOPT,
622746 ZSTD_COMPRESSBLOCK_BTULTRA,
622747 ZSTD_COMPRESSBLOCK_BTULTRA2
622748 },
622749 { ZSTD_compressBlock_fast_extDict /* default for 0 */,
622750 ZSTD_compressBlock_fast_extDict,
622751 ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT,
622752 ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT,
622753 ZSTD_COMPRESSBLOCK_LAZY_EXTDICT,
622754 ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT,
622755 ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT,
622756 ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT,
622757 ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT,
622758 ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT
622759 },
622760 { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,
622761 ZSTD_compressBlock_fast_dictMatchState,
622762 ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE,
622763 ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE,
622764 ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE,
622765 ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE,
622766 ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE,
622767 ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE,
622768 ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE,
622769 ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE
622770 },
622771 { NULL /* default for 0 */,
622772 NULL,
622773 NULL,
622774 ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH,
622775 ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH,
622776 ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH,
622777 NULL,
622778 NULL,
622779 NULL,
622780 NULL }
622781 };
622782 ZSTD_blockCompressor selectedCompressor;
622783 ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
622784
622785 assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
622786 DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
622787 if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {
622788 static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = {
622789 {
622790 ZSTD_COMPRESSBLOCK_GREEDY_ROW,
622791 ZSTD_COMPRESSBLOCK_LAZY_ROW,
622792 ZSTD_COMPRESSBLOCK_LAZY2_ROW
622793 },
622794 {
622795 ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW,
622796 ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW,
622797 ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW
622798 },
622799 {
622800 ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW,
622801 ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW,
622802 ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW
622803 },
622804 {
622805 ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW,
622806 ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW,
622807 ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW
622808 }
622809 };
622810 DEBUGLOG(4, "Selecting a row-based matchfinder");
622811 assert(useRowMatchFinder != ZSTD_ps_auto);

◆ ZSTD_LLcode()

MEM_STATIC U32 duckdb_zstd::ZSTD_LLcode ( U32 litLength)
618039{
618040 static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
618041 8, 9, 10, 11, 12, 13, 14, 15,
618042 16, 16, 17, 17, 18, 18, 19, 19,
618043 20, 20, 20, 20, 21, 21, 21, 21,

◆ ZSTD_MLcode()

MEM_STATIC U32 duckdb_zstd::ZSTD_MLcode ( U32 mlBase)
618049 : LL_Code[litLength];
618050}
618051
618052/* ZSTD_MLcode() :
618053 * note : mlBase = matchLength - MINMATCH;
618054 * because it's the format it's stored in seqStore->sequences */
618055MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
618056{
618057 static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
618058 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
618059 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
618060 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,

◆ ZSTD_cParam_withinBounds()

MEM_STATIC int duckdb_zstd::ZSTD_cParam_withinBounds ( ZSTD_cParameter cParam,
int value )
618066 : ML_Code[mlBase];
618067}
618068
618069/* ZSTD_cParam_withinBounds:
618070 * @return 1 if value is within cParam bounds,
618071 * 0 otherwise */
618072MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)

◆ ZSTD_noCompressBlock()

MEM_STATIC size_t duckdb_zstd::ZSTD_noCompressBlock ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 lastBlock )
618086{
618087 U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);

◆ ZSTD_rleCompressBlock()

MEM_STATIC size_t duckdb_zstd::ZSTD_rleCompressBlock ( void * dst,
size_t dstCapacity,
BYTE src,
size_t srcSize,
U32 lastBlock )
618098{

◆ ZSTD_minGain()

MEM_STATIC size_t duckdb_zstd::ZSTD_minGain ( size_t srcSize,
ZSTD_strategy strat )

◆ ZSTD_literalsCompressionIsDisabled()

MEM_STATIC int duckdb_zstd::ZSTD_literalsCompressionIsDisabled ( const ZSTD_CCtx_params * cctxParams)
618113{
618114 U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
618115 ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
618116 assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
618117 return (srcSize >> minlog) + 2;
618118}
618119
618120MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)
618121{
618122 switch (cctxParams->literalCompressionMode) {
618123 case ZSTD_ps_enable:
618124 return 0;
618125 case ZSTD_ps_disable:
618126 return 1;

◆ ZSTD_safecopyLiterals()

void duckdb_zstd::ZSTD_safecopyLiterals ( BYTE * op,
BYTE const * ip,
BYTE const *const iend,
BYTE const * ilimit_w )
static

ZSTD_safecopyLiterals() : memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w. Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single large copies.

618142{
618143 assert(iend > ilimit_w);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_storeSeq()

HINT_INLINE UNUSED_ATTR void duckdb_zstd::ZSTD_storeSeq ( seqStore_t * seqStorePtr,
size_t litLength,
const BYTE * literals,
const BYTE * litLimit,
U32 offBase,
size_t matchLength )

ZSTD_storeSeq() : Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t. @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE(). @matchLength : must be >= MINMATCH Allowed to over-read literals up to litLimit.

618174{
618175 BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;
618176 BYTE const* const litEnd = literals + litLength;
618177#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
618178 static const BYTE* g_start = NULL;
618179 if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
618180 { U32 const pos = (U32)((const BYTE*)literals - g_start);
618181 DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
618182 pos, (U32)litLength, (U32)matchLength, (U32)offBase);
618183 }
618184#endif
618185 assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
618186 /* copy Literals */
618187 assert(seqStorePtr->maxNbLit <= 128 KB);
618188 assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
618189 assert(literals + litLength <= litLimit);
618190 if (litEnd <= litLimit_w) {
618191 /* Common case we can use wildcopy.
618192 * First copy 16 bytes, because literals are likely short.
618193 */
618194 ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);
618195 ZSTD_copy16(seqStorePtr->lit, literals);
618196 if (litLength > 16) {
618197 ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);
618198 }
618199 } else {
618200 ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);
618201 }
618202 seqStorePtr->lit += litLength;
618203
618204 /* literal Length */
618205 if (litLength>0xFFFF) {
618206 assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
618207 seqStorePtr->longLengthType = ZSTD_llt_literalLength;
618208 seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
618209 }
618210 seqStorePtr->sequences[0].litLength = (U16)litLength;
618211
618212 /* match offset */
618213 seqStorePtr->sequences[0].offBase = offBase;
618214
618215 /* match Length */
618216 assert(matchLength >= MINMATCH);
618217 { size_t const mlBase = matchLength - MINMATCH;
618218 if (mlBase>0xFFFF) {
618219 assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
618220 seqStorePtr->longLengthType = ZSTD_llt_matchLength;
static void ZSTD_safecopyLiterals(BYTE *op, BYTE const *ip, BYTE const *const iend, BYTE const *ilimit_w)
Definition duckdb.cpp:618134
MEM_STATIC FORCE_INLINE_ATTR void ZSTD_wildcopy(void *dst, const void *src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
Definition duckdb.cpp:614134
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_updateRep()

MEM_STATIC void duckdb_zstd::ZSTD_updateRep ( U32 rep[ZSTD_REP_NUM],
U32 const offBase,
U32 const ll0 )
618235{
618236 if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */
618237 rep[2] = rep[1];
618238 rep[1] = rep[0];
618239 rep[0] = OFFBASE_TO_OFFSET(offBase);
618240 } else { /* repcode */
618241 U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;
618242 if (repCode > 0) { /* note : if repCode==0, no change */
618243 U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
618244 rep[2] = (repCode >= 2) ? rep[1] : rep[2];

◆ ZSTD_newRep()

MEM_STATIC repcodes_t duckdb_zstd::ZSTD_newRep ( U32 const rep[ZSTD_REP_NUM],
U32 const offBase,
U32 const ll0 )
618253 {
618254 U32 rep[3];
618255} repcodes_t;
618256
618257MEM_STATIC repcodes_t

◆ ZSTD_count()

MEM_STATIC size_t duckdb_zstd::ZSTD_count ( const BYTE * pIn,
const BYTE * pMatch,
const BYTE *const pInLimit )
618271{
618272 const BYTE* const pStart = pIn;
618273 const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
618274
618275 if (pIn < pInLoopLimit) {
618276 { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
618277 if (diff) return ZSTD_NbCommonBytes(diff); }
618278 pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
618279 while (pIn < pInLoopLimit) {
618280 size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
618281 if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
618282 pIn += ZSTD_NbCommonBytes(diff);

◆ ZSTD_count_2segments()

MEM_STATIC size_t duckdb_zstd::ZSTD_count_2segments ( const BYTE * ip,
const BYTE * match,
const BYTE * iEnd,
const BYTE * mEnd,
const BYTE * iStart )

ZSTD_count_2segments() : can count match length with ip & match in 2 different segments. convention : on reaching mEnd, match count continue starting from iStart

618298{
618299 const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
618300 size_t const matchLength = ZSTD_count(ip, match, vEnd);
618301 if (match + matchLength != mEnd) return matchLength;
Here is the caller graph for this function:

◆ ZSTD_hash3()

U32 duckdb_zstd::ZSTD_hash3 ( U32 u,
U32 h,
U32 s )
static

◆ ZSTD_hash3Ptr()

MEM_STATIC size_t duckdb_zstd::ZSTD_hash3Ptr ( const void * ptr,
U32 h )

◆ ZSTD_hash3PtrS()

MEM_STATIC size_t duckdb_zstd::ZSTD_hash3PtrS ( const void * ptr,
U32 h,
U32 s )

◆ ZSTD_hash4()

U32 duckdb_zstd::ZSTD_hash4 ( U32 u,
U32 h,
U32 s )
static

◆ ZSTD_hash4Ptr()

size_t duckdb_zstd::ZSTD_hash4Ptr ( const void * ptr,
U32 h )
static

◆ ZSTD_hash4PtrS()

size_t duckdb_zstd::ZSTD_hash4PtrS ( const void * ptr,
U32 h,
U32 s )
static
618315{ assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }

◆ ZSTD_hash5()

size_t duckdb_zstd::ZSTD_hash5 ( U64 u,
U32 h,
U64 s )
static

◆ ZSTD_hash5Ptr()

size_t duckdb_zstd::ZSTD_hash5Ptr ( const void * p,
U32 h )
static

◆ ZSTD_hash5PtrS()

size_t duckdb_zstd::ZSTD_hash5PtrS ( const void * p,
U32 h,
U64 s )
static
618320{ assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }

◆ ZSTD_hash6()

size_t duckdb_zstd::ZSTD_hash6 ( U64 u,
U32 h,
U64 s )
static

◆ ZSTD_hash6Ptr()

size_t duckdb_zstd::ZSTD_hash6Ptr ( const void * p,
U32 h )
static

◆ ZSTD_hash6PtrS()

size_t duckdb_zstd::ZSTD_hash6PtrS ( const void * p,
U32 h,
U64 s )
static
618325{ assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }

◆ ZSTD_hash7()

size_t duckdb_zstd::ZSTD_hash7 ( U64 u,
U32 h,
U64 s )
static

◆ ZSTD_hash7Ptr()

size_t duckdb_zstd::ZSTD_hash7Ptr ( const void * p,
U32 h )
static

◆ ZSTD_hash7PtrS()

size_t duckdb_zstd::ZSTD_hash7PtrS ( const void * p,
U32 h,
U64 s )
static
618330{ assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }

◆ ZSTD_hash8()

size_t duckdb_zstd::ZSTD_hash8 ( U64 u,
U32 h,
U64 s )
static

◆ ZSTD_hash8Ptr()

size_t duckdb_zstd::ZSTD_hash8Ptr ( const void * p,
U32 h )
static

◆ ZSTD_hash8PtrS()

size_t duckdb_zstd::ZSTD_hash8PtrS ( const void * p,
U32 h,
U64 s )
static
618335{ assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }

◆ ZSTD_hashPtr()

MEM_STATIC FORCE_INLINE_ATTR size_t duckdb_zstd::ZSTD_hashPtr ( const void * p,
U32 hBits,
U32 mls )
618340 { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }
618341static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }
618342static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }
618343
618344
618345MEM_STATIC FORCE_INLINE_ATTR
618346size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
618347{
618348 /* Although some of these hashes do support hBits up to 64, some do not.
618349 * To be on the safe side, always avoid hBits > 32. */
618350 assert(hBits <= 32);
618351
618352 switch(mls)
618353 {
618354 default:

◆ ZSTD_hashPtrSalted()

MEM_STATIC FORCE_INLINE_ATTR size_t duckdb_zstd::ZSTD_hashPtrSalted ( const void * p,
U32 hBits,
U32 mls,
const U64 hashSalt )
618357 : return ZSTD_hash6Ptr(p, hBits);
618358 case 7: return ZSTD_hash7Ptr(p, hBits);
618359 case 8: return ZSTD_hash8Ptr(p, hBits);
618360 }
618361}
618362
618363MEM_STATIC FORCE_INLINE_ATTR
618364size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {
618365 /* Although some of these hashes do support hBits up to 64, some do not.
618366 * To be on the safe side, always avoid hBits > 32. */
618367 assert(hBits <= 32);
618368
618369 switch(mls)
618370 {
618371 default:

◆ ZSTD_ipow()

U64 duckdb_zstd::ZSTD_ipow ( U64 base,
U64 exponent )
static

ZSTD_ipow() : Return base^exponent.

618385{
618386 U64 power = 1;
Quat< T > power(const Quat< T > &q, const Quat< T > &p, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT)
Here is the caller graph for this function:

◆ ZSTD_rollingHash_append()

U64 duckdb_zstd::ZSTD_rollingHash_append ( U64 hash,
void const * buf,
size_t size )
static

ZSTD_rollingHash_append() : Add the buffer to the hash value.

618401{
618402 BYTE const* istart = (BYTE const*)buf;
Here is the caller graph for this function:

◆ ZSTD_rollingHash_compute()

MEM_STATIC U64 duckdb_zstd::ZSTD_rollingHash_compute ( void const * buf,
size_t size )

ZSTD_rollingHash_compute() : Compute the rolling hash value of the buffer.

Here is the caller graph for this function:

◆ ZSTD_rollingHash_primePower()

MEM_STATIC U64 duckdb_zstd::ZSTD_rollingHash_primePower ( U32 length)

ZSTD_rollingHash_primePower() : Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash over a window of length bytes.

Here is the call graph for this function:

◆ ZSTD_rollingHash_rotate()

MEM_STATIC U64 duckdb_zstd::ZSTD_rollingHash_rotate ( U64 hash,
BYTE toRemove,
BYTE toAdd,
U64 primePower )

ZSTD_rollingHash_rotate() : Rotate the rolling hash by one byte.

618424{
618425 return ZSTD_ipow(prime8bytes, length - 1);
618426}
618427
static U64 ZSTD_ipow(U64 base, U64 exponent)
Definition duckdb.cpp:618377
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_window_clear()

MEM_STATIC void duckdb_zstd::ZSTD_window_clear ( ZSTD_window_t * window)

ZSTD_window_clear(): Clears the window containing the history by simply setting it to empty.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_window_isEmpty()

MEM_STATIC U32 duckdb_zstd::ZSTD_window_isEmpty ( ZSTD_window_t const window)

◆ ZSTD_window_hasExtDict()

MEM_STATIC U32 duckdb_zstd::ZSTD_window_hasExtDict ( ZSTD_window_t const window)

ZSTD_window_hasExtDict(): Returns non-zero if the window has a non-empty extDict.

◆ ZSTD_matchState_dictMode()

MEM_STATIC ZSTD_dictMode_e duckdb_zstd::ZSTD_matchState_dictMode ( const ZSTD_matchState_t * ms)

ZSTD_matchState_dictMode(): Inspects the provided matchState and figures out what dictMode should be passed to the compressor.

◆ ZSTD_window_canOverflowCorrect()

MEM_STATIC U32 duckdb_zstd::ZSTD_window_canOverflowCorrect ( ZSTD_window_t const window,
U32 cycleLog,
U32 maxDist,
U32 loadedDictEnd,
void const * src )

ZSTD_window_canOverflowCorrect(): Returns non-zero if the indices are large enough for overflow correction to work correctly without impacting compression ratio.

618517{
618518 U32 const cycleSize = 1u << cycleLog;
618519 U32 const curr = (U32)((BYTE const*)src - window.base);
618520 U32 const minIndexToOverflowCorrect = cycleSize
618521 + MAX(maxDist, cycleSize)
618522 + ZSTD_WINDOW_START_INDEX;
618523
618524 /* Adjust the min index to backoff the overflow correction frequency,
618525 * so we don't waste too much CPU in overflow correction. If this
618526 * computation overflows we don't really care, we just need to make
618527 * sure it is at least minIndexToOverflowCorrect.
618528 */
618529 U32 const adjustment = window.nbOverflowCorrections + 1;
618530 U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,
618531 minIndexToOverflowCorrect);
618532 U32 const indexLargeEnough = curr > adjustedIndex;
618533
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_window_needOverflowCorrection()

MEM_STATIC U32 duckdb_zstd::ZSTD_window_needOverflowCorrection ( ZSTD_window_t const window,
U32 cycleLog,
U32 maxDist,
U32 loadedDictEnd,
void const * src,
void const * srcEnd )

ZSTD_window_needOverflowCorrection(): Returns non-zero if the indices are getting too large and need overflow protection.

618553{
618554 U32 const curr = (U32)((BYTE const*)srcEnd - window.base);

◆ ZSTD_window_correctOverflow()

MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_window_correctOverflow ( ZSTD_window_t * window,
U32 cycleLog,
U32 maxDist,
void const * src )

ZSTD_window_correctOverflow(): Reduces the indices to protect from index overflow. Returns the correction made to the indices, which must be applied to every stored index.

The least significant cycleLog bits of the indices must remain the same, which may be 0. Every index up to maxDist in the past must be valid.

618576{
618577 /* preemptive overflow correction:
618578 * 1. correction is large enough:
618579 * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
618580 * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
618581 *
618582 * current - newCurrent
618583 * > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
618584 * > (3<<29) - (1<<chainLog)
618585 * > (3<<29) - (1<<30) (NOTE: chainLog <= 30)
618586 * > 1<<29
618587 *
618588 * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
618589 * After correction, current is less than (1<<chainLog + 1<<windowLog).
618590 * In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
618591 * In 32-bit mode we are safe, because (chainLog <= 29), so
618592 * ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
618593 * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
618594 * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
618595 */
618596 U32 const cycleSize = 1u << cycleLog;
618597 U32 const cycleMask = cycleSize - 1;
618598 U32 const curr = (U32)((BYTE const*)src - window->base);
618599 U32 const currentCycle = curr & cycleMask;
618600 /* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */
618601 U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX
618602 ? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)
618603 : 0;
618604 U32 const newCurrent = currentCycle
618605 + currentCycleCorrection
618606 + MAX(maxDist, cycleSize);
618607 U32 const correction = curr - newCurrent;
618608 /* maxDist must be a power of two so that:
618609 * (newCurrent & cycleMask) == (curr & cycleMask)
618610 * This is required to not corrupt the chains / binary tree.
618611 */
618612 assert((maxDist & (maxDist - 1)) == 0);
618613 assert((curr & cycleMask) == (newCurrent & cycleMask));
618614 assert(curr > newCurrent);
618615 if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
618616 /* Loose bound, should be around 1<<29 (see above) */
618617 assert(correction > 1<<28);
618618 }
618619
618620 window->base += correction;
618621 window->dictBase += correction;
618622 if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {
618623 window->lowLimit = ZSTD_WINDOW_START_INDEX;
618624 } else {
618625 window->lowLimit -= correction;
618626 }
618627 if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {
618628 window->dictLimit = ZSTD_WINDOW_START_INDEX;
618629 } else {
618630 window->dictLimit -= correction;
618631 }
618632
618633 /* Ensure we can still reference the full window. */
618634 assert(newCurrent >= maxDist);
618635 assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
618636 /* Ensure that lowLimit and dictLimit didn't underflow. */
618637 assert(window->lowLimit <= newCurrent);
618638 assert(window->dictLimit <= newCurrent);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_window_enforceMaxDist()

MEM_STATIC void duckdb_zstd::ZSTD_window_enforceMaxDist ( ZSTD_window_t * window,
const void * blockEnd,
U32 maxDist,
U32 * loadedDictEndPtr,
const ZSTD_matchState_t ** dictMatchStatePtr )

ZSTD_window_enforceMaxDist(): Updates lowLimit so that: (srcEnd - base) - lowLimit == maxDist + loadedDictEnd

It ensures index is valid as long as index >= lowLimit. This must be called before a block compression call.

loadedDictEnd is only defined if a dictionary is in use for current compression. As the name implies, loadedDictEnd represents the index at end of dictionary. The value lies within context's referential, it can be directly compared to blockEndIdx.

If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0. If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit. This is because dictionaries are allowed to be referenced fully as long as the last byte of the dictionary is in the window. Once input has progressed beyond window size, dictionary cannot be referenced anymore.

In normal dict mode, the dictionary lies between lowLimit and dictLimit. In dictMatchState mode, lowLimit and dictLimit are the same, and the dictionary is below them. forceWindow and dictMatchState are therefore incompatible.

618676{
618677 U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
618678 U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
618679 DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
618680 (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
618681
618682 /* - When there is no dictionary : loadedDictEnd == 0.
618683 In which case, the test (blockEndIdx > maxDist) is merely to avoid
618684 overflowing next operation `newLowLimit = blockEndIdx - maxDist`.
618685 - When there is a standard dictionary :
618686 Index referential is copied from the dictionary,
618687 which means it starts from 0.
618688 In which case, loadedDictEnd == dictSize,
618689 and it makes sense to compare `blockEndIdx > maxDist + dictSize`
618690 since `blockEndIdx` also starts from zero.
618691 - When there is an attached dictionary :
618692 loadedDictEnd is expressed within the referential of the context,
618693 so it can be directly compared against blockEndIdx.
618694 */
618695 if (blockEndIdx > maxDist + loadedDictEnd) {
618696 U32 const newLowLimit = blockEndIdx - maxDist;
618697 if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
618698 if (window->dictLimit < window->lowLimit) {
618699 DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
618700 (unsigned)window->dictLimit, (unsigned)window->lowLimit);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_checkDictValidity()

MEM_STATIC void duckdb_zstd::ZSTD_checkDictValidity ( const ZSTD_window_t * window,
const void * blockEnd,
U32 maxDist,
U32 * loadedDictEndPtr,
const ZSTD_matchState_t ** dictMatchStatePtr )
618721{
618722 assert(loadedDictEndPtr != NULL);
618723 assert(dictMatchStatePtr != NULL);
618724 { U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
618725 U32 const loadedDictEnd = *loadedDictEndPtr;
618726 DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
618727 (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
618728 assert(blockEndIdx >= loadedDictEnd);
618729
618730 if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {
618731 /* On reaching window size, dictionaries are invalidated.
618732 * For simplification, if window size is reached anywhere within next block,
618733 * the dictionary is invalidated for the full block.
618734 *
618735 * We also have to invalidate the dictionary if ZSTD_window_update() has detected
618736 * non-contiguous segments, which means that loadedDictEnd != window->dictLimit.
618737 * loadedDictEnd may be 0, if forceWindow is true, but in that case we never use
618738 * dictMatchState, so setting it to NULL is not a problem.
618739 */
618740 DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");

◆ ZSTD_window_init()

MEM_STATIC void duckdb_zstd::ZSTD_window_init ( ZSTD_window_t * window)
618743 {
618744 if (*loadedDictEndPtr != 0) {
618745 DEBUGLOG(6, "dictionary considered valid for current block");
618746 } } }
618747}
618748
618749MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
618750 ZSTD_memset(window, 0, sizeof(*window));
618751 window->base = (BYTE const*)" ";
Definition duckdb.cpp:617713

◆ ZSTD_window_update()

MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_window_update ( ZSTD_window_t * window,
void const * src,
size_t srcSize,
int forceNonContiguous )

ZSTD_window_update(): Updates the window by appending [src, src + srcSize) to the window. If it is not contiguous, the current prefix becomes the extDict, and we forget about the extDict. Handles overlap of the prefix and extDict. Returns non-zero if the segment is contiguous.

618772{
618773 BYTE const* const ip = (BYTE const*)src;
618774 U32 contiguous = 1;
618775 DEBUGLOG(5, "ZSTD_window_update");
618776 if (srcSize == 0)
618777 return contiguous;
618778 assert(window->base != NULL);
618779 assert(window->dictBase != NULL);
618780 /* Check if blocks follow each other */
618781 if (src != window->nextSrc || forceNonContiguous) {
618782 /* not contiguous */
618783 size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
618784 DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
618785 window->lowLimit = window->dictLimit;
618786 assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */
618787 window->dictLimit = (U32)distanceFromBase;
618788 window->dictBase = window->base;
618789 window->base = ip - distanceFromBase;
618790 /* ms->nextToUpdate = window->dictLimit; */
618791 if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */
618792 contiguous = 0;
618793 }
618794 window->nextSrc = ip + srcSize;
618795 /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
618796 if ( (ip+srcSize > window->dictBase + window->lowLimit)
618797 & (ip < window->dictBase + window->dictLimit)) {
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getLowestMatchIndex()

MEM_STATIC U32 duckdb_zstd::ZSTD_getLowestMatchIndex ( const ZSTD_matchState_t * ms,
U32 curr,
unsigned windowLog )

Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.

618810{
618811 U32 const maxDistance = 1U << windowLog;
618812 U32 const lowestValid = ms->window.lowLimit;
618813 U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
618814 U32 const isDictionary = (ms->loadedDictEnd != 0);
Here is the caller graph for this function:

◆ ZSTD_getLowestPrefixIndex()

MEM_STATIC U32 duckdb_zstd::ZSTD_getLowestPrefixIndex ( const ZSTD_matchState_t * ms,
U32 curr,
unsigned windowLog )

Returns the lowest allowed match index in the prefix.

618819 : withinWindow;
618820 return matchLowest;
618821}
618822
618826MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)
618827{
618828 U32 const maxDistance = 1U << windowLog;
618829 U32 const lowestValid = ms->window.dictLimit;
618830 U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t *ms, U32 curr, unsigned windowLog)
Definition duckdb.cpp:618819
Here is the caller graph for this function:

◆ ZSTD_writeTaggedIndex()

MEM_STATIC void duckdb_zstd::ZSTD_writeTaggedIndex ( U32 *const hashTable,
size_t hashAndTag,
U32 index )

◆ ZSTD_comparePackedTags()

MEM_STATIC int duckdb_zstd::ZSTD_comparePackedTags ( size_t packedTag1,
size_t packedTag2 )

◆ ZSTD_loadCEntropy()

size_t duckdb_zstd::ZSTD_loadCEntropy ( ZSTD_compressedBlockState_t * bs,
void * workspace,
const void *const dict,
size_t dictSize )
624629 {
624630 return FSE_repeat_check;
624631 }
624632 }
624633 return FSE_repeat_valid;
624634}
624635
624636size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
624637 const void* const dict, size_t dictSize)
624638{
624639 short offcodeNCount[MaxOff+1];
624640 unsigned offcodeMaxValue = MaxOff;
624641 const BYTE* dictPtr = (const BYTE*)dict; /* skip magic num and dict ID */
624642 const BYTE* const dictEnd = dictPtr + dictSize;
624643 dictPtr += 8;
624644 bs->entropy.huf.repeatMode = HUF_repeat_check;
624645
624646 { unsigned maxSymbolValue = 255;
624647 unsigned hasZeroWeights = 1;
624648 size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
624649 dictEnd-dictPtr, &hasZeroWeights);
624650
624651 /* We only set the loaded table as valid if it contains all non-zero
624652 * weights. Otherwise, we set it to check */
624653 if (!hasZeroWeights && maxSymbolValue == 255)
624654 bs->entropy.huf.repeatMode = HUF_repeat_valid;
624655
624656 RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
624657 dictPtr += hufHeaderSize;
624658 }
624659
624660 { unsigned offcodeLog;
624661 size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
624662 RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
624663 RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
624664 /* fill all offset symbols to avoid garbage at end of table */
624665 RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
624666 bs->entropy.fse.offcodeCTable,
624667 offcodeNCount, MaxOff, offcodeLog,
624668 workspace, HUF_WORKSPACE_SIZE)),
624669 dictionary_corrupted, "");
624670 /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
624671 dictPtr += offcodeHeaderSize;
624672 }
624673
624674 { short matchlengthNCount[MaxML+1];
624675 unsigned matchlengthMaxValue = MaxML, matchlengthLog;
624676 size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
624677 RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
624678 RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
624679 RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
624680 bs->entropy.fse.matchlengthCTable,
624681 matchlengthNCount, matchlengthMaxValue, matchlengthLog,
624682 workspace, HUF_WORKSPACE_SIZE)),
624683 dictionary_corrupted, "");
624684 bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
624685 dictPtr += matchlengthHeaderSize;
624686 }
624687
624688 { short litlengthNCount[MaxLL+1];
624689 unsigned litlengthMaxValue = MaxLL, litlengthLog;
624690 size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
624691 RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
624692 RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
624693 RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
624694 bs->entropy.fse.litlengthCTable,
624695 litlengthNCount, litlengthMaxValue, litlengthLog,
624696 workspace, HUF_WORKSPACE_SIZE)),
624697 dictionary_corrupted, "");
624698 bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
624699 dictPtr += litlengthHeaderSize;
624700 }
624701
624702 RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
624703 bs->rep[0] = MEM_readLE32(dictPtr+0);
624704 bs->rep[1] = MEM_readLE32(dictPtr+4);
624705 bs->rep[2] = MEM_readLE32(dictPtr+8);
624706 dictPtr += 12;
624707
624708 { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
624709 U32 offcodeMax = MaxOff;
624710 if (dictContentSize <= ((U32)-1) - 128 KB) {
624711 U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
624712 offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
624713 }
624714 /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
624715 bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
624716
624717 /* All repCodes must be <= dictContentSize and != 0 */
624718 { U32 u;
size_t HUF_readCTable(HUF_CElt *CTable, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, unsigned *hasZeroWeights)
Definition duckdb.cpp:615560
Definition duckdb.cpp:617708

◆ ZSTD_reset_compressedBlockState()

void duckdb_zstd::ZSTD_reset_compressedBlockState ( ZSTD_compressedBlockState_t * bs)
621622{
621623 int i;

◆ ZSTD_getCParamsFromCCtxParams()

ZSTD_compressionParameters duckdb_zstd::ZSTD_getCParamsFromCCtxParams ( const ZSTD_CCtx_params * CCtxParams,
U64 srcSizeHint,
size_t dictSize,
ZSTD_cParamMode_e mode )
621343{
621345 if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
621346 srcSizeHint = CCtxParams->srcSizeHint;
621347 }

◆ ZSTD_initCStream_internal()

size_t duckdb_zstd::ZSTD_initCStream_internal ( ZSTD_CStream * zcs,
const void * dict,
size_t dictSize,
const ZSTD_CDict * cdict,
const ZSTD_CCtx_params * params,
unsigned long long pledgedSrcSize )

ZSTD_initCStream_internal() : Private use only. Init streaming operation. expects params to be valid. must receive dict, or cdict, or none, but not both.

Returns
: 0, or an error code

ZSTD_initCStream_internal() : Note : for lib/compress only. Used by zstdmt_compress.c. Assumption 1 : params are valid Assumption 2 : either dict, or cdict, is defined, not both

625563{
625564 DEBUGLOG(4, "ZSTD_initCStream_internal");
625565 FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
625566 FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
625568 zcs->requestedParams = *params;
625569 assert(!((dict) && (cdict))); /* either dict or cdict, not both */
625570 if (dict) {
ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx *cctx, unsigned long long pledgedSrcSize)
Definition duckdb.cpp:620927

◆ ZSTD_resetSeqStore()

void duckdb_zstd::ZSTD_resetSeqStore ( seqStore_t * ssPtr)
622822{
622823 ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);
622824 seqStorePtr->lit += lastLLSize;
622825}

◆ ZSTD_getCParamsFromCDict()

ZSTD_compressionParameters duckdb_zstd::ZSTD_getCParamsFromCDict ( const ZSTD_CDict * cdict)

ZSTD_getCParamsFromCDict() : as the name implies

◆ ZSTD_compressBegin_advanced_internal()

size_t duckdb_zstd::ZSTD_compressBegin_advanced_internal ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
ZSTD_dictContentType_e dictContentType,
ZSTD_dictTableLoadMethod_e dtlm,
const ZSTD_CDict * cdict,
const ZSTD_CCtx_params * params,
unsigned long long pledgedSrcSize )
624867{
624868 DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
624869 /* compression parameters verification and optimization */

◆ ZSTD_compress_advanced_internal()

size_t duckdb_zstd::ZSTD_compress_advanced_internal ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const void * dict,
size_t dictSize,
const ZSTD_CCtx_params * params )

◆ ZSTD_writeLastEmptyBlock()

size_t duckdb_zstd::ZSTD_writeLastEmptyBlock ( void * dst,
size_t dstCapacity )
624349{

◆ ZSTD_referenceExternalSequences()

void duckdb_zstd::ZSTD_referenceExternalSequences ( ZSTD_CCtx * cctx,
rawSeq * seq,
size_t nbSeq )
624352 { U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1); /* 0 size */
624353 MEM_writeLE24(dst, cBlockHeader24);
624354 return ZSTD_blockHeaderSize;
624355 }
624356}
624357
624358void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
624359{
624360 assert(cctx->stage == ZSTDcs_init);
Definition duckdb.cpp:617652

◆ ZSTD_cycleLog()

U32 duckdb_zstd::ZSTD_cycleLog ( U32 hashLog,
ZSTD_strategy strat )

ZSTD_cycleLog() : condition for correct operation : hashLog > 1

Here is the caller graph for this function:

◆ ZSTD_CCtx_trace()

void duckdb_zstd::ZSTD_CCtx_trace ( ZSTD_CCtx * cctx,
size_t extraCSize )

ZSTD_CCtx_trace() : Trace the end of a compression call.

624959{
624960#if ZSTD_TRACE
624961 if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
624962 int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
624963 ZSTD_Trace trace;
624964 ZSTD_memset(&trace, 0, sizeof(trace));
624965 trace.version = ZSTD_VERSION_NUMBER;
624966 trace.streaming = streaming;
624967 trace.dictionaryID = cctx->dictID;
624968 trace.dictionarySize = cctx->dictContentSize;
624969 trace.uncompressedSize = cctx->consumedSrcSize;
624970 trace.compressedSize = cctx->producedCSize + extraCSize;
624971 trace.params = &cctx->appliedParams;
624972 trace.cctx = cctx;
624973 ZSTD_trace_compress_end(cctx->traceCtx, &trace);
Scalar trace(InputArray mtx)

◆ ZSTD_copySequencesToSeqStoreExplicitBlockDelim()

size_t duckdb_zstd::ZSTD_copySequencesToSeqStoreExplicitBlockDelim ( ZSTD_CCtx * cctx,
ZSTD_sequencePosition * seqPos,
const ZSTD_Sequence *const inSeqs,
size_t inSeqsSize,
const void * src,
size_t blockSize,
ZSTD_paramSwitch_e externalRepSearch )
626199 {
626200 offBase = REPCODE3_TO_OFFBASE;
626201 }
626202 return offBase;
626203}
626204
626205size_t
626206ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
626207 ZSTD_sequencePosition* seqPos,
626208 const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
626209 const void* src, size_t blockSize,
626210 ZSTD_paramSwitch_e externalRepSearch)
626211{
626212 U32 idx = seqPos->idx;
626213 U32 const startIdx = idx;
626214 BYTE const* ip = (BYTE const*)(src);
626215 const BYTE* const iend = ip + blockSize;
626216 repcodes_t updatedRepcodes;
626217 U32 dictSize;
626218
626219 DEBUGLOG(5, "ZSTD_copySequencesToSeqStoreExplicitBlockDelim (blockSize = %zu)", blockSize);
626220
626221 if (cctx->cdict) {
626222 dictSize = (U32)cctx->cdict->dictContentSize;
626223 } else if (cctx->prefixDict.dict) {
626224 dictSize = (U32)cctx->prefixDict.dictSize;
626225 } else {
626226 dictSize = 0;
626227 }
626228 ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
626229 for (; idx < inSeqsSize && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) {
626230 U32 const litLength = inSeqs[idx].litLength;
626231 U32 const matchLength = inSeqs[idx].matchLength;
626232 U32 offBase;
626233
626234 if (externalRepSearch == ZSTD_ps_disable) {
626235 offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset);
626236 } else {
626237 U32 const ll0 = (litLength == 0);
626238 offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
626239 ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
626240 }
626241
626242 DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
626243 if (cctx->appliedParams.validateSequences) {
626244 seqPos->posInSrc += litLength + matchLength;
626245 FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
626246 cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
626247 "Sequence validation failed");
626248 }
626249 RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
626250 "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
626251 ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
626252 ip += matchLength + litLength;
626253 }
626254
626255 /* If we skipped repcode search while parsing, we need to update repcodes now */
626256 assert(externalRepSearch != ZSTD_ps_auto);
626257 assert(idx >= startIdx);
626258 if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) {
626259 U32* const rep = updatedRepcodes.rep;
626260 U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */
626261
626262 if (lastSeqIdx >= startIdx + 2) {
626263 rep[2] = inSeqs[lastSeqIdx - 2].offset;
626264 rep[1] = inSeqs[lastSeqIdx - 1].offset;
626265 rep[0] = inSeqs[lastSeqIdx].offset;
626266 } else if (lastSeqIdx == startIdx + 1) {
626267 rep[2] = rep[0];
626268 rep[1] = inSeqs[lastSeqIdx - 1].offset;
626269 rep[0] = inSeqs[lastSeqIdx].offset;
626270 } else {
626271 assert(lastSeqIdx == startIdx);
626272 rep[2] = rep[1];
626273 rep[1] = rep[0];
626274 rep[0] = inSeqs[lastSeqIdx].offset;
626275 }
626276 }
626277
626278 ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
626279
626280 if (inSeqs[idx].litLength) {
626281 DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
626282 ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
HINT_INLINE UNUSED_ATTR void ZSTD_storeSeq(seqStore_t *seqStorePtr, size_t litLength, const BYTE *literals, const BYTE *litLimit, U32 offBase, size_t matchLength)
Definition duckdb.cpp:618163
Definition duckdb.cpp:408409
Definition duckdb.cpp:617667

◆ ZSTD_copySequencesToSeqStoreNoBlockDelim()

size_t duckdb_zstd::ZSTD_copySequencesToSeqStoreNoBlockDelim ( ZSTD_CCtx * cctx,
ZSTD_sequencePosition * seqPos,
const ZSTD_Sequence *const inSeqs,
size_t inSeqsSize,
const void * src,
size_t blockSize,
ZSTD_paramSwitch_e externalRepSearch )
626295{
626296 U32 idx = seqPos->idx;
626297 U32 startPosInSequence = seqPos->posInSequence;
626298 U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
626299 size_t dictSize;
626300 BYTE const* ip = (BYTE const*)(src);
626301 BYTE const* iend = ip + blockSize; /* May be adjusted if we decide to process fewer than blockSize bytes */
626302 repcodes_t updatedRepcodes;
626303 U32 bytesAdjustment = 0;
626304 U32 finalMatchSplit = 0;
626305
626306 /* TODO(embg) support fast parsing mode in noBlockDelim mode */
626307 (void)externalRepSearch;
626308
626309 if (cctx->cdict) {
626310 dictSize = cctx->cdict->dictContentSize;
626311 } else if (cctx->prefixDict.dict) {
626312 dictSize = cctx->prefixDict.dictSize;
626313 } else {
626314 dictSize = 0;
626315 }
626316 DEBUGLOG(5, "ZSTD_copySequencesToSeqStoreNoBlockDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
626317 DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
626318 ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
626319 while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
626320 const ZSTD_Sequence currSeq = inSeqs[idx];
626321 U32 litLength = currSeq.litLength;
626322 U32 matchLength = currSeq.matchLength;
626323 U32 const rawOffset = currSeq.offset;
626324 U32 offBase;
626325
626326 /* Modify the sequence depending on where endPosInSequence lies */
626327 if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
626328 if (startPosInSequence >= litLength) {
626329 startPosInSequence -= litLength;
626330 litLength = 0;
626331 matchLength -= startPosInSequence;
626332 } else {
626333 litLength -= startPosInSequence;
626334 }
626335 /* Move to the next sequence */
626336 endPosInSequence -= currSeq.litLength + currSeq.matchLength;
626337 startPosInSequence = 0;
626338 } else {
626339 /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
626340 does not reach the end of the match. So, we have to split the sequence */
626341 DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
626342 currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
626343 if (endPosInSequence > litLength) {
626344 U32 firstHalfMatchLength;
626345 litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
626346 firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
626347 if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
626348 /* Only ever split the match if it is larger than the block size */
626349 U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
626350 if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
626351 /* Move the endPosInSequence backward so that it creates match of minMatch length */
626352 endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
626353 bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
626354 firstHalfMatchLength -= bytesAdjustment;
626355 }
626356 matchLength = firstHalfMatchLength;
626357 /* Flag that we split the last match - after storing the sequence, exit the loop,
626358 but keep the value of endPosInSequence */
626359 finalMatchSplit = 1;
626360 } else {
626361 /* Move the position in sequence backwards so that we don't split match, and break to store
626362 * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
626363 * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
626364 * would cause the first half of the match to be too small
626365 */
626366 bytesAdjustment = endPosInSequence - currSeq.litLength;
626367 endPosInSequence = currSeq.litLength;
626368 break;
626369 }
626370 } else {
626371 /* This sequence ends inside the literals, break to store the last literals */
626372 break;
626373 }
626374 }
626375 /* Check if this offset can be represented with a repcode */
626376 { U32 const ll0 = (litLength == 0);
626377 offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0);
626378 ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
626379 }
626380
626381 if (cctx->appliedParams.validateSequences) {
626382 seqPos->posInSrc += litLength + matchLength;
626383 FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
626384 cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
626385 "Sequence validation failed");
626386 }
626387 DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
626388 RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
626389 "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
626390 ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
626391 ip += matchLength + litLength;
626392 if (!finalMatchSplit)
626393 idx++; /* Next Sequence */
626394 }
626395 DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
626396 assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
626397 seqPos->idx = idx;
626398 seqPos->posInSequence = endPosInSequence;
626399 ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
626400
626401 iend -= bytesAdjustment;
626402 if (ip != iend) {
626403 /* Store any last literals */
626404 U32 lastLLSize = (U32)(iend - ip);
626405 assert(ip <= iend);
unsigned minMatch
Definition duckdb.cpp:408451

◆ ZSTD_hasExtSeqProd()

MEM_STATIC int duckdb_zstd::ZSTD_hasExtSeqProd ( const ZSTD_CCtx_params * params)

◆ ZSTD_compressBegin_usingCDict_deprecated()

size_t duckdb_zstd::ZSTD_compressBegin_usingCDict_deprecated ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict )
625440{
625441 return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
625442}
625443

◆ ZSTD_compressContinue_public()

size_t duckdb_zstd::ZSTD_compressContinue_public ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )

◆ ZSTD_compressEnd_public()

size_t duckdb_zstd::ZSTD_compressEnd_public ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
624985{
624986 size_t endResult;
624987 size_t const cSize = ZSTD_compressContinue_internal(cctx,
624988 dst, dstCapacity, src, srcSize,
624989 1 /* frame mode */, 1 /* last chunk */);
624990 FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
624991 endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
624992 FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
624993 assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
624994 if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
624995 ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
624996 DEBUGLOG(4, "end of frame : controlling src size");
624998 cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
624999 srcSize_wrong,
static size_t ZSTD_writeEpilogue(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity)
Definition duckdb.cpp:624912
int contentSizeFlag
Definition duckdb.cpp:408457

◆ ZSTD_compressBlock_deprecated()

size_t duckdb_zstd::ZSTD_compressBlock_deprecated ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
624456{
624457 return ZSTD_getBlockSize_deprecated(cctx);
624458}
624459
624460/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
624461size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)

◆ ZSTD_selectEncodingType()

symbolEncodingType_e duckdb_zstd::ZSTD_selectEncodingType ( FSE_repeat * repeatMode,
unsigned const * count,
unsigned const max,
size_t const mostFrequent,
size_t nbSeq,
unsigned const FSELog,
FSE_CTable const * prevCTable,
short const * defaultNorm,
U32 defaultNormLog,
ZSTD_defaultPolicy_e const isDefaultAllowed,
ZSTD_strategy const strategy )
627425{
627426 ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
627427 if (mostFrequent == nbSeq) {
627428 *repeatMode = FSE_repeat_none;
627429 if (isDefaultAllowed && nbSeq <= 2) {
627430 /* Prefer set_basic over set_rle when there are 2 or fewer symbols,
627431 * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
627432 * If basic encoding isn't possible, always choose RLE.
627433 */
627434 DEBUGLOG(5, "Selected set_basic");
627435 return set_basic;
627436 }
627437 DEBUGLOG(5, "Selected set_rle");
627438 return set_rle;
627439 }
627440 if (strategy < ZSTD_lazy) {
627441 if (isDefaultAllowed) {
627442 size_t const staticFse_nbSeq_max = 1000;
627443 size_t const mult = 10 - strategy;
627444 size_t const baseLog = 3;
627445 size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */
627446 assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */
627447 assert(mult <= 9 && mult >= 7);
627448 if ( (*repeatMode == FSE_repeat_valid)
627449 && (nbSeq < staticFse_nbSeq_max) ) {
627450 DEBUGLOG(5, "Selected set_repeat");
627451 return set_repeat;
627452 }
627453 if ( (nbSeq < dynamicFse_nbSeq_min)
627454 || (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {
627455 DEBUGLOG(5, "Selected set_basic");
627456 /* The format allows default tables to be repeated, but it isn't useful.
627457 * When using simple heuristics to select encoding type, we don't want
627458 * to confuse these tables with dictionaries. When running more careful
627459 * analysis, we don't need to waste time checking both repeating tables
627460 * and default tables.
627461 */
627462 *repeatMode = FSE_repeat_none;
627463 return set_basic;
627464 }
627465 }
627466 } else {
627467 size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);
627468 size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);
627469 size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);
627470 size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);
627471
627472 if (isDefaultAllowed) {
627473 assert(!ZSTD_isError(basicCost));
627474 assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));
627475 }
627476 assert(!ZSTD_isError(NCountCost));
627477 assert(compressedCost < ERROR(maxCode));
627478 DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",
627479 (unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost);
627480 if (basicCost <= repeatCost && basicCost <= compressedCost) {
627481 DEBUGLOG(5, "Selected set_basic");
627482 assert(isDefaultAllowed);
627483 *repeatMode = FSE_repeat_none;
627484 return set_basic;
627485 }
627486 if (repeatCost <= compressedCost) {
627487 DEBUGLOG(5, "Selected set_repeat");
627488 assert(!ZSTD_isError(repeatCost));
627489 return set_repeat;
static size_t ZSTD_NCountCost(unsigned const *count, unsigned const max, size_t const nbSeq, unsigned const FSELog)
Definition duckdb.cpp:627324
size_t ZSTD_crossEntropyCost(short const *norm, unsigned accuracyLog, unsigned const *count, unsigned const max)
Definition duckdb.cpp:627393
size_t ZSTD_fseBitCost(FSE_CTable const *ctable, unsigned const *count, unsigned const max)
Definition duckdb.cpp:627358
static size_t ZSTD_entropyCost(unsigned const *count, unsigned const max, size_t const total)
Definition duckdb.cpp:627338

◆ ZSTD_buildCTable()

size_t duckdb_zstd::ZSTD_buildCTable ( void * dst,
size_t dstCapacity,
FSE_CTable * nextCTable,
U32 FSELog,
symbolEncodingType_e type,
unsigned * count,
U32 max,
const BYTE * codeTable,
size_t nbSeq,
const S16 * defaultNorm,
U32 defaultNormLog,
U32 defaultMax,
const FSE_CTable * prevCTable,
size_t prevCTableSize,
void * entropyWorkspace,
size_t entropyWorkspaceSize )
627498 {
627499 S16 norm[MaxSeq + 1];
627500 U32 wksp[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(MaxSeq, MaxFSELog)];
627501} ZSTD_BuildCTableWksp;
627502
627503size_t
627504ZSTD_buildCTable(void* dst, size_t dstCapacity,
627505 FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
627506 unsigned* count, U32 max,
627507 const BYTE* codeTable, size_t nbSeq,
627508 const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
627509 const FSE_CTable* prevCTable, size_t prevCTableSize,
627510 void* entropyWorkspace, size_t entropyWorkspaceSize)
627511{
627512 BYTE* op = (BYTE*)dst;
627513 const BYTE* const oend = op + dstCapacity;
627514 DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);
627515
627516 switch (type) {
627517 case set_rle:
627518 FORWARD_IF_ERROR(FSE_buildCTable_rle(nextCTable, (BYTE)max), "");
627519 RETURN_ERROR_IF(dstCapacity==0, dstSize_tooSmall, "not enough space");
627520 *op = codeTable[0];
627521 return 1;
627522 case set_repeat:
627523 ZSTD_memcpy(nextCTable, prevCTable, prevCTableSize);
627524 return 0;
627525 case set_basic:
627526 FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, entropyWorkspace, entropyWorkspaceSize), ""); /* note : could be pre-calculated */
627527 return 0;
627528 case set_compressed: {
627529 ZSTD_BuildCTableWksp* wksp = (ZSTD_BuildCTableWksp*)entropyWorkspace;
627530 size_t nbSeq_1 = nbSeq;
627531 const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
627532 if (count[codeTable[nbSeq-1]] > 1) {
627533 count[codeTable[nbSeq-1]]--;
627534 nbSeq_1--;
627535 }
627536 assert(nbSeq_1 > 1);
627537 assert(entropyWorkspaceSize >= sizeof(ZSTD_BuildCTableWksp));
627538 (void)entropyWorkspaceSize;
627539 FORWARD_IF_ERROR(FSE_normalizeCount(wksp->norm, tableLog, count, nbSeq_1, max, ZSTD_useLowProbCount(nbSeq_1)), "FSE_normalizeCount failed");
627540 assert(oend >= op);
627541 { size_t const NCountSize = FSE_writeNCount(op, (size_t)(oend - op), wksp->norm, max, tableLog); /* overflow protected */
627542 FORWARD_IF_ERROR(NCountSize, "FSE_writeNCount failed");
unsigned FSE_CTable
Definition duckdb.cpp:609171
static unsigned ZSTD_useLowProbCount(size_t const nbSeq)
Definition duckdb.cpp:627311
size_t FSE_buildCTable_rle(FSE_CTable *ct, unsigned char symbolValue)
Definition duckdb.cpp:614966
Definition duckdb.cpp:627491

◆ ZSTD_encodeSequences()

size_t duckdb_zstd::ZSTD_encodeSequences ( void * dst,
size_t dstCapacity,
FSE_CTable const * CTable_MatchLength,
BYTE const * mlCodeTable,
FSE_CTable const * CTable_OffsetBits,
BYTE const * ofCodeTable,
FSE_CTable const * CTable_LitLength,
BYTE const * llCodeTable,
seqDef const * sequences,
size_t nbSeq,
int longOffsets,
int bmi2 )
627686{
627687 DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
627688#if DYNAMIC_BMI2
627689 if (bmi2) {
627690 return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
627691 CTable_MatchLength, mlCodeTable,
627692 CTable_OffsetBits, ofCodeTable,
627693 CTable_LitLength, llCodeTable,
627694 sequences, nbSeq, longOffsets);
627695 }
627696#endif

◆ ZSTD_fseBitCost()

size_t duckdb_zstd::ZSTD_fseBitCost ( FSE_CTable const * ctable,
unsigned const * count,
unsigned const max )

Returns the cost in bits of encoding the distribution in count using ctable. Returns an error if ctable cannot represent all the symbols in count.

627369{
627370 unsigned const kAccuracyLog = 8;
627371 size_t cost = 0;
627372 unsigned s;
627373 FSE_CState_t cstate;
627374 FSE_initCState(&cstate, ctable);
627375 if (ZSTD_getFSEMaxSymbolValue(ctable) < max) {
627376 DEBUGLOG(5, "Repeat FSE_CTable has maxSymbolValue %u < %u",
627377 ZSTD_getFSEMaxSymbolValue(ctable), max);
627378 return ERROR(GENERIC);
627379 }
627380 for (s = 0; s <= max; ++s) {
627381 unsigned const tableLog = cstate.stateLog;
627382 unsigned const badCost = (tableLog + 1) << kAccuracyLog;
627383 unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog);
627384 if (count[s] == 0)
627385 continue;
627386 if (bitCost >= badCost) {

◆ ZSTD_crossEntropyCost()

size_t duckdb_zstd::ZSTD_crossEntropyCost ( short const * norm,
unsigned accuracyLog,
unsigned const * count,
unsigned const max )

Returns the cost in bits of encoding the distribution in count using the table described by norm. The max symbol support by norm is assumed >= max. norm must be valid for every symbol with non-zero probability in count.

627402{
627403 unsigned const shift = 8 - accuracyLog;
627404 size_t cost = 0;
627405 unsigned s;
627406 assert(accuracyLog <= 8);
627407 for (s = 0; s <= max; ++s) {
627408 unsigned const normAcc = (norm[s] != -1) ? (unsigned)norm[s] : 1;

◆ ZSTD_noCompressLiterals()

size_t duckdb_zstd::ZSTD_noCompressLiterals ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
627053{
627054 BYTE* const ostart = (BYTE*)dst;
627055 U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
627056
627057 DEBUGLOG(5, "ZSTD_noCompressLiterals: srcSize=%zu, dstCapacity=%zu", srcSize, dstCapacity);
627058
627059 RETURN_ERROR_IF(srcSize + flSize > dstCapacity, dstSize_tooSmall, "");
627060
627061 switch(flSize)
627062 {
627063 case 1: /* 2 - 1 - 5 */
627064 ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3));
627065 break;
627066 case 2: /* 2 - 2 - 12 */
627067 MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4)));
627068 break;
627069 case 3: /* 2 - 2 - 20 */
627070 MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4)));
627071 break;
627072 default: /* not necessary : flSize is {1,2,3} */

◆ ZSTD_compressRleLiteralsBlock()

size_t duckdb_zstd::ZSTD_compressRleLiteralsBlock ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
627087 {
627088 if (((const BYTE*)src)[p] != b) return 0;
627089 }
627090 return 1;
627091 }
627092}
627093
627094size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
627095{
627096 BYTE* const ostart = (BYTE*)dst;
627097 U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
627098
627099 assert(dstCapacity >= 4); (void)dstCapacity;
627100 assert(allBytesIdentical(src, srcSize));
627101
627102 switch(flSize)
627103 {
627104 case 1: /* 2 - 1 - 5 */
627105 ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3));
627106 break;
627107 case 2: /* 2 - 2 - 12 */
627108 MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4)));
627109 break;
627110 case 3: /* 2 - 2 - 20 */
627111 MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4)));
627112 break;
627113 default: /* not necessary : flSize is {1,2,3} */

◆ ZSTD_compressLiterals()

size_t duckdb_zstd::ZSTD_compressLiterals ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
void * entropyWorkspace,
size_t entropyWorkspaceSize,
const ZSTD_hufCTables_t * prevHuf,
ZSTD_hufCTables_t * nextHuf,
ZSTD_strategy strategy,
int disableLiteralCompression,
int suspectUncompressible,
int bmi2 )
627135 { int const shift = MIN(9-(int)strategy, 3);
627136 size_t const mintc = (huf_repeat == HUF_repeat_valid) ? 6 : (size_t)8 << shift;
627137 DEBUGLOG(7, "minLiteralsToCompress = %zu", mintc);
627138 return mintc;
627139 }
627140}
627141
627142size_t ZSTD_compressLiterals (
627143 void* dst, size_t dstCapacity,
627144 const void* src, size_t srcSize,
627145 void* entropyWorkspace, size_t entropyWorkspaceSize,
627146 const ZSTD_hufCTables_t* prevHuf,
627147 ZSTD_hufCTables_t* nextHuf,
627148 ZSTD_strategy strategy,
627149 int disableLiteralCompression,
627150 int suspectUncompressible,
627151 int bmi2)
627152{
627153 size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
627154 BYTE* const ostart = (BYTE*)dst;
627155 U32 singleStream = srcSize < 256;
627156 symbolEncodingType_e hType = set_compressed;
627157 size_t cLitSize;
627158
627159 DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i, srcSize=%u, dstCapacity=%zu)",
627160 disableLiteralCompression, (U32)srcSize, dstCapacity);
627161
627162 DEBUGLOG(6, "Completed literals listing (%zu bytes)", showHexa(src, srcSize));
627163
627164 /* Prepare nextEntropy assuming reusing the existing table */
627165 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
627166
627167 if (disableLiteralCompression)
627168 return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
627169
627170 /* if too small, don't even attempt compression (speed opt) */
627171 if (srcSize < ZSTD_minLiteralsToCompress(strategy, prevHuf->repeatMode))
627172 return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
627173
627174 RETURN_ERROR_IF(dstCapacity < lhSize+1, dstSize_tooSmall, "not enough space for compression");
627175 { HUF_repeat repeat = prevHuf->repeatMode;
627176 int const flags = 0
627177 | (bmi2 ? HUF_flags_bmi2 : 0)
627178 | (strategy < ZSTD_lazy && srcSize <= 1024 ? HUF_flags_preferRepeat : 0)
627179 | (strategy >= HUF_OPTIMAL_DEPTH_THRESHOLD ? HUF_flags_optimalDepth : 0)
627180 | (suspectUncompressible ? HUF_flags_suspectUncompressible : 0);
627181
627182 typedef size_t (*huf_compress_f)(void*, size_t, const void*, size_t, unsigned, unsigned, void*, size_t, HUF_CElt*, HUF_repeat*, int);
627183 huf_compress_f huf_compress;
627184 if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1;
627185 huf_compress = singleStream ? HUF_compress1X_repeat : HUF_compress4X_repeat;
627186 cLitSize = huf_compress(ostart+lhSize, dstCapacity-lhSize,
627187 src, srcSize,
627188 HUF_SYMBOLVALUE_MAX, LitHufLog,
627189 entropyWorkspace, entropyWorkspaceSize,
627190 (HUF_CElt*)nextHuf->CTable,
627191 &repeat, flags);
627192 DEBUGLOG(5, "%zu literals compressed into %zu bytes (before header)", srcSize, cLitSize);
627193 if (repeat != HUF_repeat_none) {
627194 /* reused the existing table */
627195 DEBUGLOG(5, "reusing statistics from previous huffman block");
627196 hType = set_repeat;
627197 }
627198 }
627199
627200 { size_t const minGain = ZSTD_minGain(srcSize, strategy);
627201 if ((cLitSize==0) || (cLitSize >= srcSize - minGain) || ERR_isError(cLitSize)) {
627202 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
627203 return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
627204 } }
627205 if (cLitSize==1) {
627206 /* A return value of 1 signals that the alphabet consists of a single symbol.
627207 * However, in some rare circumstances, it could be the compressed size (a single byte).
627208 * For that outcome to have a chance to happen, it's necessary that `srcSize < 8`.
627209 * (it's also necessary to not generate statistics).
627210 * Therefore, in such a case, actively check that all bytes are identical. */
627211 if ((srcSize >= 8) || allBytesIdentical(src, srcSize)) {
627212 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
627213 return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
627214 } }
627215
627216 if (hType == set_compressed) {
627217 /* using a newly constructed table */
627218 nextHuf->repeatMode = HUF_repeat_check;
627219 }
627220
627221 /* Build header */
627222 switch(lhSize)
627223 {
627224 case 3: /* 2 - 2 - 10 - 10 */
627225 if (!singleStream) assert(srcSize >= MIN_LITERALS_FOR_4_STREAMS);
627226 { U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14);
627227 MEM_writeLE24(ostart, lhc);
627228 break;
627229 }
627230 case 4: /* 2 - 2 - 14 - 14 */
627231 assert(srcSize >= MIN_LITERALS_FOR_4_STREAMS);
627232 { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18);
627233 MEM_writeLE32(ostart, lhc);
627234 break;
627235 }
627236 case 5: /* 2 - 2 - 18 - 18 */
627237 assert(srcSize >= MIN_LITERALS_FOR_4_STREAMS);
627238 { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22);
627239 MEM_writeLE32(ostart, lhc);
627240 ostart[4] = (BYTE)(cLitSize >> 10);
627241 break;
size_t HUF_compress4X_repeat(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int flags)
Definition duckdb.cpp:616721
HUF_repeat
Definition duckdb.cpp:610511
size_t HUF_compress1X_repeat(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int flags)
Definition duckdb.cpp:616704
Definition duckdb.cpp:617580

◆ ZSTD_fillHashTable()

void duckdb_zstd::ZSTD_fillHashTable ( ZSTD_matchState_t * ms,
void const * end,
ZSTD_dictTableLoadMethod_e dtlm,
ZSTD_tableFillPurpose_e tfp )
629280 {
629281 size_t const hash = ZSTD_hashPtr(ip + p, hBits, mls);
629282 if (hashTable[hash] == 0) { /* not yet filled */
629283 hashTable[hash] = curr + p;
629284 } } } }
629285}
629286
629287void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
629288 const void* const end,
629289 ZSTD_dictTableLoadMethod_e dtlm,
629290 ZSTD_tableFillPurpose_e tfp)
Definition duckdb.cpp:617731

◆ ZSTD_compressBlock_fast()

size_t duckdb_zstd::ZSTD_compressBlock_fast ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
629630{
629631 U32 const mls = ms->cParams.minMatch;
629632 assert(ms->dictMatchState == NULL);
629633 if (ms->cParams.targetLength > 1) {
629634 switch(mls)
629635 {
629636 default: /* includes case 3 */
629637 case 4 :
629638 return ZSTD_compressBlock_fast_noDict_4_1(ms, seqStore, rep, src, srcSize);
629639 case 5 :
629640 return ZSTD_compressBlock_fast_noDict_5_1(ms, seqStore, rep, src, srcSize);
629641 case 6 :
629642 return ZSTD_compressBlock_fast_noDict_6_1(ms, seqStore, rep, src, srcSize);
629643 case 7 :
629644 return ZSTD_compressBlock_fast_noDict_7_1(ms, seqStore, rep, src, srcSize);
629645 }
629646 } else {
629647 switch(mls)
629648 {
629649 default: /* includes case 3 */
629650 case 4 :
629651 return ZSTD_compressBlock_fast_noDict_4_0(ms, seqStore, rep, src, srcSize);
629652 case 5 :
629653 return ZSTD_compressBlock_fast_noDict_5_0(ms, seqStore, rep, src, srcSize);
629654 case 6 :
unsigned targetLength
Definition duckdb.cpp:408452

◆ ZSTD_compressBlock_fast_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_fast_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
629872{
629873 U32 const mls = ms->cParams.minMatch;
629874 assert(ms->dictMatchState != NULL);
629875 switch(mls)
629876 {
629877 default: /* includes case 3 */
629878 case 4 :
629879 return ZSTD_compressBlock_fast_dictMatchState_4_0(ms, seqStore, rep, src, srcSize);
629880 case 5 :

◆ ZSTD_compressBlock_fast_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_fast_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
630153{
630154 U32 const mls = ms->cParams.minMatch;
630155 assert(ms->dictMatchState == NULL);
630156 switch(mls)
630157 {
630158 default: /* includes case 3 */
630159 case 4 :
630160 return ZSTD_compressBlock_fast_extDict_4_0(ms, seqStore, rep, src, srcSize);
630161 case 5 :

◆ ZSTD_fillDoubleHashTable()

void duckdb_zstd::ZSTD_fillDoubleHashTable ( ZSTD_matchState_t * ms,
void const * end,
ZSTD_dictTableLoadMethod_e dtlm,
ZSTD_tableFillPurpose_e tfp )

◆ ZSTD_compressBlock_doubleFast()

size_t duckdb_zstd::ZSTD_compressBlock_doubleFast ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
628980{
628981 const U32 mls = ms->cParams.minMatch;
628982 switch(mls)
628983 {
628984 default: /* includes case 3 */
628985 case 4 :
628986 return ZSTD_compressBlock_doubleFast_noDict_4(ms, seqStore, rep, src, srcSize);
628987 case 5 :

◆ ZSTD_compressBlock_doubleFast_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_doubleFast_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
628991 :
628992 return ZSTD_compressBlock_doubleFast_noDict_7(ms, seqStore, rep, src, srcSize);
628993 }
628994}
628995
628996
628997size_t ZSTD_compressBlock_doubleFast_dictMatchState(
628998 ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
628999 void const* src, size_t srcSize)
629000{
629001 const U32 mls = ms->cParams.minMatch;
629002 switch(mls)
629003 {
629004 default: /* includes case 3 */
629005 case 4 :
629006 return ZSTD_compressBlock_doubleFast_dictMatchState_4(ms, seqStore, rep, src, srcSize);
629007 case 5 :
Definition duckdb.cpp:614208

◆ ZSTD_compressBlock_doubleFast_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_doubleFast_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
629171{
629172 U32 const mls = ms->cParams.minMatch;
629173 switch(mls)
629174 {
629175 default: /* includes case 3 */
629176 case 4 :
629177 return ZSTD_compressBlock_doubleFast_extDict_4(ms, seqStore, rep, src, srcSize);
629178 case 5 :

◆ ZSTD_insertAndFindFirstIndex()

U32 duckdb_zstd::ZSTD_insertAndFindFirstIndex ( ZSTD_matchState_t * ms,
const BYTE * ip )

◆ ZSTD_row_update()

void duckdb_zstd::ZSTD_row_update ( ZSTD_matchState_t *const ms,
const BYTE * ip )
631130 {

◆ ZSTD_dedicatedDictSearch_lazy_loadDictionary()

void duckdb_zstd::ZSTD_dedicatedDictSearch_lazy_loadDictionary ( ZSTD_matchState_t * ms,
const BYTE *const ip )

Dedicated dict search

630593{
630594 const BYTE* const base = ms->window.base;
630595 U32 const target = (U32)(ip - base);
630596 U32* const hashTable = ms->hashTable;
630597 U32* const chainTable = ms->chainTable;
630598 U32 const chainSize = 1 << ms->cParams.chainLog;
630599 U32 idx = ms->nextToUpdate;
630600 U32 const minChain = chainSize < target - idx ? target - chainSize : idx;
630601 U32 const bucketSize = 1 << ZSTD_LAZY_DDSS_BUCKET_LOG;
630602 U32 const cacheSize = bucketSize - 1;
630603 U32 const chainAttempts = (1 << ms->cParams.searchLog) - cacheSize;
630604 U32 const chainLimit = chainAttempts > 255 ? 255 : chainAttempts;
630605
630606 /* We know the hashtable is oversized by a factor of `bucketSize`.
630607 * We are going to temporarily pretend `bucketSize == 1`, keeping only a
630608 * single entry. We will use the rest of the space to construct a temporary
630609 * chaintable.
630610 */
630611 U32 const hashLog = ms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
630612 U32* const tmpHashTable = hashTable;
630613 U32* const tmpChainTable = hashTable + ((size_t)1 << hashLog);
630614 U32 const tmpChainSize = (U32)((1 << ZSTD_LAZY_DDSS_BUCKET_LOG) - 1) << hashLog;
630615 U32 const tmpMinChain = tmpChainSize < target ? target - tmpChainSize : idx;
630616 U32 hashIdx;
630617
630618 assert(ms->cParams.chainLog <= 24);
630619 assert(ms->cParams.hashLog > ms->cParams.chainLog);
630620 assert(idx != 0);
630621 assert(tmpMinChain <= minChain);
630622
630623 /* fill conventional hash table and conventional chain table */
630624 for ( ; idx < target; idx++) {
630625 U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch);
630626 if (idx >= tmpMinChain) {
630627 tmpChainTable[idx - tmpMinChain] = hashTable[h];
630628 }
630629 tmpHashTable[h] = idx;
630630 }
630631
630632 /* sort chains into ddss chain table */
630633 {
630634 U32 chainPos = 0;
630635 for (hashIdx = 0; hashIdx < (1U << hashLog); hashIdx++) {
630636 U32 count;
630637 U32 countBeyondMinChain = 0;
630638 U32 i = tmpHashTable[hashIdx];
630639 for (count = 0; i >= tmpMinChain && count < cacheSize; count++) {
630640 /* skip through the chain to the first position that won't be
630641 * in the hash cache bucket */
630642 if (i < minChain) {
630643 countBeyondMinChain++;
630644 }
630645 i = tmpChainTable[i - tmpMinChain];
630646 }
630647 if (count == cacheSize) {
630648 for (count = 0; count < chainLimit;) {
630649 if (i < minChain) {
630650 if (!i || ++countBeyondMinChain > cacheSize) {
630651 /* only allow pulling `cacheSize` number of entries
630652 * into the cache or chainTable beyond `minChain`,
630653 * to replace the entries pulled out of the
630654 * chainTable into the cache. This lets us reach
630655 * back further without increasing the total number
630656 * of entries in the chainTable, guaranteeing the
630657 * DDSS chain table will fit into the space
630658 * allocated for the regular one. */
630659 break;
630660 }
630661 }
630662 chainTable[chainPos++] = i;
630663 count++;
630664 if (i < tmpMinChain) {
630665 break;
630666 }
630667 i = tmpChainTable[i - tmpMinChain];
630668 }
630669 } else {
630670 count = 0;
630671 }
630672 if (count) {
630673 tmpHashTable[hashIdx] = ((chainPos - count) << 8) + count;
630674 } else {
630675 tmpHashTable[hashIdx] = 0;
630676 }
630677 }
630678 assert(chainPos <= chainSize); /* I believe this is guaranteed... */
630679 }
630680
630681 /* move chain pointers into the last entry of each hash bucket */
630682 for (hashIdx = (1 << hashLog); hashIdx; ) {
630683 U32 const bucketIdx = --hashIdx << ZSTD_LAZY_DDSS_BUCKET_LOG;
630684 U32 const chainPackedPointer = tmpHashTable[hashIdx];
630685 U32 i;
630686 for (i = 0; i < cacheSize; i++) {
630687 hashTable[bucketIdx + i] = 0;
630688 }
630689 hashTable[bucketIdx + bucketSize - 1] = chainPackedPointer;
630690 }
630691
630692 /* fill the buckets of the hash table */
630693 for (idx = ms->nextToUpdate; idx < target; idx++) {
630694 U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch)
630696 U32 i;
630697 /* Shift hash cache down 1. */
#define ZSTD_LAZY_DDSS_BUCKET_LOG
Definition duckdb.cpp:619300
unsigned hashLog
Definition duckdb.cpp:408449
unsigned searchLog
Definition duckdb.cpp:408450

◆ ZSTD_compressBlock_greedy()

size_t duckdb_zstd::ZSTD_compressBlock_greedy ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )

used in ZSTD_reduceIndex(). preemptively increase value of ZSTD_DUBT_UNSORTED_MARK

◆ ZSTD_compressBlock_greedy_row()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
631982{
631983 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch);
631984}

◆ ZSTD_compressBlock_greedy_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
631968{
631969 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict);
631970}

◆ ZSTD_compressBlock_greedy_dictMatchState_row()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_dictMatchState_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
631989{
631990 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict);
631991}

◆ ZSTD_compressBlock_greedy_dedicatedDictSearch()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_dedicatedDictSearch ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
631975{
631976 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState);
631977}

◆ ZSTD_compressBlock_greedy_dedicatedDictSearch_row()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_dedicatedDictSearch_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
631996{
631997 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState);
631998}

◆ ZSTD_compressBlock_greedy_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )

◆ ZSTD_compressBlock_greedy_extDict_row()

size_t duckdb_zstd::ZSTD_compressBlock_greedy_extDict_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632325{
632326 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0);
632327}

◆ ZSTD_compressBlock_lazy()

size_t duckdb_zstd::ZSTD_compressBlock_lazy ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632003{
632004 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch);
632005}
632006#endif
632007

◆ ZSTD_compressBlock_lazy_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632026{
632027 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch);
632028}

◆ ZSTD_compressBlock_lazy_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632012{
632013 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict);
632014}

◆ ZSTD_compressBlock_lazy_dictMatchState_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_dictMatchState_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632033{
632034 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict);
632035}

◆ ZSTD_compressBlock_lazy_dedicatedDictSearch()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_dedicatedDictSearch ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632019{
632020 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState);
632021}

◆ ZSTD_compressBlock_lazy_dedicatedDictSearch_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_dedicatedDictSearch_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632040{
632041 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState);
632042}

◆ ZSTD_compressBlock_lazy_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632332{
632333 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0);
632334}
632335#endif
632336
632337#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR

◆ ZSTD_compressBlock_lazy_extDict_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy_extDict_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632342{
632343 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1);
632344}
632345

◆ ZSTD_compressBlock_lazy2()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2 ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632047{
632048 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch);
632049}
632050#endif
632051

◆ ZSTD_compressBlock_lazy2_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632070{
632071 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch);
632072}

◆ ZSTD_compressBlock_lazy2_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632056{
632057 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict);
632058}

◆ ZSTD_compressBlock_lazy2_dictMatchState_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_dictMatchState_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632077{
632078 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict);
632079}

◆ ZSTD_compressBlock_lazy2_dedicatedDictSearch()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_dedicatedDictSearch ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632063{
632064 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState);
632065}

◆ ZSTD_compressBlock_lazy2_dedicatedDictSearch_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_dedicatedDictSearch_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632084{
632085 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState);
632086}

◆ ZSTD_compressBlock_lazy2_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632350{
632351 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1);
632352}
632353#endif
632354
632355#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR

◆ ZSTD_compressBlock_lazy2_extDict_row()

size_t duckdb_zstd::ZSTD_compressBlock_lazy2_extDict_row ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632360{
632361 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2);
632362}

◆ ZSTD_compressBlock_btlazy2()

size_t duckdb_zstd::ZSTD_compressBlock_btlazy2 ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632091{
632092 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch);
632093}
632094#endif
632095

◆ ZSTD_compressBlock_btlazy2_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_btlazy2_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632100{
632101 return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict);
632102}

◆ ZSTD_compressBlock_btlazy2_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_btlazy2_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
632367{
632368 return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2);
632369}
632370#endif
632371
632372#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR

◆ ZSTD_updateTree()

void duckdb_zstd::ZSTD_updateTree ( ZSTD_matchState_t * ms,
const BYTE * ip,
const BYTE * iend )

◆ ZSTD_compressBlock_btopt()

size_t duckdb_zstd::ZSTD_compressBlock_btopt ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
634710{
634711 return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode);
634712}
634713#endif
634714
634715#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR

◆ ZSTD_compressBlock_btopt_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_btopt_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )

◆ ZSTD_compressBlock_btopt_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_btopt_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
634802{
634803 return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);
634804}

◆ ZSTD_compressBlock_btultra()

size_t duckdb_zstd::ZSTD_compressBlock_btultra ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )

◆ ZSTD_compressBlock_btultra_dictMatchState()

size_t duckdb_zstd::ZSTD_compressBlock_btultra_dictMatchState ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
634809{
634810 return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict);
634811}
634812#endif
634813

◆ ZSTD_compressBlock_btultra_extDict()

size_t duckdb_zstd::ZSTD_compressBlock_btultra_extDict ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
634818{
634819 return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);
634820}

◆ ZSTD_compressBlock_btultra2()

size_t duckdb_zstd::ZSTD_compressBlock_btultra2 ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize )
634764{
634765 DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);
634766 return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
634767}
634768
634769size_t ZSTD_compressBlock_btultra2(
634770 ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
634771 const void* src, size_t srcSize)
634772{
634773 U32 const curr = (U32)((const BYTE*)src - ms->window.base);
634774 DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);
634775
634776 /* 2-passes strategy:
634777 * this strategy makes a first pass over first block to collect statistics
634778 * in order to seed next round's statistics with it.
634779 * After 1st pass, function forgets history, and starts a new block.
634780 * Consequently, this can only work if no data has been previously loaded in tables,
634781 * aka, no dictionary, no prefix, no ldm preprocessing.
634782 * The compression ratio gain is generally small (~0.5% on first block),
634783 * the cost is 2x cpu time on first block. */
634784 assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
634785 if ( (ms->opt.litLengthSum==0) /* first block */
634786 && (seqStore->sequences == seqStore->sequencesStart) /* no ldm */
634787 && (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */
634788 && (curr == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */

◆ ZSTD_ldm_fillHashTable()

void duckdb_zstd::ZSTD_ldm_fillHashTable ( ldmState_t * state,
const BYTE * ip,
const BYTE * iend,
ldmParams_t const * params )
632777 :
632778 assert(0); /* not possible : not a valid strategy id */
632779 }
632780
632781 return 0;
632782}
632783
632784void ZSTD_ldm_fillHashTable(
632785 ldmState_t* ldmState, const BYTE* ip,
632786 const BYTE* iend, ldmParams_t const* params)
632787{
632788 U32 const minMatchLength = params->minMatchLength;
632789 U32 const hBits = params->hashLog - params->bucketSizeLog;
632790 BYTE const* const base = ldmState->window.base;
632791 BYTE const* const istart = ip;
632792 ldmRollingHashState_t hashState;
632793 size_t* const splits = ldmState->splitIndices;
632794 unsigned numSplits;
632795
632796 DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
632797
632798 ZSTD_ldm_gear_init(&hashState, params);
632799 while (ip < iend) {
632800 size_t hashed;
632801 unsigned n;
632802
632803 numSplits = 0;
632804 hashed = ZSTD_ldm_gear_feed(&hashState, ip, iend - ip, splits, &numSplits);
632805
632806 for (n = 0; n < numSplits; n++) {
632807 if (ip + splits[n] >= istart + minMatchLength) {
632808 BYTE const* const split = ip + splits[n] - minMatchLength;
632809 U64 const xxhash = XXH64(split, minMatchLength, 0);
632810 U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
632811 ldmEntry_t entry;
632812
632813 entry.offset = (U32)(split - base);
632814 entry.checksum = (U32)(xxhash >> 32);
void split(const Mat &src, Mat *mvbegin)
static void ZSTD_ldm_gear_init(ldmRollingHashState_t *state, ldmParams_t const *params)
Definition duckdb.cpp:632538
static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t *state, BYTE const *data, size_t size, size_t *splits, unsigned *numSplits)
Definition duckdb.cpp:632602
Definition duckdb.cpp:617782
Definition duckdb.cpp:617805
Definition duckdb.cpp:632529
Definition duckdb.cpp:617796

◆ ZSTD_ldm_generateSequences()

size_t duckdb_zstd::ZSTD_ldm_generateSequences ( ldmState_t * ldms,
rawSeqStore_t * sequences,
ldmParams_t const * params,
void const * src,
size_t srcSize )

ZSTD_ldm_generateSequences():

Generates the sequences using the long distance match finder. Generates long range matching sequences in sequences, which parse a prefix of the source. sequences must be large enough to store every sequence, which can be checked with ZSTD_ldm_getMaxNbSeq().

Returns
0 or an error code.

NOTE: The user must have called ZSTD_window_update() for all of the input they have, even if they pass it to ZSTD_ldm_generateSequences() in chunks. NOTE: This function returns an error if it runs out of space to store sequences.

633018 {
633019 if (table[u].offset < reducerValue) table[u].offset = 0;
633020 else table[u].offset -= reducerValue;
633021 }
633022}
633023
633025 ldmState_t* ldmState, rawSeqStore_t* sequences,
633026 ldmParams_t const* params, void const* src, size_t srcSize)
633027{
633028 U32 const maxDist = 1U << params->windowLog;
633029 BYTE const* const istart = (BYTE const*)src;
633030 BYTE const* const iend = istart + srcSize;
633031 size_t const kMaxChunkSize = 1 << 20;
633032 size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
633033 size_t chunk;
633034 size_t leftoverSize = 0;
633035
633036 assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
633037 /* Check that ZSTD_window_update() has been called for this chunk prior
633038 * to passing it to this function.
633039 */
633040 assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
633041 /* The input could be very large (in zstdmt), so it must be broken up into
633042 * chunks to enforce the maximum distance and handle overflow correction.
633043 */
633044 assert(sequences->pos <= sequences->size);
633045 assert(sequences->size <= sequences->capacity);
633046 for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
633047 BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
633048 size_t const remaining = (size_t)(iend - chunkStart);
633049 BYTE const *const chunkEnd =
633050 (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
633051 size_t const chunkSize = chunkEnd - chunkStart;
633052 size_t newLeftoverSize;
633053 size_t const prevSize = sequences->size;
633054
633055 assert(chunkStart < iend);
633056 /* 1. Perform overflow correction if necessary. */
633057 if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
633058 U32 const ldmHSize = 1U << params->hashLog;
633059 U32 const correction = ZSTD_window_correctOverflow(
633060 &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
633061 ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
633062 /* invalidate dictionaries on overflow correction */
633063 ldmState->loadedDictEnd = 0;
633064 }
633065 /* 2. We enforce the maximum offset allowed.
633066 *
633067 * kMaxChunkSize should be small enough that we don't lose too much of
633068 * the window through early invalidation.
633069 * TODO: * Test the chunk size.
633070 * * Try invalidation after the sequence generation and test the
633071 * offset against maxDist directly.
633072 *
633073 * NOTE: Because of dictionaries + sequence splitting we MUST make sure
633074 * that any offset used is valid at the END of the sequence, since it may
633075 * be split into two sequences. This condition holds when using
633076 * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
633077 * against maxDist directly, we'll have to carefully handle that case.
633078 */
633079 ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
633080 /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
633081 newLeftoverSize = ZSTD_ldm_generateSequences_internal(
633082 ldmState, sequences, params, chunkStart, chunkSize);
633083 if (ZSTD_isError(newLeftoverSize))
633084 return newLeftoverSize;
633085 /* 4. We add the leftover literals from previous iterations to the first
633086 * newly generated sequence, or add the `newLeftoverSize` if none are
633087 * generated.
633088 */
633089 /* Prepend the leftover literals from the last call */
633090 if (prevSize < sequences->size) {
633091 sequences->seq[prevSize].litLength += (U32)leftoverSize;
633092 leftoverSize = newLeftoverSize;
static void ZSTD_ldm_reduceTable(ldmEntry_t *const table, U32 const size, U32 const reducerValue)
Definition duckdb.cpp:633007
size_t ZSTD_ldm_generateSequences(ldmState_t *ldms, rawSeqStore_t *sequences, ldmParams_t const *params, void const *src, size_t srcSize)
Definition duckdb.cpp:633017
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_window_correctOverflow(ZSTD_window_t *window, U32 cycleLog, U32 maxDist, void const *src)
Definition duckdb.cpp:618567
MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window, U32 cycleLog, U32 maxDist, U32 loadedDictEnd, void const *src, void const *srcEnd)
Definition duckdb.cpp:618540
MEM_STATIC void ZSTD_window_enforceMaxDist(ZSTD_window_t *window, const void *blockEnd, U32 maxDist, U32 *loadedDictEndPtr, const ZSTD_matchState_t **dictMatchStatePtr)
Definition duckdb.cpp:618664
Definition duckdb.cpp:617658

◆ ZSTD_ldm_blockCompress()

size_t duckdb_zstd::ZSTD_ldm_blockCompress ( rawSeqStore_t * rawSeqStore,
ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
ZSTD_paramSwitch_e useRowMatchFinder,
void const * src,
size_t srcSize )

ZSTD_ldm_blockCompress():

Compresses a block using the predefined sequences, along with a secondary block compressor. The literals section of every sequence is passed to the secondary block compressor, and those sequences are interspersed with the predefined sequences. Returns the length of the last literals. Updates rawSeqStore.pos to indicate how many sequences have been consumed. rawSeqStore.seq may also be updated to split the last sequence between two blocks.

Returns
The length of the last literals.

NOTE: The source must be at most the maximum block size, but the predefined sequences can be any size, and may be longer than the block. In the case that they are longer than the block, the last sequences may need to be split into two. We handle that case correctly, and update rawSeqStore appropriately. NOTE: This function does not return any errors.

633174 {
633175 rawSeqStore->posInSequence = 0;
633176 }
633177}
633178
633179size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
633180 ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
633181 ZSTD_paramSwitch_e useRowMatchFinder,
633182 void const* src, size_t srcSize)
633183{
633184 const ZSTD_compressionParameters* const cParams = &ms->cParams;
633185 unsigned const minMatch = cParams->minMatch;
633186 ZSTD_blockCompressor const blockCompressor =
633187 ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
633188 /* Input bounds */
633189 BYTE const* const istart = (BYTE const*)src;
633190 BYTE const* const iend = istart + srcSize;
633191 /* Input positions */
633192 BYTE const* ip = istart;
633193
633194 DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
633195 /* If using opt parser, use LDMs only as candidates rather than always accepting them */
633196 if (cParams->strategy >= ZSTD_btopt) {
633197 size_t lastLLSize;
633198 ms->ldmSeqStore = rawSeqStore;
633199 lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
633200 ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
633201 return lastLLSize;
633202 }
633203
633204 assert(rawSeqStore->pos <= rawSeqStore->size);
633205 assert(rawSeqStore->size <= rawSeqStore->capacity);
633206 /* Loop through each sequence and apply the block compressor to the literals */
633207 while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
633208 /* maybeSplitSequence updates rawSeqStore->pos */
633209 rawSeq const sequence = maybeSplitSequence(rawSeqStore,
633210 (U32)(iend - ip), minMatch);
633211 /* End signal */
633212 if (sequence.offset == 0)
633213 break;
633214
633215 assert(ip + sequence.litLength + sequence.matchLength <= iend);
633216
633217 /* Fill tables for block compressor */
633219 ZSTD_ldm_fillFastTables(ms, ip);
633220 /* Run the block compressor */
633221 DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
633222 {
633223 int i;
633224 size_t const newLitLength =
633225 blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
633226 ip += sequence.litLength;
633227 /* Update the repcodes */
633228 for (i = ZSTD_REP_NUM - 1; i > 0; i--)
633229 rep[i] = rep[i-1];
633230 rep[0] = sequence.offset;
633231 /* Store the sequence */
633232 ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
633233 OFFSET_TO_OFFBASE(sequence.offset),
633234 sequence.matchLength);
633235 ip += sequence.matchLength;
633236 }
size_t ZSTD_ldm_blockCompress(rawSeqStore_t *rawSeqStore, ZSTD_matchState_t *ms, seqStore_t *seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const *src, size_t srcSize)
Definition duckdb.cpp:633172
static rawSeq maybeSplitSequence(rawSeqStore_t *rawSeqStore, U32 const remaining, U32 const minMatch)
Definition duckdb.cpp:633131
static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t *ms, void const *end)
Definition duckdb.cpp:632743
static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t *ms, const BYTE *anchor)
Definition duckdb.cpp:632822
MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
Definition duckdb.cpp:618479

◆ ZSTD_ldm_skipSequences()

void duckdb_zstd::ZSTD_ldm_skipSequences ( rawSeqStore_t * rawSeqStore,
size_t srcSize,
U32 const minMatch )

ZSTD_ldm_skipSequences():

Skip past srcSize bytes worth of sequences in rawSeqStore. Avoids emitting matches less than minMatch bytes. Must be called for data that is not passed to ZSTD_ldm_blockCompress().

633103{
633104 while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
633105 rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
633106 if (srcSize <= seq->litLength) {
633107 /* Skip past srcSize literals */
633108 seq->litLength -= (U32)srcSize;
633109 return;
633110 }
633111 srcSize -= seq->litLength;
633112 seq->litLength = 0;
633113 if (srcSize < seq->matchLength) {
633114 /* Skip past the first srcSize of the match */
633115 seq->matchLength -= (U32)srcSize;
633116 if (seq->matchLength < minMatch) {
633117 /* The match is too short, omit it */
633118 if (rawSeqStore->pos + 1 < rawSeqStore->size) {
633119 seq[1].litLength += seq[0].matchLength;
633120 }
633121 rawSeqStore->pos++;
633122 }
Here is the caller graph for this function:

◆ ZSTD_ldm_skipRawSeqStoreBytes()

void duckdb_zstd::ZSTD_ldm_skipRawSeqStoreBytes ( rawSeqStore_t * rawSeqStore,
size_t nbBytes )
633162 {
633163 U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
633164 while (currPos && rawSeqStore->pos < rawSeqStore->size) {
633165 rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
633166 if (currPos >= currSeq.litLength + currSeq.matchLength) {
633167 currPos -= currSeq.litLength + currSeq.matchLength;
633168 rawSeqStore->pos++;
633169 } else {
633170 rawSeqStore->posInSequence = currPos;

◆ ZSTD_ldm_getTableSize()

size_t duckdb_zstd::ZSTD_ldm_getTableSize ( ldmParams_t params)

ZSTD_ldm_getTableSize() : Estimate the space needed for long distance matching tables or 0 if LDM is disabled.

632663 : params->windowLog - params->hashLog;
632664 }
632665 params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
632666}
632667
632668size_t ZSTD_ldm_getTableSize(ldmParams_t params)
632669{
size_t ZSTD_ldm_getTableSize(ldmParams_t params)
Definition duckdb.cpp:632661

◆ ZSTD_ldm_getMaxNbSeq()

size_t duckdb_zstd::ZSTD_ldm_getMaxNbSeq ( ldmParams_t params,
size_t maxChunkSize )

ZSTD_ldm_getSeqSpace() : Return an upper bound on the number of sequences that can be produced by the long distance matcher, or 0 if LDM is disabled.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_ldm_adjustParameters()

void duckdb_zstd::ZSTD_ldm_adjustParameters ( ldmParams_t * params,
ZSTD_compressionParameters const * cParams )

ZSTD_ldm_adjustParameters() : If the params->hashRateLog is not set, set it to its default value based on windowLog and params->hashLog.

Ensures that params->bucketSizeLog is <= params->hashLog (setting it to params->hashLog if it is not).

Ensures that the minMatchLength >= targetLength during optimal parsing.

632643 :
632644 state->rolling = hash;
632645 return n;
632646}
632647
632648void ZSTD_ldm_adjustParameters(ldmParams_t* params,
632649 ZSTD_compressionParameters const* cParams)
632650{
632651 params->windowLog = cParams->windowLog;
632652 ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
632653 DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
632654 if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG;
632655 if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH;
632656 if (params->hashLog == 0) {
632657 params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG);
632658 assert(params->hashLog <= ZSTD_HASHLOG_MAX);
632659 }
void ZSTD_ldm_adjustParameters(ldmParams_t *params, ZSTD_compressionParameters const *cParams)
Definition duckdb.cpp:632641
Here is the caller graph for this function:

◆ ZSTD_compressSuperBlock()

size_t duckdb_zstd::ZSTD_compressSuperBlock ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
void const * src,
size_t srcSize,
unsigned lastBlock )
628376 : total compressed size = %u",
628377 (unsigned)(op-ostart));
628378 return (size_t)(op-ostart);
628379}
628380
628381size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
628382 void* dst, size_t dstCapacity,
628383 const void* src, size_t srcSize,
628384 unsigned lastBlock)
628385{
628386 ZSTD_entropyCTablesMetadata_t entropyMetadata;
628387
628388 FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
628389 &zc->blockState.prevCBlock->entropy,
628390 &zc->blockState.nextCBlock->entropy,
628391 &zc->appliedParams,
628392 &entropyMetadata,
628393 zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), "");
628394
628395 return ZSTD_compressSubBlock_multi(&zc->seqStore,
628396 zc->blockState.prevCBlock,
628397 zc->blockState.nextCBlock,

◆ ZSTD_initCCtx()

void duckdb_zstd::ZSTD_initCCtx ( ZSTD_CCtx * cctx,
ZSTD_customMem memManager )
static
619810{
619811 return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
619812}
619813
619814static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
619815{
619816 assert(cctx != NULL);
619817 ZSTD_memset(cctx, 0, sizeof(*cctx));

◆ ZSTD_clearAllDicts()

void duckdb_zstd::ZSTD_clearAllDicts ( ZSTD_CCtx * cctx)
static

Clears and frees all of the dictionaries in the CCtx.

◆ ZSTD_sizeof_localDict()

size_t duckdb_zstd::ZSTD_sizeof_localDict ( ZSTD_localDict dict)
static

◆ ZSTD_freeCCtxContent()

void duckdb_zstd::ZSTD_freeCCtxContent ( ZSTD_CCtx * cctx)
static
619875{
619876 size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
619877 size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
619878 return bufferSize + cdictSize;
619879}
619880
619881static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
619882{
619883 assert(cctx != NULL);

◆ ZSTD_sizeof_mtctx()

size_t duckdb_zstd::ZSTD_sizeof_mtctx ( const ZSTD_CCtx * cctx)
static
619907{

◆ ZSTD_rowMatchFinderSupported()

int duckdb_zstd::ZSTD_rowMatchFinderSupported ( const ZSTD_strategy strategy)
static

◆ ZSTD_rowMatchFinderUsed()

int duckdb_zstd::ZSTD_rowMatchFinderUsed ( const ZSTD_strategy strategy,
const ZSTD_paramSwitch_e mode )
static
619936 {
619937 return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);
619938}
619939

◆ ZSTD_resolveRowMatchFinderMode()

ZSTD_paramSwitch_e duckdb_zstd::ZSTD_resolveRowMatchFinderMode ( ZSTD_paramSwitch_e mode,
const ZSTD_compressionParameters *const cParams )
static
619943 {
619944 assert(mode != ZSTD_ps_auto);
619945 return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_ps_enable);
619946}
619947
619948/* Returns row matchfinder usage given an initial mode and cParams */
619949static ZSTD_paramSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_paramSwitch_e mode,
619950 const ZSTD_compressionParameters* const cParams) {
619951#if defined(ZSTD_ARCH_X86_SSE2) || defined(ZSTD_ARCH_ARM_NEON)
619952 int const kHasSIMD128 = 1;
619953#else
619954 int const kHasSIMD128 = 0;
619955#endif
619956 if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
619957 mode = ZSTD_ps_disable;
619958 if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;

◆ ZSTD_resolveBlockSplitterMode()

ZSTD_paramSwitch_e duckdb_zstd::ZSTD_resolveBlockSplitterMode ( ZSTD_paramSwitch_e mode,
const ZSTD_compressionParameters *const cParams )
static
619961 {
619962 if (cParams->windowLog > 17) mode = ZSTD_ps_enable;
619963 }
619964 return mode;
619965}

◆ ZSTD_allocateChainTable()

int duckdb_zstd::ZSTD_allocateChainTable ( const ZSTD_strategy strategy,
const ZSTD_paramSwitch_e useRowMatchFinder,
const U32 forDDSDict )
static
619969 {
619970 if (mode != ZSTD_ps_auto) return mode;
619971 return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17) ? ZSTD_ps_enable : ZSTD_ps_disable;
619972}
619973
619974/* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
619975static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
619976 const ZSTD_paramSwitch_e useRowMatchFinder,

◆ ZSTD_resolveEnableLdm()

ZSTD_paramSwitch_e duckdb_zstd::ZSTD_resolveEnableLdm ( ZSTD_paramSwitch_e mode,
const ZSTD_compressionParameters *const cParams )
static

◆ ZSTD_resolveExternalSequenceValidation()

int duckdb_zstd::ZSTD_resolveExternalSequenceValidation ( int mode)
static
619990 {

◆ ZSTD_resolveMaxBlockSize()

size_t duckdb_zstd::ZSTD_resolveMaxBlockSize ( size_t maxBlockSize)
static
619995 {
619996 return mode;
619997}
619998
619999/* Resolves maxBlockSize to the default if no value is present. */

◆ ZSTD_resolveExternalRepcodeSearch()

ZSTD_paramSwitch_e duckdb_zstd::ZSTD_resolveExternalRepcodeSearch ( ZSTD_paramSwitch_e value,
int cLevel )
static
620001 {
620002 return ZSTD_BLOCKSIZE_MAX;
620003 } else {
620004 return maxBlockSize;
620005 }
620006}
620007
620008static ZSTD_paramSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_paramSwitch_e value, int cLevel) {

◆ ZSTD_CDictIndicesAreTagged()

int duckdb_zstd::ZSTD_CDictIndicesAreTagged ( const ZSTD_compressionParameters *const cParams)
static
620012 {
620013 return ZSTD_ps_enable;
620014 }

◆ ZSTD_makeCCtxParamsFromCParams()

ZSTD_CCtx_params duckdb_zstd::ZSTD_makeCCtxParamsFromCParams ( ZSTD_compressionParameters cParams)
static
620019 {
620020 return cParams->strategy == ZSTD_fast || cParams->strategy == ZSTD_dfast;
620021}
620022
620023static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
620024 ZSTD_compressionParameters cParams)
620025{
620026 ZSTD_CCtx_params cctxParams;
620027 /* should not matter, as all cParams are presumed properly defined */
620028 ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
620029 cctxParams.cParams = cParams;
620030
620031 /* Adjust advanced params according to cParams */
620032 cctxParams.ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);
620033 if (cctxParams.ldmParams.enableLdm == ZSTD_ps_enable) {
620034 ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
620035 assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
620036 assert(cctxParams.ldmParams.hashRateLog < 32);
620037 }
620038 cctxParams.useBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.useBlockSplitter, &cParams);
620039 cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);

◆ ZSTD_createCCtxParams_advanced()

ZSTD_CCtx_params * duckdb_zstd::ZSTD_createCCtxParams_advanced ( ZSTD_customMem customMem)
static
620050{
620051 ZSTD_CCtx_params* params;
620052 if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;

◆ ZSTD_CCtxParams_init_internal()

void duckdb_zstd::ZSTD_CCtxParams_init_internal ( ZSTD_CCtx_params * cctxParams,
const ZSTD_parameters * params,
int compressionLevel )
static

Initializes cctxParams from params and compressionLevel.

Parameters
compressionLevelIf params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
620096{
620097 assert(!ZSTD_checkCParams(params->cParams));
620098 ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
620099 cctxParams->cParams = params->cParams;
620100 cctxParams->fParams = params->fParams;
620101 /* Should not matter, as all cParams are presumed properly defined.
620102 * But, set it for tracing anyway.
620103 */
620104 cctxParams->compressionLevel = compressionLevel;
620105 cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, &params->cParams);
620106 cctxParams->useBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->useBlockSplitter, &params->cParams);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_CCtxParams_setZstdParams()

void duckdb_zstd::ZSTD_CCtxParams_setZstdParams ( ZSTD_CCtx_params * cctxParams,
const ZSTD_parameters * params )
static

Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.

Parameters
paramsValidated zstd parameters.
620129{
620130 assert(!ZSTD_checkCParams(params->cParams));
Here is the caller graph for this function:

◆ ZSTD_cParam_clampBounds()

size_t duckdb_zstd::ZSTD_cParam_clampBounds ( ZSTD_cParameter cParam,
int * value )
static

◆ ZSTD_isUpdateAuthorized()

int duckdb_zstd::ZSTD_isUpdateAuthorized ( ZSTD_cParameter param)
static
620367 { \
620368 RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
620369 parameter_outOfBound, "Param out of bounds"); \
620370 } while (0)
620371
620372
620373static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
620374{
620375 switch(param)
620376 {
620377 case ZSTD_c_compressionLevel:
620378 case ZSTD_c_hashLog:
620379 case ZSTD_c_chainLog:
620380 case ZSTD_c_searchLog:
620381 case ZSTD_c_minMatch:
620382 case ZSTD_c_targetLength:
620383 case ZSTD_c_strategy:
620384 return 1;
620385
620386 case ZSTD_c_format:
620387 case ZSTD_c_windowLog:
620388 case ZSTD_c_contentSizeFlag:
620389 case ZSTD_c_checksumFlag:
620390 case ZSTD_c_dictIDFlag:
620391 case ZSTD_c_forceMaxWindow :
620392 case ZSTD_c_nbWorkers:
620393 case ZSTD_c_jobSize:
620394 case ZSTD_c_overlapLog:
620395 case ZSTD_c_rsyncable:
620396 case ZSTD_c_enableDedicatedDictSearch:
620397 case ZSTD_c_enableLongDistanceMatching:
620398 case ZSTD_c_ldmHashLog:
620399 case ZSTD_c_ldmMinMatch:
620400 case ZSTD_c_ldmBucketSizeLog:
620401 case ZSTD_c_ldmHashRateLog:
620402 case ZSTD_c_forceAttachDict:
620403 case ZSTD_c_literalCompressionMode:
620404 case ZSTD_c_targetCBlockSize:
620405 case ZSTD_c_srcSizeHint:
620406 case ZSTD_c_stableInBuffer:
620407 case ZSTD_c_stableOutBuffer:
620408 case ZSTD_c_blockDelimiters:
620409 case ZSTD_c_validateSequences:
620410 case ZSTD_c_useBlockSplitter:
620411 case ZSTD_c_useRowMatchFinder:
620412 case ZSTD_c_deterministicRefPrefix:
620413 case ZSTD_c_prefetchCDictTables:

◆ ZSTD_dedicatedDictSearch_getCParams()

ZSTD_compressionParameters duckdb_zstd::ZSTD_dedicatedDictSearch_getCParams ( int const compressionLevel,
size_t const dictSize )
static
626832 {
626833
626834int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
626835int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
626836int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
626837
626838static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
626839{
626840 ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
626841 switch (cParams.strategy) {
626842 case ZSTD_fast:
626843 case ZSTD_dfast:
626844 break;
626845 case ZSTD_greedy:
626846 case ZSTD_lazy:
626847 case ZSTD_lazy2:
626848 cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
626849 break;
626850 case ZSTD_btlazy2:
ZSTDLIB_API int ZSTD_defaultCLevel(void)
Definition duckdb.cpp:626829

◆ ZSTD_dedicatedDictSearch_isSupported()

int duckdb_zstd::ZSTD_dedicatedDictSearch_isSupported ( const ZSTD_compressionParameters * cParams)
static
626852 :
626853 case ZSTD_btultra2:
626854 break;
626855 }
626856 return cParams;
626857}
626858
626859static int ZSTD_dedicatedDictSearch_isSupported(

◆ ZSTD_dedicatedDictSearch_revertCParams()

void duckdb_zstd::ZSTD_dedicatedDictSearch_revertCParams ( ZSTD_compressionParameters * cParams)
static

Reverses the adjustment applied to cparams when enabling dedicated dict search. This is used to recover the params set to be used in the working context. (Otherwise, those tables would also grow.)

626874 {
626875 switch (cParams->strategy) {
626876 case ZSTD_fast:
626877 case ZSTD_dfast:
626878 break;
626879 case ZSTD_greedy:
626880 case ZSTD_lazy:
626881 case ZSTD_lazy2:
626883 if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
626884 cParams->hashLog = ZSTD_HASHLOG_MIN;
626885 }
626886 break;

◆ ZSTD_initLocalDict()

size_t duckdb_zstd::ZSTD_initLocalDict ( ZSTD_CCtx * cctx)
static

Initializes the local dictionary using requested parameters. NOTE: Initialization does not employ the pledged src size, because the dictionary may be used for multiple compressions.

620957{
620958 ZSTD_localDict* const dl = &cctx->localDict;
620959 if (dl->dict == NULL) {
620960 /* No local dictionary. */
620961 assert(dl->dictBuffer == NULL);
620962 assert(dl->cdict == NULL);
620963 assert(dl->dictSize == 0);
620964 return 0;
620965 }
620966 if (dl->cdict != NULL) {
620967 /* Local dictionary already initialized. */
620968 assert(cctx->cdict == dl->cdict);
620969 return 0;
620970 }
620971 assert(dl->dictSize > 0);
620972 assert(cctx->cdict == NULL);
620973 assert(cctx->prefixDict.dict == NULL);
620974
620975 dl->cdict = ZSTD_createCDict_advanced2(
620976 dl->dict,
620977 dl->dictSize,
Definition duckdb.cpp:617572
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_clampCParams()

ZSTD_compressionParameters duckdb_zstd::ZSTD_clampCParams ( ZSTD_compressionParameters cParams)
static

ZSTD_clampCParams() : make CParam values within valid range.

Returns
: valid CParams
621109{
621110# define CLAMP_TYPE(cParam, val, type) \
621111 do { \
621112 ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \
621113 if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \
621114 else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
621115 } while (0)
621116# define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
621117 CLAMP(ZSTD_c_windowLog, cParams.windowLog);
621118 CLAMP(ZSTD_c_chainLog, cParams.chainLog);

◆ ZSTD_dictAndWindowLog()

U32 duckdb_zstd::ZSTD_dictAndWindowLog ( U32 windowLog,
U64 srcSize,
U64 dictSize )
static

ZSTD_dictAndWindowLog() : Returns an adjusted window log that is large enough to fit the source and the dictionary. The zstd format says that the entire dictionary is valid if one byte of the dictionary is within the window. So the hashLog and chainLog should be large enough to reference both the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing the hashLog and windowLog. NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.

621141 : srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.
621142 */
621143static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
621144{
621145 const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;
621146 /* No dictionary ==> No change */
621147 if (dictSize == 0) {
621148 return windowLog;
621149 }
621150 assert(windowLog <= ZSTD_WINDOWLOG_MAX);
621151 assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */
621152 {
621153 U64 const windowSize = 1ULL << windowLog;
621154 U64 const dictAndWindowSize = dictSize + windowSize;
621155 /* If the window size is already large enough to fit both the source and the dictionary
621156 * then just use the window size. Otherwise adjust so that it fits the dictionary and
621157 * the window.
621158 */
621159 if (windowSize >= dictSize + srcSize) {
621160 return windowLog; /* Window size large enough already */
static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
Definition duckdb.cpp:621136
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_adjustCParams_internal()

ZSTD_compressionParameters duckdb_zstd::ZSTD_adjustCParams_internal ( ZSTD_compressionParameters cPar,
unsigned long long srcSize,
size_t dictSize,
ZSTD_cParamMode_e mode,
ZSTD_paramSwitch_e useRowMatchFinder )
static

ZSTD_adjustCParams_internal() : optimize cPar for a specified input (srcSize and dictSize). mostly downsize to reduce memory consumption and initialization latency. srcSize can be ZSTD_CONTENTSIZE_UNKNOWN when not known. mode is the mode for parameter adjustment. See docs for ZSTD_cParamMode_e. note : srcSize==0 means 0! condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()).

621174 : `srcSize==0` means 0!
621175 * condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
621178 unsigned long long srcSize,
621179 size_t dictSize,
621180 ZSTD_cParamMode_e mode,
621181 ZSTD_paramSwitch_e useRowMatchFinder)
621182{
621183 const U64 minSrcSize = 513; /* (1<<9) + 1 */
621184 const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
621185 assert(ZSTD_checkCParams(cPar)==0);
621186
621187 /* Cascade the selected strategy down to the next-highest one built into
621188 * this binary. */
621189#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
621190 if (cPar.strategy == ZSTD_btultra2) {
621191 cPar.strategy = ZSTD_btultra;
621192 }
621193 if (cPar.strategy == ZSTD_btultra) {
621194 cPar.strategy = ZSTD_btopt;
621195 }
621196#endif
621197#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
621198 if (cPar.strategy == ZSTD_btopt) {
621199 cPar.strategy = ZSTD_btlazy2;
621200 }
621201#endif
621202#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
621203 if (cPar.strategy == ZSTD_btlazy2) {
621204 cPar.strategy = ZSTD_lazy2;
621205 }
621206#endif
621207#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
621208 if (cPar.strategy == ZSTD_lazy2) {
621209 cPar.strategy = ZSTD_lazy;
621210 }
621211#endif
621212#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
621213 if (cPar.strategy == ZSTD_lazy) {
621214 cPar.strategy = ZSTD_greedy;
621215 }
621216#endif
621217#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
621218 if (cPar.strategy == ZSTD_greedy) {
621219 cPar.strategy = ZSTD_dfast;
621220 }
621221#endif
621222#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
621223 if (cPar.strategy == ZSTD_dfast) {
621224 cPar.strategy = ZSTD_fast;
621225 cPar.targetLength = 0;
621226 }
621227#endif
621228
621229 switch (mode) {
621230 case ZSTD_cpm_unknown:
621231 case ZSTD_cpm_noAttachDict:
621232 /* If we don't know the source size, don't make any
621233 * assumptions about it. We will already have selected
621234 * smaller parameters if a dictionary is in use.
621235 */
621236 break;
621237 case ZSTD_cpm_createCDict:
621238 /* Assume a small source size when creating a dictionary
621239 * with an unknown source size.
621240 */
621241 if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
621242 srcSize = minSrcSize;
621243 break;
621244 case ZSTD_cpm_attachDict:
621245 /* Dictionary has its own dedicated parameters which have
621246 * already been selected. We are selecting parameters
621247 * for only the source.
621248 */
621249 dictSize = 0;
621250 break;
621251 default:
621252 assert(0);
621253 break;
621254 }
621255
621256 /* resize windowLog if input is small enough, to use less memory */
621257 if ( (srcSize <= maxWindowResize)
621258 && (dictSize <= maxWindowResize) ) {
621259 U32 const tSize = (U32)(srcSize + dictSize);
621260 static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
621261 U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
621262 ZSTD_highbit32(tSize-1) + 1;
621263 if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
621264 }
621265 if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
621266 U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);
621267 U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
621268 if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;
621269 if (cycleLog > dictAndWindowLog)
621270 cPar.chainLog -= (cycleLog - dictAndWindowLog);
621271 }
621272
621273 if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
621274 cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* minimum wlog required for valid frame header */
621275
621276 /* We can't use more than 32 bits of hash in total, so that means that we require:
621277 * (hashLog + 8) <= 32 && (chainLog + 8) <= 32
621278 */
621279 if (mode == ZSTD_cpm_createCDict && ZSTD_CDictIndicesAreTagged(&cPar)) {
621280 U32 const maxShortCacheHashLog = 32 - ZSTD_SHORT_CACHE_TAG_BITS;
621281 if (cPar.hashLog > maxShortCacheHashLog) {
621282 cPar.hashLog = maxShortCacheHashLog;
621283 }
621284 if (cPar.chainLog > maxShortCacheHashLog) {
621285 cPar.chainLog = maxShortCacheHashLog;
621286 }
621287 }
621288
621289
621290 /* At this point, we aren't 100% sure if we are using the row match finder.
621291 * Unless it is explicitly disabled, conservatively assume that it is enabled.
621292 * In this case it will only be disabled for small sources, so shrinking the
621293 * hash log a little bit shouldn't result in any ratio loss.
621294 */
621295 if (useRowMatchFinder == ZSTD_ps_auto)
621296 useRowMatchFinder = ZSTD_ps_enable;
621297
621298 /* We can't hash more than 32-bits in total. So that means that we require:
621299 * (hashLog - rowLog + 8) <= 32
621300 */
621301 if (ZSTD_rowMatchFinderUsed(cPar.strategy, useRowMatchFinder)) {
621302 /* Switch to 32-entry rows if searchLog is 5 (or more) */
621303 U32 const rowLog = BOUNDED(4, cPar.searchLog, 6);
621304 U32 const maxRowHashLog = 32 - ZSTD_ROW_HASH_TAG_BITS;
621305 U32 const maxHashLog = maxRowHashLog + rowLog;
621306 assert(cPar.hashLog >= rowLog);
U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
Definition duckdb.cpp:621122
static ZSTD_compressionParameters ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize, ZSTD_cParamMode_e mode, ZSTD_paramSwitch_e useRowMatchFinder)
Definition duckdb.cpp:621170
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_getCParams_internal()

ZSTD_compressionParameters duckdb_zstd::ZSTD_getCParams_internal ( int compressionLevel,
unsigned long long srcSizeHint,
size_t dictSize,
ZSTD_cParamMode_e mode )
static

ZSTD_getCParams_internal() :

Returns
ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize. Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown. Use dictSize == 0 for unknown or unused. Note: mode controls how we treat the dictSize. See docs for ZSTD_cParamMode_e.
626921{
626922 U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
626923 U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
626924 int row;
626925 DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
626926
626927 /* row */
626928 if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
626929 else if (compressionLevel < 0) row = 0; /* entry 0 is baseline for fast mode */
626930 else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
626931 else row = compressionLevel;
626932
626933 { ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
626934 DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
626935 /* acceleration factor */
626936 if (compressionLevel < 0) {
Here is the caller graph for this function:

◆ ZSTD_getParams_internal()

ZSTD_parameters duckdb_zstd::ZSTD_getParams_internal ( int compressionLevel,
unsigned long long srcSizeHint,
size_t dictSize,
ZSTD_cParamMode_e mode )
static

ZSTD_getParams() : same idea as ZSTD_getCParams()

Returns
a ZSTD_parameters structure (instead of ZSTD_compressionParameters). Fields of ZSTD_frameParameters are set to default values
626958 {
Definition duckdb.cpp:408462
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_overrideCParams()

void duckdb_zstd::ZSTD_overrideCParams ( ZSTD_compressionParameters * cParams,
const ZSTD_compressionParameters * overrides )
static
621331{
621332 if (overrides->windowLog) cParams->windowLog = overrides->windowLog;

◆ ZSTD_sizeof_matchState()

size_t duckdb_zstd::ZSTD_sizeof_matchState ( const ZSTD_compressionParameters *const cParams,
const ZSTD_paramSwitch_e useRowMatchFinder,
const U32 enableDedicatedDictSearch,
const U32 forCCtx )
static
621361{
621362 /* chain table size should be 0 for fast or row-hash strategies */
621363 size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)
621364 ? ((size_t)1 << cParams->chainLog)
621365 : 0;
621366 size_t const hSize = ((size_t)1) << cParams->hashLog;
621367 U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
621368 size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
621369 /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
621370 * surrounded by redzones in ASAN. */
621371 size_t const tableSpace = chainSize * sizeof(U32)
621372 + hSize * sizeof(U32)
621373 + h3Size * sizeof(U32);
621374 size_t const optPotentialSpace =
621375 ZSTD_cwksp_aligned_alloc_size((MaxML+1) * sizeof(U32))
621376 + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32))
621377 + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32))
621378 + ZSTD_cwksp_aligned_alloc_size((1<<Litbits) * sizeof(U32))
621379 + ZSTD_cwksp_aligned_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_match_t))
621380 + ZSTD_cwksp_aligned_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
621381 size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)
621383 : 0;
621384 size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
621385 ? optPotentialSpace
621386 : 0;
621387 size_t const slackSpace = ZSTD_cwksp_slack_space_required();
621388
621389 /* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
#define ZSTD_HASHLOG3_MAX
Definition duckdb.cpp:619759
MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size)
Definition duckdb.cpp:617018
Definition duckdb.cpp:617647
Definition duckdb.cpp:617675

◆ ZSTD_maxNbSeq()

size_t duckdb_zstd::ZSTD_maxNbSeq ( size_t blockSize,
unsigned minMatch,
int useSequenceProducer )
static
621393 : %u - hSize: %u - h3Size: %u",
621394 (U32)chainSize, (U32)hSize, (U32)h3Size);
621395 return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;
621396}

◆ ZSTD_estimateCCtxSize_usingCCtxParams_internal()

size_t duckdb_zstd::ZSTD_estimateCCtxSize_usingCCtxParams_internal ( const ZSTD_compressionParameters * cParams,
const ldmParams_t * ldmParams,
const int isStatic,
const ZSTD_paramSwitch_e useRowMatchFinder,
const size_t buffInSize,
const size_t buffOutSize,
const U64 pledgedSrcSize,
int useSequenceProducer,
size_t maxBlockSize )
static
621400 {
621401 U32 const divider = (minMatch==3 || useSequenceProducer) ? 3 : 4;
621402 return blockSize / divider;
621403}
621404
621405static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
621406 const ZSTD_compressionParameters* cParams,
621407 const ldmParams_t* ldmParams,
621408 const int isStatic,
621409 const ZSTD_paramSwitch_e useRowMatchFinder,
621410 const size_t buffInSize,
621411 const size_t buffOutSize,
621412 const U64 pledgedSrcSize,
621413 int useSequenceProducer,
621414 size_t maxBlockSize)
621415{
621416 size_t const windowSize = (size_t) BOUNDED(1ULL, 1ULL << cParams->windowLog, pledgedSrcSize);
621417 size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize);
621418 size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer);
621419 size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
621420 + ZSTD_cwksp_aligned_alloc_size(maxNbSeq * sizeof(seqDef))
621421 + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
621422 size_t const entropySpace = ZSTD_cwksp_alloc_size(ENTROPY_WORKSPACE_SIZE);
621423 size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
621424 size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
621425
621426 size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
621427 size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
621428 size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ?
621429 ZSTD_cwksp_aligned_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
621430
621431
621432 size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
621433 + ZSTD_cwksp_alloc_size(buffOutSize);
621434
621435 size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
621436
621437 size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
621438 size_t const externalSeqSpace = useSequenceProducer
621439 ? ZSTD_cwksp_aligned_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence))
621440 : 0;
621441
621442 size_t const neededSpace =
621443 cctxSpace +
621444 entropySpace +
621445 blockStateSpace +
621446 ldmSpace +
621447 ldmSeqSpace +
621448 matchStateSize +
ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize)
Definition duckdb.cpp:623144
size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
Definition duckdb.cpp:632671

◆ ZSTD_estimateCCtxSize_internal()

size_t duckdb_zstd::ZSTD_estimateCCtxSize_internal ( int compressionLevel)
static
621484 {
621485 return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
621486 }
621487}
621488
621489static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
621490{
621491 int tier = 0;
621492 size_t largestSize = 0;
621493 static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};

◆ ZSTD_estimateCStreamSize_internal()

size_t duckdb_zstd::ZSTD_estimateCStreamSize_internal ( int compressionLevel)
static
621546 {
621547 return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
621548 }

◆ ZSTD_assertEqualCParams()

void duckdb_zstd::ZSTD_assertEqualCParams ( ZSTD_compressionParameters cParams1,
ZSTD_compressionParameters cParams2 )
static
621609{
621610 (void)cParams1;
621611 (void)cParams2;
621612 assert(cParams1.windowLog == cParams2.windowLog);

◆ ZSTD_invalidateMatchState()

void duckdb_zstd::ZSTD_invalidateMatchState ( ZSTD_matchState_t * ms)
static

ZSTD_invalidateMatchState() Invalidate all the matches in the match finder tables. Requires nextSrc and base to be set (can be NULL).

621637{

◆ ZSTD_bitmix()

U64 duckdb_zstd::ZSTD_bitmix ( U64 val,
U64 len )
static
621668 {
621669 ZSTD_resetTarget_CDict,
621670 ZSTD_resetTarget_CCtx
621671} ZSTD_resetTarget_e;
621672
621673/* Mixes bits in a 64 bits in a value, based on XXH3_rrmxmx */

◆ ZSTD_advanceHashSalt()

void duckdb_zstd::ZSTD_advanceHashSalt ( ZSTD_matchState_t * ms)
static

◆ ZSTD_reset_matchState()

size_t duckdb_zstd::ZSTD_reset_matchState ( ZSTD_matchState_t * ms,
ZSTD_cwksp * ws,
const ZSTD_compressionParameters * cParams,
const ZSTD_paramSwitch_e useRowMatchFinder,
const ZSTD_compResetPolicy_e crp,
const ZSTD_indexResetPolicy_e forceResetIndex,
const ZSTD_resetTarget_e forWho )
static
621683 {
621684 ms->hashSalt = ZSTD_bitmix(ms->hashSalt, 8) ^ ZSTD_bitmix((U64) ms->hashSaltEntropy, 4);
621685}
621686
621687static size_t
621688ZSTD_reset_matchState(ZSTD_matchState_t* ms,
621689 ZSTD_cwksp* ws,
621690 const ZSTD_compressionParameters* cParams,
621691 const ZSTD_paramSwitch_e useRowMatchFinder,
621692 const ZSTD_compResetPolicy_e crp,
621693 const ZSTD_indexResetPolicy_e forceResetIndex,
621694 const ZSTD_resetTarget_e forWho)
621695{
621696 /* disable chain table allocation for fast or row-based strategies */
621697 size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
621698 ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
621699 ? ((size_t)1 << cParams->chainLog)
621700 : 0;
621701 size_t const hSize = ((size_t)1) << cParams->hashLog;
621702 U32 const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
621703 size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
621704
621705 DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
621706 assert(useRowMatchFinder != ZSTD_ps_auto);
621707 if (forceResetIndex == ZSTDirp_reset) {
621708 ZSTD_window_init(&ms->window);
621709 ZSTD_cwksp_mark_tables_dirty(ws);
621710 }
621711
621712 ms->hashLog3 = hashLog3;
621713 ms->lazySkipping = 0;
621714
621716
621717 assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
621718
621720
621721 DEBUGLOG(5, "reserving table space");
621722 /* table Space */
621723 ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
621724 ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
621725 ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
621726 RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
621727 "failed a workspace allocation in ZSTD_reset_matchState");
621728
621729 DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
621730 if (crp!=ZSTDcrp_leaveDirty) {
621731 /* reset tables only */
621733 }
621734
621735 if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
621736 /* Row match finder needs an additional table of hashes ("tags") */
621737 size_t const tagTableSize = hSize;
621738 /* We want to generate a new salt in case we reset a Cctx, but we always want to use
621739 * 0 when we reset a Cdict */
621740 if(forWho == ZSTD_resetTarget_CCtx) {
621741 ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize);
621742 ZSTD_advanceHashSalt(ms);
621743 } else {
621744 /* When we are not salting we want to always memset the memory */
621745 ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned(ws, tagTableSize);
621746 ZSTD_memset(ms->tagTable, 0, tagTableSize);
621747 ms->hashSalt = 0;
621748 }
621749 { /* Switch to 32-entry rows if searchLog is 5 (or more) */
621750 U32 const rowLog = BOUNDED(4, cParams->searchLog, 6);
621751 assert(cParams->hashLog >= rowLog);
621752 ms->rowHashLog = cParams->hashLog - rowLog;
621753 }
621754 }
621755
621756 /* opt parser space */
621757 if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
621758 DEBUGLOG(4, "reserving optimal parser space");
621759 ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (1<<Litbits) * sizeof(unsigned));
621760 ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
621761 ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
621762 ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
621763 ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));
621764 ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
621765 }
MEM_STATIC void * ZSTD_cwksp_reserve_table(ZSTD_cwksp *ws, size_t bytes)
Definition duckdb.cpp:617198
MEM_STATIC void * ZSTD_cwksp_reserve_aligned(ZSTD_cwksp *ws, size_t bytes)
Definition duckdb.cpp:617185
MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp *ws)
Definition duckdb.cpp:617299
ZSTD_indexResetPolicy_e
Definition duckdb.cpp:621656
static void ZSTD_invalidateMatchState(ZSTD_matchState_t *ms)
Definition duckdb.cpp:621629
MEM_STATIC void * ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp *ws, size_t bytes)
Definition duckdb.cpp:617161
MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp *ws)
Definition duckdb.cpp:617285
ZSTD_compResetPolicy_e
Definition duckdb.cpp:621646

◆ ZSTD_indexTooCloseToMax()

int duckdb_zstd::ZSTD_indexTooCloseToMax ( ZSTD_window_t w)
static
621775 : prefer memset() rather than reduceIndex()
621776 * which is measurably slow in some circumstances (reported for Visual Studio).
621777 * Works when re-using a context for a lot of smallish inputs :
621778 * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,

◆ ZSTD_dictTooBig()

int duckdb_zstd::ZSTD_dictTooBig ( size_t const loadedDictSize)
static

ZSTD_dictTooBig(): When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in one go generically. So we ensure that in that case we reset the tables to zero, so that we can load as much of the dictionary as possible.

Here is the caller graph for this function:

◆ ZSTD_resetCCtx_internal()

size_t duckdb_zstd::ZSTD_resetCCtx_internal ( ZSTD_CCtx * zc,
ZSTD_CCtx_params const * params,
U64 const pledgedSrcSize,
size_t const loadedDictSize,
ZSTD_compResetPolicy_e const crp,
ZSTD_buffered_policy_e const zbuff )
static

ZSTD_resetCCtx_internal() :

Parameters
loadedDictSizeThe size of the dictionary to be loaded into the context, if any. If no dictionary is used, or the dictionary is being attached / copied, then pass 0. note : params are assumed fully validated at this stage.
621809{
621810 ZSTD_cwksp* const ws = &zc->workspace;
621811 DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d",
621812 (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->useBlockSplitter);
621814
621815 zc->isFirstBlock = 1;
621816
621817 /* Set applied params early so we can modify them for LDM,
621818 * and point params at the applied params.
621819 */
621820 zc->appliedParams = *params;
621821 params = &zc->appliedParams;
621822
621823 assert(params->useRowMatchFinder != ZSTD_ps_auto);
621824 assert(params->useBlockSplitter != ZSTD_ps_auto);
621825 assert(params->ldmParams.enableLdm != ZSTD_ps_auto);
621826 assert(params->maxBlockSize != 0);
621827 if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
621828 /* Adjust long distance matching parameters */
621829 ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, &params->cParams);
621830 assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
621831 assert(params->ldmParams.hashRateLog < 32);
621832 }
621833
621834 { size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
621835 size_t const blockSize = MIN(params->maxBlockSize, windowSize);
621836 size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));
621837 size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
621838 ? ZSTD_compressBound(blockSize) + 1
621839 : 0;
621840 size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
621841 ? windowSize + blockSize
621842 : 0;
621843 size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
621844
621845 int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
621846 int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
621847 ZSTD_indexResetPolicy_e needsIndexReset =
621848 (indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
621849
621850 size_t const neededSpace =
621851 ZSTD_estimateCCtxSize_usingCCtxParams_internal(
621852 &params->cParams, &params->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
621853 buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
621854
621855 FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
621856
621857 if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
621858
621859 { /* Check if workspace is large enough, alloc a new one if needed */
621860 int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
621861 int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
621862 int resizeWorkspace = workspaceTooSmall || workspaceWasteful;
621863 DEBUGLOG(4, "Need %zu B workspace", neededSpace);
621864 DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
621865
621866 if (resizeWorkspace) {
621867 DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
621868 ZSTD_cwksp_sizeof(ws) >> 10,
621869 neededSpace >> 10);
621870
621871 RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
621872
621873 needsIndexReset = ZSTDirp_reset;
621874
621875 ZSTD_cwksp_free(ws, zc->customMem);
621876 FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
621877
621878 DEBUGLOG(5, "reserving object space");
621879 /* Statically sized space.
621880 * entropyWorkspace never moves,
621881 * though prev/next block swap places */
621882 assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
621883 zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
621884 RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
621885 zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
621886 RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
621887 zc->entropyWorkspace = (U32*) ZSTD_cwksp_reserve_object(ws, ENTROPY_WORKSPACE_SIZE);
621888 RETURN_ERROR_IF(zc->entropyWorkspace == NULL, memory_allocation, "couldn't allocate entropyWorkspace");
621889 } }
621890
621891 ZSTD_cwksp_clear(ws);
621892
621893 /* init params */
621894 zc->blockState.matchState.cParams = params->cParams;
621895 zc->blockState.matchState.prefetchCDictTables = params->prefetchCDictTables == ZSTD_ps_enable;
621896 zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
621897 zc->consumedSrcSize = 0;
621898 zc->producedCSize = 0;
621899 if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
621900 zc->appliedParams.fParams.contentSizeFlag = 0;
621901 DEBUGLOG(4, "pledged content size : %u ; flag : %u",
621902 (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
621903 zc->blockSize = blockSize;
621904
621905 XXH64_reset(&zc->xxhState, 0);
621906 zc->stage = ZSTDcs_init;
621907 zc->dictID = 0;
621908 zc->dictContentSize = 0;
621909
621910 ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
621911
621912 FORWARD_IF_ERROR(ZSTD_reset_matchState(
621913 &zc->blockState.matchState,
621914 ws,
621915 &params->cParams,
621916 params->useRowMatchFinder,
621917 crp,
621918 needsIndexReset,
621919 ZSTD_resetTarget_CCtx), "");
621920
621921 zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned(ws, maxNbSeq * sizeof(seqDef));
621922
621923 /* ldm hash table */
621924 if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
621925 /* TODO: avoid memset? */
621926 size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
621927 zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned(ws, ldmHSize * sizeof(ldmEntry_t));
621928 ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
621929 zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned(ws, maxNbLdmSeq * sizeof(rawSeq));
621930 zc->maxNbLdmSequences = maxNbLdmSeq;
621931
621932 ZSTD_window_init(&zc->ldmState.window);
621933 zc->ldmState.loadedDictEnd = 0;
621934 }
621935
621936 /* reserve space for block-level external sequences */
621937 if (ZSTD_hasExtSeqProd(params)) {
621938 size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
621939 zc->extSeqBufCapacity = maxNbExternalSeq;
621940 zc->extSeqBuf =
621941 (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));
621942 }
621943
621944 /* buffers */
621945
621946 /* ZSTD_wildcopy() is used to copy into the literals buffer,
621947 * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
621948 */
621949 zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
621950 zc->seqStore.maxNbLit = blockSize;
621951
621952 zc->bufferedPolicy = zbuff;
621953 zc->inBuffSize = buffInSize;
621954 zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
621955 zc->outBuffSize = buffOutSize;
621956 zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
621957
621958 /* ldm bucketOffsets table */
621959 if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
621960 /* TODO: avoid memset? */
621961 size_t const numBuckets =
621962 ((size_t)1) << (params->ldmParams.hashLog -
621963 params->ldmParams.bucketSizeLog);
621964 zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
621965 ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
621966 }
621967
621968 /* sequences storage */
621969 ZSTD_referenceExternalSequences(zc, NULL, 0);
621970 zc->seqStore.maxNbSeq = maxNbSeq;
621971 zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
621972 zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
621973 zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
621974
621975 DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
static int ZSTD_dictTooBig(size_t const loadedDictSize)
Definition duckdb.cpp:621785
MEM_STATIC BYTE * ZSTD_cwksp_reserve_buffer(ZSTD_cwksp *ws, size_t bytes)
Definition duckdb.cpp:617147
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_shouldAttachDict()

int duckdb_zstd::ZSTD_shouldAttachDict ( const ZSTD_CDict * cdict,
const ZSTD_CCtx_params * params,
U64 pledgedSrcSize )
static
622014{
622015 size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
622016 int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;
622017 return dedicatedDictSearch

◆ ZSTD_resetCCtx_byAttachingCDict()

size_t duckdb_zstd::ZSTD_resetCCtx_byAttachingCDict ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict,
ZSTD_CCtx_params params,
U64 pledgedSrcSize,
ZSTD_buffered_policy_e zbuff )
static
622032{
622033 DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
622034 (unsigned long long)pledgedSrcSize);
622035 {
622036 ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;
622037 unsigned const windowLog = params.cParams.windowLog;
622038 assert(windowLog != 0);
622039 /* Resize working context table params for input only, since the dict
622040 * has its own tables. */
622041 /* pledgedSrcSize == 0 means 0! */
622042
622043 if (cdict->matchState.dedicatedDictSearch) {
622044 ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
622045 }
622046
622047 params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
622048 cdict->dictContentSize, ZSTD_cpm_attachDict,
622049 params.useRowMatchFinder);
622050 params.cParams.windowLog = windowLog;
622051 params.useRowMatchFinder = cdict->useRowMatchFinder; /* cdict overrides */
622052 FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
622053 /* loadedDictSize */ 0,
622054 ZSTDcrp_makeClean, zbuff), "");
622055 assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);
622056 }
622057
622058 { const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
622059 - cdict->matchState.window.base);
622060 const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
622061 if (cdictLen == 0) {
622062 /* don't even attach dictionaries with no contents */
622063 DEBUGLOG(4, "skipping attaching empty dictionary");
622064 } else {
622065 DEBUGLOG(4, "attaching dictionary into context");
622066 cctx->blockState.matchState.dictMatchState = &cdict->matchState;
622067
622068 /* prep working match state so dict matches never have negative indices
622069 * when they are translated to the working context's index space. */
622070 if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
622071 cctx->blockState.matchState.window.nextSrc =
622072 cctx->blockState.matchState.window.base + cdictEnd;
622073 ZSTD_window_clear(&cctx->blockState.matchState.window);
622074 }
622075 /* loadedDictEnd is expressed within the referential of the active context */
622076 cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
622077 } }
622078
622079 cctx->dictID = cdict->dictID;
static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx *zc, ZSTD_CCtx_params const *params, U64 const pledgedSrcSize, size_t const loadedDictSize, ZSTD_compResetPolicy_e const crp, ZSTD_buffered_policy_e const zbuff)
Definition duckdb.cpp:621796
static void ZSTD_dedicatedDictSearch_revertCParams(ZSTD_compressionParameters *cParams)
Definition duckdb.cpp:626866
MEM_STATIC void ZSTD_window_clear(ZSTD_window_t *window)
Definition duckdb.cpp:618449

◆ ZSTD_copyCDictTableIntoCCtx()

void duckdb_zstd::ZSTD_copyCDictTableIntoCCtx ( U32 * dst,
U32 const * src,
size_t tableSize,
ZSTD_compressionParameters const * cParams )
static
622089 {
622090 if (ZSTD_CDictIndicesAreTagged(cParams)){
622091 /* Remove tags from the CDict table if they are present.
622092 * See docs on "short cache" in zstd_compress_internal.h for context. */
622093 size_t i;
622094 for (i = 0; i < tableSize; i++) {
622095 U32 const taggedIndex = src[i];

◆ ZSTD_resetCCtx_byCopyingCDict()

size_t duckdb_zstd::ZSTD_resetCCtx_byCopyingCDict ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict,
ZSTD_CCtx_params params,
U64 pledgedSrcSize,
ZSTD_buffered_policy_e zbuff )
static
622099 {
622100 ZSTD_memcpy(dst, src, tableSize * sizeof(U32));
622101 }
622102}
622103
622104static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
622105 const ZSTD_CDict* cdict,
622106 ZSTD_CCtx_params params,
622107 U64 pledgedSrcSize,
622109{
622110 const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
622111
622112 assert(!cdict->matchState.dedicatedDictSearch);
622113 DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
622114 (unsigned long long)pledgedSrcSize);
622115
622116 { unsigned const windowLog = params.cParams.windowLog;
622117 assert(windowLog != 0);
622118 /* Copy only compression parameters related to tables. */
622119 params.cParams = *cdict_cParams;
622120 params.cParams.windowLog = windowLog;
622121 params.useRowMatchFinder = cdict->useRowMatchFinder;
622122 FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
622123 /* loadedDictSize */ 0,
622124 ZSTDcrp_leaveDirty, zbuff), "");
622125 assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
622126 assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
622127 assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
622128 }
622129
622130 ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
622131 assert(params.useRowMatchFinder != ZSTD_ps_auto);
622132
622133 /* copy tables */
622134 { size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
622135 ? ((size_t)1 << cdict_cParams->chainLog)
622136 : 0;
622137 size_t const hSize = (size_t)1 << cdict_cParams->hashLog;
622138
622139 ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.hashTable,
622140 cdict->matchState.hashTable,
622141 hSize, cdict_cParams);
622142
622143 /* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
622144 if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
622145 ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.chainTable,
622146 cdict->matchState.chainTable,
622147 chainSize, cdict_cParams);
622148 }
622149 /* copy tag table */
622150 if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
622151 size_t const tagTableSize = hSize;
622152 ZSTD_memcpy(cctx->blockState.matchState.tagTable,
622153 cdict->matchState.tagTable,
622154 tagTableSize);
622155 cctx->blockState.matchState.hashSalt = cdict->matchState.hashSalt;
622156 }
622157 }
622158
622159 /* Zero the hashTable3, since the cdict never fills it */
622160 { int const h3log = cctx->blockState.matchState.hashLog3;
622161 size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
622162 assert(cdict->matchState.hashLog3 == 0);
622163 ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
622164 }
622165
622166 ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
622167
622168 /* copy dictionary offsets */
622169 { ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
622170 ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
622171 dstMatchState->window = srcMatchState->window;
622172 dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
622173 dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
622174 }
622175
622176 cctx->dictID = cdict->dictID;

◆ ZSTD_resetCCtx_usingCDict()

size_t duckdb_zstd::ZSTD_resetCCtx_usingCDict ( ZSTD_CCtx * cctx,
const ZSTD_CDict * cdict,
const ZSTD_CCtx_params * params,
U64 pledgedSrcSize,
ZSTD_buffered_policy_e zbuff )
static
622193{
622194
622195 DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
622196 (unsigned)pledgedSrcSize);
622197
622198 if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {

◆ ZSTD_copyCCtx_internal()

size_t duckdb_zstd::ZSTD_copyCCtx_internal ( ZSTD_CCtx * dstCCtx,
const ZSTD_CCtx * srcCCtx,
ZSTD_frameParameters fParams,
U64 pledgedSrcSize,
ZSTD_buffered_policy_e zbuff )
static

ZSTD_copyCCtx_internal() : Duplicate an existing context srcCCtx into another one dstCCtx. Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). The "context", in this case, refers to the hash and chain tables, entropy tables, and dictionary references. windowLog value is enforced if != 0, otherwise value is copied from srcCCtx.

Returns
: 0, or an error code
622219{
622220 RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
622221 "Can't copy a ctx that's not in init stage.");
622222 DEBUGLOG(5, "ZSTD_copyCCtx_internal");
622223 ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
622224 { ZSTD_CCtx_params params = dstCCtx->requestedParams;
622225 /* Copy only compression parameters related to tables. */
622226 params.cParams = srcCCtx->appliedParams.cParams;
622227 assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);
622228 assert(srcCCtx->appliedParams.useBlockSplitter != ZSTD_ps_auto);
622229 assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);
622230 params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
622231 params.useBlockSplitter = srcCCtx->appliedParams.useBlockSplitter;
622232 params.ldmParams = srcCCtx->appliedParams.ldmParams;
622233 params.fParams = fParams;
622234 params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;
622235 ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
622236 /* loadedDictSize */ 0,
622237 ZSTDcrp_leaveDirty, zbuff);
622238 assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
622239 assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
622240 assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
622241 assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
622242 assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
622243 }
622244
622245 ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
622246
622247 /* copy tables */
622248 { size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
622249 srcCCtx->appliedParams.useRowMatchFinder,
622250 0 /* forDDSDict */)
622251 ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
622252 : 0;
622253 size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
622254 int const h3log = srcCCtx->blockState.matchState.hashLog3;
622255 size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
622256
622257 ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
622258 srcCCtx->blockState.matchState.hashTable,
622259 hSize * sizeof(U32));
622260 ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
622261 srcCCtx->blockState.matchState.chainTable,
622262 chainSize * sizeof(U32));
622263 ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
622264 srcCCtx->blockState.matchState.hashTable3,
622265 h3Size * sizeof(U32));
622266 }
622267
622268 ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
622269
622270 /* copy dictionary offsets */
622271 {
622272 const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
622273 ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
622274 dstMatchState->window = srcMatchState->window;
622275 dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
622276 dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
622277 }
622278 dstCCtx->dictID = srcCCtx->dictID;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_reduceTable_internal()

FORCE_INLINE_TEMPLATE void duckdb_zstd::ZSTD_reduceTable_internal ( U32 *const table,
U32 const size,
U32 const reducerValue,
int const preserveMark )

ZSTD_reduceTable() : reduce table indexes by reducerValue, or squash to zero. PreserveMark preserves "unsorted mark" for btlazy2 strategy. It must be set to a clear 0/1 value, to remove branch during inlining. Presume table size is a multiple of ZSTD_ROWSIZE to help auto-vectorization

622315{
622316 int const nbRows = (int)size / ZSTD_ROWSIZE;
622317 int cellNb = 0;
622318 int rowNb;
622319 /* Protect special index values < ZSTD_WINDOW_START_INDEX. */
622320 U32 const reducerThreshold = reducerValue + ZSTD_WINDOW_START_INDEX;
622321 assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */
622322 assert(size < (1U<<31)); /* can be casted to int */
622323
622324 for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
622325 int column;
622326 for (column=0; column<ZSTD_ROWSIZE; column++) {
622327 U32 newVal;
622328 if (preserveMark && table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) {
622329 /* This write is pointless, but is required(?) for the compiler
622330 * to auto-vectorize the loop. */
622331 newVal = ZSTD_DUBT_UNSORTED_MARK;
622332 } else if (table[cellNb] < reducerThreshold) {
622333 newVal = 0;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_reduceTable()

void duckdb_zstd::ZSTD_reduceTable ( U32 *const table,
U32 const size,
U32 const reducerValue )
static

◆ ZSTD_reduceTable_btlazy2()

void duckdb_zstd::ZSTD_reduceTable_btlazy2 ( U32 *const table,
U32 const size,
U32 const reducerValue )
static
622343{

◆ ZSTD_reduceIndex()

void duckdb_zstd::ZSTD_reduceIndex ( ZSTD_matchState_t * ms,
ZSTD_CCtx_params const * params,
const U32 reducerValue )
static

ZSTD_reduceIndex() : rescale all indexes to avoid future overflow (indexes are U32)

622348{
622349 ZSTD_reduceTable_internal(table, size, reducerValue, 1);
622350}
622351
622354static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
622355{
622356 { U32 const hSize = (U32)1 << params->cParams.hashLog;
622357 ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
622358 }
622359
622360 if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
622361 U32 const chainSize = (U32)1 << params->cParams.chainLog;
622362 if (params->cParams.strategy == ZSTD_btlazy2)
622363 ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
622364 else
622365 ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
static void ZSTD_reduceIndex(ZSTD_matchState_t *ms, ZSTD_CCtx_params const *params, const U32 reducerValue)
Definition duckdb.cpp:622347
FORCE_INLINE_TEMPLATE void ZSTD_reduceTable_internal(U32 *const table, U32 const size, U32 const reducerValue, int const preserveMark)
Definition duckdb.cpp:622307
Here is the call graph for this function:

◆ ZSTD_useTargetCBlockSize()

int duckdb_zstd::ZSTD_useTargetCBlockSize ( const ZSTD_CCtx_params * cctxParams)
static

◆ ZSTD_blockSplitterEnabled()

int duckdb_zstd::ZSTD_blockSplitterEnabled ( ZSTD_CCtx_params * cctxParams)
static

◆ ZSTD_buildSequencesStatistics()

ZSTD_symbolEncodingTypeStats_t duckdb_zstd::ZSTD_buildSequencesStatistics ( const seqStore_t * seqStorePtr,
size_t nbSeq,
const ZSTD_fseCTables_t * prevEntropy,
ZSTD_fseCTables_t * nextEntropy,
BYTE * dst,
const BYTE *const dstEnd,
ZSTD_strategy strategy,
unsigned * countWorkspace,
void * entropyWorkspace,
size_t entropyWkspSize )
static
622457{
622458 BYTE* const ostart = dst;
622459 const BYTE* const oend = dstEnd;
622460 BYTE* op = ostart;
622461 FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;
622462 FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;
622463 FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;
622464 const BYTE* const ofCodeTable = seqStorePtr->ofCode;
622465 const BYTE* const llCodeTable = seqStorePtr->llCode;
622466 const BYTE* const mlCodeTable = seqStorePtr->mlCode;
622468
622469 stats.lastCountSize = 0;
622470 /* convert length/distances into codes */
622471 stats.longOffsets = ZSTD_seqToCodes(seqStorePtr);
622472 assert(op <= oend);
622473 assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */
622474 /* build CTable for Literal Lengths */
622475 { unsigned max = MaxLL;
622476 size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
622477 DEBUGLOG(5, "Building LL table");
622478 nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;
622479 stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,
622480 countWorkspace, max, mostFrequent, nbSeq,
622481 LLFSELog, prevEntropy->litlengthCTable,
622482 LL_defaultNorm, LL_defaultNormLog,
622483 ZSTD_defaultAllowed, strategy);
622484 assert(set_basic < set_compressed && set_rle < set_compressed);
622485 assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
622486 { size_t const countSize = ZSTD_buildCTable(
622487 op, (size_t)(oend - op),
622488 CTable_LitLength, LLFSELog, (symbolEncodingType_e)stats.LLtype,
622489 countWorkspace, max, llCodeTable, nbSeq,
622490 LL_defaultNorm, LL_defaultNormLog, MaxLL,
622491 prevEntropy->litlengthCTable,
622492 sizeof(prevEntropy->litlengthCTable),
622493 entropyWorkspace, entropyWkspSize);
622494 if (ZSTD_isError(countSize)) {
622495 DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");
622496 stats.size = countSize;
622497 return stats;
622498 }
622499 if (stats.LLtype == set_compressed)
622500 stats.lastCountSize = countSize;
622501 op += countSize;
622502 assert(op <= oend);
622503 } }
622504 /* build CTable for Offsets */
622505 { unsigned max = MaxOff;
622506 size_t const mostFrequent = HIST_countFast_wksp(
622507 countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
622508 /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
622509 ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
622510 DEBUGLOG(5, "Building OF table");
622511 nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;
622512 stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,
622513 countWorkspace, max, mostFrequent, nbSeq,
622514 OffFSELog, prevEntropy->offcodeCTable,
622515 OF_defaultNorm, OF_defaultNormLog,
622516 defaultPolicy, strategy);
622517 assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
622518 { size_t const countSize = ZSTD_buildCTable(
622519 op, (size_t)(oend - op),
622520 CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)stats.Offtype,
622521 countWorkspace, max, ofCodeTable, nbSeq,
622522 OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
622523 prevEntropy->offcodeCTable,
622524 sizeof(prevEntropy->offcodeCTable),
622525 entropyWorkspace, entropyWkspSize);
622526 if (ZSTD_isError(countSize)) {
622527 DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");
622528 stats.size = countSize;
622529 return stats;
622530 }
622531 if (stats.Offtype == set_compressed)
622532 stats.lastCountSize = countSize;
622533 op += countSize;
622534 assert(op <= oend);
622535 } }
622536 /* build CTable for MatchLengths */
622537 { unsigned max = MaxML;
622538 size_t const mostFrequent = HIST_countFast_wksp(
622539 countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
622540 DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
622541 nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;
622542 stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,
622543 countWorkspace, max, mostFrequent, nbSeq,
622544 MLFSELog, prevEntropy->matchlengthCTable,
622545 ML_defaultNorm, ML_defaultNormLog,
622546 ZSTD_defaultAllowed, strategy);
622547 assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
622548 { size_t const countSize = ZSTD_buildCTable(
622549 op, (size_t)(oend - op),
622550 CTable_MatchLength, MLFSELog, (symbolEncodingType_e)stats.MLtype,
622551 countWorkspace, max, mlCodeTable, nbSeq,
622552 ML_defaultNorm, ML_defaultNormLog, MaxML,
622553 prevEntropy->matchlengthCTable,
622554 sizeof(prevEntropy->matchlengthCTable),
622555 entropyWorkspace, entropyWkspSize);
622556 if (ZSTD_isError(countSize)) {
622557 DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");
622558 stats.size = countSize;
622559 return stats;
622560 }
622561 if (stats.MLtype == set_compressed)

◆ ZSTD_entropyCompressSeqStore_internal()

MEM_STATIC size_t duckdb_zstd::ZSTD_entropyCompressSeqStore_internal ( const seqStore_t * seqStorePtr,
const ZSTD_entropyCTables_t * prevEntropy,
ZSTD_entropyCTables_t * nextEntropy,
const ZSTD_CCtx_params * cctxParams,
void * dst,
size_t dstCapacity,
void * entropyWorkspace,
size_t entropyWkspSize,
const int bmi2 )
622584{
622585 ZSTD_strategy const strategy = cctxParams->cParams.strategy;
622586 unsigned* count = (unsigned*)entropyWorkspace;
622587 FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
622588 FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
622589 FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
622590 const seqDef* const sequences = seqStorePtr->sequencesStart;
622591 const size_t nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
622592 const BYTE* const ofCodeTable = seqStorePtr->ofCode;
622593 const BYTE* const llCodeTable = seqStorePtr->llCode;
622594 const BYTE* const mlCodeTable = seqStorePtr->mlCode;
622595 BYTE* const ostart = (BYTE*)dst;
622596 BYTE* const oend = ostart + dstCapacity;
622597 BYTE* op = ostart;
622598 size_t lastCountSize;
622599 int longOffsets = 0;
622600
622601 entropyWorkspace = count + (MaxSeq + 1);
622602 entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);
622603
622604 DEBUGLOG(5, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu, dstCapacity=%zu)", nbSeq, dstCapacity);
622605 ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
622606 assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);
622607
622608 /* Compress literals */
622609 { const BYTE* const literals = seqStorePtr->litStart;
622610 size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
622611 size_t const numLiterals = (size_t)(seqStorePtr->lit - seqStorePtr->litStart);
622612 /* Base suspicion of uncompressibility on ratio of literals to sequences */
622613 unsigned const suspectUncompressible = (numSequences == 0) || (numLiterals / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO);
622614 size_t const litSize = (size_t)(seqStorePtr->lit - literals);
622615
622616 size_t const cSize = ZSTD_compressLiterals(
622617 op, dstCapacity,
622618 literals, litSize,
622619 entropyWorkspace, entropyWkspSize,
622620 &prevEntropy->huf, &nextEntropy->huf,
622621 cctxParams->cParams.strategy,
622622 ZSTD_literalsCompressionIsDisabled(cctxParams),
622623 suspectUncompressible, bmi2);
622624 FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
622625 assert(cSize <= dstCapacity);
622626 op += cSize;
622627 }
622628
622629 /* Sequences Header */
622630 RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
622631 dstSize_tooSmall, "Can't fit seq hdr in output buf!");
622632 if (nbSeq < 128) {
622633 *op++ = (BYTE)nbSeq;
622634 } else if (nbSeq < LONGNBSEQ) {
622635 op[0] = (BYTE)((nbSeq>>8) + 0x80);
622636 op[1] = (BYTE)nbSeq;
622637 op+=2;
622638 } else {
622639 op[0]=0xFF;
622640 MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
622641 op+=3;
622642 }
622643 assert(op <= oend);
622644 if (nbSeq==0) {
622645 /* Copy the old tables over as if we repeated them */
622646 ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
622647 return (size_t)(op - ostart);
622648 }
622649 { BYTE* const seqHead = op++;
622650 /* build stats for sequences */
622651 const ZSTD_symbolEncodingTypeStats_t stats =
622652 ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
622653 &prevEntropy->fse, &nextEntropy->fse,
622654 op, oend,
622655 strategy, count,
622656 entropyWorkspace, entropyWkspSize);
622657 FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
622658 *seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));
622659 lastCountSize = stats.lastCountSize;
622660 op += stats.size;
622661 longOffsets = stats.longOffsets;
622662 }
622663
622664 { size_t const bitstreamSize = ZSTD_encodeSequences(
622665 op, (size_t)(oend - op),
622666 CTable_MatchLength, mlCodeTable,
622667 CTable_OffsetBits, ofCodeTable,
622668 CTable_LitLength, llCodeTable,
622669 sequences, nbSeq,
622670 longOffsets, bmi2);
622671 FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
622672 op += bitstreamSize;
622673 assert(op <= oend);
622674 /* zstd versions <= 1.3.4 mistakenly report corruption when
622675 * FSE_readNCount() receives a buffer < 4 bytes.
622676 * Fixed by https://github.com/facebook/zstd/pull/1146.
622677 * This can happen when the last set_compressed table present is 2
622678 * bytes and the bitstream is only one byte.
622679 * In this exceedingly rare case, we will simply emit an uncompressed
622680 * block, since it isn't worth optimizing.
622681 */
622682 if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {
622683 /* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
622684 assert(lastCountSize + bitstreamSize == 3);
622685 DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
622686 "emitting an uncompressed block.");

◆ ZSTD_entropyCompressSeqStore()

MEM_STATIC size_t duckdb_zstd::ZSTD_entropyCompressSeqStore ( const seqStore_t * seqStorePtr,
const ZSTD_entropyCTables_t * prevEntropy,
ZSTD_entropyCTables_t * nextEntropy,
const ZSTD_CCtx_params * cctxParams,
void * dst,
size_t dstCapacity,
size_t srcSize,
void * entropyWorkspace,
size_t entropyWkspSize,
int bmi2 )
622691 : %u", (unsigned)(op - ostart));
622692 return (size_t)(op - ostart);
622693}
622694
622695MEM_STATIC size_t
622696ZSTD_entropyCompressSeqStore(
622697 const seqStore_t* seqStorePtr,
622698 const ZSTD_entropyCTables_t* prevEntropy,
622699 ZSTD_entropyCTables_t* nextEntropy,
622700 const ZSTD_CCtx_params* cctxParams,
622701 void* dst, size_t dstCapacity,
622702 size_t srcSize,
622703 void* entropyWorkspace, size_t entropyWkspSize,
622704 int bmi2)
622705{
622706 size_t const cSize = ZSTD_entropyCompressSeqStore_internal(
622707 seqStorePtr, prevEntropy, nextEntropy, cctxParams,
622708 dst, dstCapacity,
622709 entropyWorkspace, entropyWkspSize, bmi2);
622710 if (cSize == 0) return 0;
622711 /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
622712 * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
622713 */
622714 if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity)) {
622715 DEBUGLOG(4, "not enough dstCapacity (%zu) for ZSTD_entropyCompressSeqStore_internal()=> do not compress block", dstCapacity);
622716 return 0; /* block not compressed */
622717 }
622718 FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");
622719
622720 /* Check compressibility */
622721 { size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
622722 if (cSize >= maxCSize) return 0; /* block not compressed */
622723 }

◆ ZSTD_storeLastLiterals()

void duckdb_zstd::ZSTD_storeLastLiterals ( seqStore_t * seqStorePtr,
const BYTE * anchor,
size_t lastLLSize )
static
622813 {
622814 selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
622815 }
622816 assert(selectedCompressor != NULL);
622817 return selectedCompressor;
622818}

◆ ZSTD_postProcessSequenceProducerResult()

size_t duckdb_zstd::ZSTD_postProcessSequenceProducerResult ( ZSTD_Sequence * outSeqs,
size_t nbExternalSeqs,
size_t outSeqsCapacity,
size_t srcSize )
static
622842 {
622844 nbExternalSeqs > outSeqsCapacity,
622845 sequenceProducer_failed,
622846 "External sequence producer returned error code %lu",
622847 (unsigned long)nbExternalSeqs
622848 );
622849
622851 nbExternalSeqs == 0 && srcSize > 0,
622852 sequenceProducer_failed,
622853 "Got zero sequences from external sequence producer for a non-empty src buffer!"
622854 );
622855
622856 if (srcSize == 0) {
622857 ZSTD_memset(&outSeqs[0], 0, sizeof(ZSTD_Sequence));
622858 return 1;
622859 }
622860
622861 {
622862 ZSTD_Sequence const lastSeq = outSeqs[nbExternalSeqs - 1];
622863
622864 /* We can return early if lastSeq is already a block delimiter. */
622865 if (lastSeq.offset == 0 && lastSeq.matchLength == 0) {
622866 return nbExternalSeqs;
622867 }
622868
622869 /* This error condition is only possible if the external matchfinder
622870 * produced an invalid parse, by definition of ZSTD_sequenceBound(). */
622872 nbExternalSeqs == outSeqsCapacity,
622873 sequenceProducer_failed,
622874 "nbExternalSeqs == outSeqsCapacity but lastSeq is not a block delimiter!"

◆ ZSTD_fastSequenceLengthSum()

size_t duckdb_zstd::ZSTD_fastSequenceLengthSum ( ZSTD_Sequence const * seqBuf,
size_t seqBufSize )
static
622889 {
622890 size_t matchLenSum, litLenSum, i;
622891 matchLenSum = 0;

◆ ZSTD_buildSeqStore()

size_t duckdb_zstd::ZSTD_buildSeqStore ( ZSTD_CCtx * zc,
const void * src,
size_t srcSize )
static
622900 { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e;
622901
622902static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
622903{
622904 ZSTD_matchState_t* const ms = &zc->blockState.matchState;
622905 DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
622906 assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
622907 /* Assert that we have correctly flushed the ctx params into the ms's copy */
622908 ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
622909 /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
622910 * additional 1. We need to revisit and change this logic to be more consistent */
622911 if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
622912 if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
622913 ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
622914 } else {
622915 ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
622916 }
622917 return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
622918 }
622919 ZSTD_resetSeqStore(&(zc->seqStore));
622920 /* required for optimal parser to read stats from dictionary */
622921 ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
622922 /* tell the optimal parser how we expect to compress literals */
622923 ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
622924 /* a gap between an attached dict and the current window is not safe,
622925 * they must remain adjacent,
622926 * and when that stops being the case, the dict must be unset */
622927 assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
622928
622929 /* limited update after a very long match */
622930 { const BYTE* const base = ms->window.base;
622931 const BYTE* const istart = (const BYTE*)src;
622932 const U32 curr = (U32)(istart-base);
622933 if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */
622934 if (curr > ms->nextToUpdate + 384)
622935 ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
622936 }
622937
622938 /* select and store sequences */
622939 { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
622940 size_t lastLLSize;
622941 { int i;
622942 for (i = 0; i < ZSTD_REP_NUM; ++i)
622943 zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
622944 }
622945 if (zc->externSeqStore.pos < zc->externSeqStore.size) {
622946 assert(zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_disable);
622947
622948 /* External matchfinder + LDM is technically possible, just not implemented yet.
622949 * We need to revisit soon and implement it. */
622951 ZSTD_hasExtSeqProd(&zc->appliedParams),
622952 parameter_combination_unsupported,
622953 "Long-distance matching with external sequence producer enabled is not currently supported."
622954 );
622955
622956 /* Updates ldmSeqStore.pos */
622957 lastLLSize =
622958 ZSTD_ldm_blockCompress(&zc->externSeqStore,
622959 ms, &zc->seqStore,
622960 zc->blockState.nextCBlock->rep,
622961 zc->appliedParams.useRowMatchFinder,
622962 src, srcSize);
622963 assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
622964 } else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
622965 rawSeqStore_t ldmSeqStore = kNullRawSeqStore;
622966
622967 /* External matchfinder + LDM is technically possible, just not implemented yet.
622968 * We need to revisit soon and implement it. */
622970 ZSTD_hasExtSeqProd(&zc->appliedParams),
622971 parameter_combination_unsupported,
622972 "Long-distance matching with external sequence producer enabled is not currently supported."
622973 );
622974
622975 ldmSeqStore.seq = zc->ldmSequences;
622976 ldmSeqStore.capacity = zc->maxNbLdmSequences;
622977 /* Updates ldmSeqStore.size */
622978 FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
622979 &zc->appliedParams.ldmParams,
622980 src, srcSize), "");
622981 /* Updates ldmSeqStore.pos */
622982 lastLLSize =
622983 ZSTD_ldm_blockCompress(&ldmSeqStore,
622984 ms, &zc->seqStore,
622985 zc->blockState.nextCBlock->rep,
622986 zc->appliedParams.useRowMatchFinder,
622987 src, srcSize);
622988 assert(ldmSeqStore.pos == ldmSeqStore.size);
622989 } else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {
622990 assert(
622991 zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)
622992 );
622993 assert(zc->appliedParams.extSeqProdFunc != NULL);
622994
622995 { U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;
622996
622997 size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(
622998 zc->appliedParams.extSeqProdState,
622999 zc->extSeqBuf,
623000 zc->extSeqBufCapacity,
623001 src, srcSize,
623002 NULL, 0, /* dict and dictSize, currently not supported */
623003 zc->appliedParams.compressionLevel,
623004 windowSize
623005 );
623006
623007 size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
623008 zc->extSeqBuf,
623009 nbExternalSeqs,
623010 zc->extSeqBufCapacity,
623011 srcSize
623012 );
623013
623014 /* Return early if there is no error, since we don't need to worry about last literals */
623015 if (!ZSTD_isError(nbPostProcessedSeqs)) {
623016 ZSTD_sequencePosition seqPos = {0,0,0};
623017 size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);
623018 RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");
623020 ZSTD_copySequencesToSeqStoreExplicitBlockDelim(
623021 zc, &seqPos,
623022 zc->extSeqBuf, nbPostProcessedSeqs,
623023 src, srcSize,
623024 zc->appliedParams.searchForExternalRepcodes
623025 ),
623026 "Failed to copy external sequences to seqStore!"
623027 );
623028 ms->ldmSeqStore = NULL;
623029 DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.", (unsigned long)nbExternalSeqs);
623030 return ZSTDbss_compress;
623031 }
623032
623033 /* Propagate the error if fallback is disabled */
623034 if (!zc->appliedParams.enableMatchFinderFallback) {
623035 return nbPostProcessedSeqs;
623036 }
623037
623038 /* Fallback to software matchfinder */
623039 { ZSTD_blockCompressor const blockCompressor =
623040 ZSTD_selectBlockCompressor(
623041 zc->appliedParams.cParams.strategy,
623042 zc->appliedParams.useRowMatchFinder,
623043 dictMode);
623044 ms->ldmSeqStore = NULL;
623045 DEBUGLOG(
623046 5,
623047 "External sequence producer returned error code %lu. Falling back to internal parser.",
623048 (unsigned long)nbExternalSeqs
623049 );
623050 lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
623051 } }
623052 } else { /* not long range mode and no external matchfinder */
623053 ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(
623054 zc->appliedParams.cParams.strategy,
623055 zc->appliedParams.useRowMatchFinder,
623056 dictMode);
623057 ms->ldmSeqStore = NULL;
void ZSTD_ldm_skipSequences(rawSeqStore_t *rawSeqStore, size_t srcSize, U32 const minMatch)
Definition duckdb.cpp:633095

◆ ZSTD_copyBlockSequences()

size_t duckdb_zstd::ZSTD_copyBlockSequences ( SeqCollector * seqCollector,
const seqStore_t * seqStore,
const U32 prevRepcodes[ZSTD_REP_NUM] )
static
623060 { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
623061 ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
623062 } }
623063 return ZSTDbss_compress;
623064}
623065
623066static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const seqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])
623067{
623068 const seqDef* inSeqs = seqStore->sequencesStart;
623069 const size_t nbInSequences = seqStore->sequences - inSeqs;
623070 const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart);
623071
623072 ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex;
623073 const size_t nbOutSequences = nbInSequences + 1;
623074 size_t nbOutLiterals = 0;
623075 repcodes_t repcodes;
623076 size_t i;
623077
623078 /* Bounds check that we have enough space for every input sequence
623079 * and the block delimiter
623080 */
623081 assert(seqCollector->seqIndex <= seqCollector->maxSequences);
623083 nbOutSequences > (size_t)(seqCollector->maxSequences - seqCollector->seqIndex),
623084 dstSize_tooSmall,
623085 "Not enough space to copy sequences");
623086
623087 ZSTD_memcpy(&repcodes, prevRepcodes, sizeof(repcodes));
623088 for (i = 0; i < nbInSequences; ++i) {
623089 U32 rawOffset;
623090 outSeqs[i].litLength = inSeqs[i].litLength;
623091 outSeqs[i].matchLength = inSeqs[i].mlBase + MINMATCH;
623092 outSeqs[i].rep = 0;
623093
623094 /* Handle the possible single length >= 64K
623095 * There can only be one because we add MINMATCH to every match length,
623096 * and blocks are at most 128K.
623097 */
623098 if (i == seqStore->longLengthPos) {
623099 if (seqStore->longLengthType == ZSTD_llt_literalLength) {
623100 outSeqs[i].litLength += 0x10000;
623101 } else if (seqStore->longLengthType == ZSTD_llt_matchLength) {
623102 outSeqs[i].matchLength += 0x10000;
623103 }
623104 }
623105
623106 /* Determine the raw offset given the offBase, which may be a repcode. */
623107 if (OFFBASE_IS_REPCODE(inSeqs[i].offBase)) {
623108 const U32 repcode = OFFBASE_TO_REPCODE(inSeqs[i].offBase);
623109 assert(repcode > 0);
623110 outSeqs[i].rep = repcode;
623111 if (outSeqs[i].litLength != 0) {
623112 rawOffset = repcodes.rep[repcode - 1];
623113 } else {
623114 if (repcode == 3) {
623115 assert(repcodes.rep[0] > 1);
623116 rawOffset = repcodes.rep[0] - 1;
623117 } else {
623118 rawOffset = repcodes.rep[repcode];
623119 }
623120 }
623121 } else {
623122 rawOffset = OFFBASE_TO_OFFSET(inSeqs[i].offBase);
623123 }
623124 outSeqs[i].offset = rawOffset;
623125
623126 /* Update repcode history for the sequence */
623127 ZSTD_updateRep(repcodes.rep,
623128 inSeqs[i].offBase,
623129 inSeqs[i].litLength == 0);
623130
623131 nbOutLiterals += outSeqs[i].litLength;
623132 }
623133 /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.
623134 * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker
623135 * for the block boundary, according to the API.
623136 */
623137 assert(nbInLiterals >= nbOutLiterals);
623138 {
623139 const size_t lastLLSize = nbInLiterals - nbOutLiterals;
623140 outSeqs[nbInSequences].litLength = (U32)lastLLSize;
623141 outSeqs[nbInSequences].matchLength = 0;
623142 outSeqs[nbInSequences].offset = 0;
Definition duckdb.cpp:617814

◆ ZSTD_isRLE()

int duckdb_zstd::ZSTD_isRLE ( const BYTE * src,
size_t length )
static
623208 {
623209 const BYTE* ip = src;
623210 const BYTE value = ip[0];
623211 const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);
623212 const size_t unrollSize = sizeof(size_t) * 4;
623213 const size_t unrollMask = unrollSize - 1;
623214 const size_t prefixLength = length & unrollMask;
623215 size_t i;
623216 if (length == 1) return 1;
623217 /* Check if prefix is RLE first before using unrolled loop */
623218 if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {
623219 return 0;
623220 }
623221 for (i = prefixLength; i != length; i += unrollSize) {

◆ ZSTD_maybeRLE()

int duckdb_zstd::ZSTD_maybeRLE ( seqStore_t const * seqStore)
static

◆ ZSTD_blockState_confirmRepcodesAndEntropyTables()

void duckdb_zstd::ZSTD_blockState_confirmRepcodesAndEntropyTables ( ZSTD_blockState_t *const bs)
static

◆ writeBlockHeader()

void duckdb_zstd::writeBlockHeader ( void * op,
size_t cSize,
size_t blockSize,
U32 lastBlock )
static

◆ ZSTD_buildBlockEntropyStats_literals()

size_t duckdb_zstd::ZSTD_buildBlockEntropyStats_literals ( void *const src,
size_t srcSize,
const ZSTD_hufCTables_t * prevHuf,
ZSTD_hufCTables_t * nextHuf,
ZSTD_hufCTablesMetadata_t * hufMetadata,
const int literalsCompressionIsDisabled,
void * workspace,
size_t wkspSize,
int hufFlags )
static

ZSTD_buildBlockEntropyStats_literals() : Builds entropy for the literals. Stores literals block type (raw, rle, compressed, repeat) and huffman description table to hufMetadata. Requires ENTROPY_WORKSPACE_SIZE workspace

Returns
: size of huffman description table, or an error code
623266 : size of huffman description table, or an error code
623267 */
623268static size_t
623269ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,
623270 const ZSTD_hufCTables_t* prevHuf,
623271 ZSTD_hufCTables_t* nextHuf,
623272 ZSTD_hufCTablesMetadata_t* hufMetadata,
623273 const int literalsCompressionIsDisabled,
623274 void* workspace, size_t wkspSize,
623275 int hufFlags)
623276{
623277 BYTE* const wkspStart = (BYTE*)workspace;
623278 BYTE* const wkspEnd = wkspStart + wkspSize;
623279 BYTE* const countWkspStart = wkspStart;
623280 unsigned* const countWksp = (unsigned*)workspace;
623281 const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);
623282 BYTE* const nodeWksp = countWkspStart + countWkspSize;
623283 const size_t nodeWkspSize = (size_t)(wkspEnd - nodeWksp);
623284 unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
623285 unsigned huffLog = LitHufLog;
623286 HUF_repeat repeat = prevHuf->repeatMode;
623287 DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);
623288
623289 /* Prepare nextEntropy assuming reusing the existing table */
623290 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
623291
623292 if (literalsCompressionIsDisabled) {
623293 DEBUGLOG(5, "set_basic - disabled");
623294 hufMetadata->hType = set_basic;
623295 return 0;
623296 }
623297
623298 /* small ? don't even attempt compression (speed opt) */
623299#ifndef COMPRESS_LITERALS_SIZE_MIN
623300# define COMPRESS_LITERALS_SIZE_MIN 63 /* heuristic */
623301#endif
623302 { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
623303 if (srcSize <= minLitSize) {
623304 DEBUGLOG(5, "set_basic - too small");
623305 hufMetadata->hType = set_basic;
623306 return 0;
623307 } }
623308
623309 /* Scan input and build symbol stats */
623310 { size_t const largest =
623311 HIST_count_wksp (countWksp, &maxSymbolValue,
623312 (const BYTE*)src, srcSize,
623313 workspace, wkspSize);
623314 FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");
623315 if (largest == srcSize) {
623316 /* only one literal symbol */
623317 DEBUGLOG(5, "set_rle");
623318 hufMetadata->hType = set_rle;
623319 return 0;
623320 }
623321 if (largest <= (srcSize >> 7)+4) {
623322 /* heuristic: likely not compressible */
623323 DEBUGLOG(5, "set_basic - no gain");
623324 hufMetadata->hType = set_basic;
623325 return 0;
623326 } }
623327
623328 /* Validate the previous Huffman table */
623329 if (repeat == HUF_repeat_check
623330 && !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {
623332 }
623333
623334 /* Build Huffman Tree */
623335 ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));
623336 huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, nodeWksp, nodeWkspSize, nextHuf->CTable, countWksp, hufFlags);
623337 assert(huffLog <= LitHufLog);
623338 { size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,
623339 maxSymbolValue, huffLog,
623340 nodeWksp, nodeWkspSize);
623341 FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");
623342 huffLog = (U32)maxBits;
623343 }
623344 { /* Build and write the CTable */
623345 size_t const newCSize = HUF_estimateCompressedSize(
623346 (HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);
623347 size_t const hSize = HUF_writeCTable_wksp(
623348 hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),
623349 (HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,
623350 nodeWksp, nodeWkspSize);
623351 /* Check against repeating the previous CTable */
623352 if (repeat != HUF_repeat_none) {
623353 size_t const oldCSize = HUF_estimateCompressedSize(
623354 (HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);
623355 if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {
623356 DEBUGLOG(5, "set_repeat - smaller");
623357 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
623358 hufMetadata->hType = set_repeat;
623359 return 0;
623360 } }
623361 if (newCSize + hSize >= srcSize) {
623362 DEBUGLOG(5, "set_basic - no gains");
623363 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
623364 hufMetadata->hType = set_basic;
623365 return 0;
Definition duckdb.cpp:617607
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_buildDummySequencesStatistics()

ZSTD_symbolEncodingTypeStats_t duckdb_zstd::ZSTD_buildDummySequencesStatistics ( ZSTD_fseCTables_t * nextEntropy)
static

◆ ZSTD_buildBlockEntropyStats_sequences()

size_t duckdb_zstd::ZSTD_buildBlockEntropyStats_sequences ( const seqStore_t * seqStorePtr,
const ZSTD_fseCTables_t * prevEntropy,
ZSTD_fseCTables_t * nextEntropy,
const ZSTD_CCtx_params * cctxParams,
ZSTD_fseCTablesMetadata_t * fseMetadata,
void * workspace,
size_t wkspSize )
static

ZSTD_buildBlockEntropyStats_sequences() : Builds entropy for the sequences. Stores symbol compression modes and fse table to fseMetadata. Requires ENTROPY_WORKSPACE_SIZE wksp.

Returns
: size of fse tables or error code
623402{
623403 ZSTD_strategy const strategy = cctxParams->cParams.strategy;
623404 size_t const nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
623405 BYTE* const ostart = fseMetadata->fseTablesBuffer;
623406 BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);
623407 BYTE* op = ostart;
623408 unsigned* countWorkspace = (unsigned*)workspace;
623409 unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);
623410 size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);
623412
623413 DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);
623414 stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
623415 prevEntropy, nextEntropy, op, oend,
623416 strategy, countWorkspace,
623417 entropyWorkspace, entropyWorkspaceSize)
623418 : ZSTD_buildDummySequencesStatistics(nextEntropy);
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_estimateBlockSize_literal()

size_t duckdb_zstd::ZSTD_estimateBlockSize_literal ( const BYTE * literals,
size_t litSize,
const ZSTD_hufCTables_t * huf,
const ZSTD_hufCTablesMetadata_t * hufMetadata,
void * workspace,
size_t wkspSize,
int writeEntropy )
static
623471{
623472 unsigned* const countWksp = (unsigned*)workspace;
623473 unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
623474 size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);
623475 U32 singleStream = litSize < 256;
623476
623477 if (hufMetadata->hType == set_basic) return litSize;
623478 else if (hufMetadata->hType == set_rle) return 1;
623479 else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
623480 size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
623481 if (ZSTD_isError(largest)) return litSize;
623482 { size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);

◆ ZSTD_estimateBlockSize_symbolType()

size_t duckdb_zstd::ZSTD_estimateBlockSize_symbolType ( symbolEncodingType_e type,
const BYTE * codeTable,
size_t nbSeq,
unsigned maxCode,
const FSE_CTable * fseCTable,
const U8 * additionalBits,
short const * defaultNorm,
U32 defaultNormLog,
U32 defaultMax,
void * workspace,
size_t wkspSize )
static
623499{
623500 unsigned* const countWksp = (unsigned*)workspace;
623501 const BYTE* ctp = codeTable;
623502 const BYTE* const ctStart = ctp;
623503 const BYTE* const ctEnd = ctStart + nbSeq;
623504 size_t cSymbolTypeSizeEstimateInBits = 0;
623505 unsigned max = maxCode;
623506
623507 HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */
623508 if (type == set_basic) {
623509 /* We selected this encoding type, so it must be valid. */
623510 assert(max <= defaultMax);
623511 (void)defaultMax;
623512 cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
623513 } else if (type == set_rle) {
623514 cSymbolTypeSizeEstimateInBits = 0;
623515 } else if (type == set_compressed || type == set_repeat) {
623516 cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
623517 }
623518 if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {
623519 return nbSeq * 10;
623520 }

◆ ZSTD_estimateBlockSize_sequences()

size_t duckdb_zstd::ZSTD_estimateBlockSize_sequences ( const BYTE * ofCodeTable,
const BYTE * llCodeTable,
const BYTE * mlCodeTable,
size_t nbSeq,
const ZSTD_fseCTables_t * fseTables,
const ZSTD_fseCTablesMetadata_t * fseMetadata,
void * workspace,
size_t wkspSize,
int writeEntropy )
static
623539{
623540 size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);
623541 size_t cSeqSizeEstimate = 0;
623542 cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,
623543 fseTables->offcodeCTable, NULL,
623544 OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
623545 workspace, wkspSize);
623546 cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,
623547 fseTables->litlengthCTable, LL_bits,
623548 LL_defaultNorm, LL_defaultNormLog, MaxLL,
623549 workspace, wkspSize);

◆ ZSTD_estimateBlockSize()

size_t duckdb_zstd::ZSTD_estimateBlockSize ( const BYTE * literals,
size_t litSize,
const BYTE * ofCodeTable,
const BYTE * llCodeTable,
const BYTE * mlCodeTable,
size_t nbSeq,
const ZSTD_entropyCTables_t * entropy,
const ZSTD_entropyCTablesMetadata_t * entropyMetadata,
void * workspace,
size_t wkspSize,
int writeLitEntropy,
int writeSeqEntropy )
static
623569{
623570 size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,

◆ ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()

size_t duckdb_zstd::ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize ( seqStore_t * seqStore,
ZSTD_CCtx * zc )
static
623585{
623586 ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata;
623587 DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()");
623589 &zc->blockState.prevCBlock->entropy,
623590 &zc->blockState.nextCBlock->entropy,
623591 &zc->appliedParams,
623592 entropyMetadata,
623593 zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE), "");
623594 return ZSTD_estimateBlockSize(
623595 seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
size_t ZSTD_buildBlockEntropyStats(const seqStore_t *seqStorePtr, const ZSTD_entropyCTables_t *prevEntropy, ZSTD_entropyCTables_t *nextEntropy, const ZSTD_CCtx_params *cctxParams, ZSTD_entropyCTablesMetadata_t *entropyMetadata, void *workspace, size_t wkspSize)
Definition duckdb.cpp:623427
Definition duckdb.cpp:617627

◆ ZSTD_countSeqStoreLiteralsBytes()

size_t duckdb_zstd::ZSTD_countSeqStoreLiteralsBytes ( const seqStore_t *const seqStore)
static
623606{
623607 size_t literalsBytes = 0;
623608 size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
623609 size_t i;
623610 for (i = 0; i < nbSeqs; ++i) {

◆ ZSTD_countSeqStoreMatchBytes()

size_t duckdb_zstd::ZSTD_countSeqStoreMatchBytes ( const seqStore_t *const seqStore)
static
623613 {
623614 literalsBytes += 0x10000;
623615 } }
623616 return literalsBytes;
623617}
623618
623619/* Returns match bytes represented in a seqStore */
623620static size_t ZSTD_countSeqStoreMatchBytes(const seqStore_t* const seqStore)
623621{
623622 size_t matchBytes = 0;
623623 size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
623624 size_t i;
623625 for (i = 0; i < nbSeqs; ++i) {

◆ ZSTD_deriveSeqStoreChunk()

void duckdb_zstd::ZSTD_deriveSeqStoreChunk ( seqStore_t * resultSeqStore,
const seqStore_t * originalSeqStore,
size_t startIdx,
size_t endIdx )
static
623640{
623641 *resultSeqStore = *originalSeqStore;
623642 if (startIdx > 0) {
623643 resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;
623644 resultSeqStore->litStart += ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
623645 }
623646
623647 /* Move longLengthPos into the correct position if necessary */
623648 if (originalSeqStore->longLengthType != ZSTD_llt_none) {
623649 if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
623650 resultSeqStore->longLengthType = ZSTD_llt_none;
623651 } else {
623652 resultSeqStore->longLengthPos -= (U32)startIdx;
623653 }
623654 }
623655 resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;
623656 resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;
623657 if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {
623658 /* This accounts for possible last literals if the derived chunk reaches the end of the block */
623659 assert(resultSeqStore->lit == originalSeqStore->lit);
623660 } else {

◆ ZSTD_resolveRepcodeToRawOffset()

U32 duckdb_zstd::ZSTD_resolveRepcodeToRawOffset ( const U32 rep[ZSTD_REP_NUM],
const U32 offBase,
const U32 ll0 )
static

Returns the raw offset represented by the combination of offBase, ll0, and repcode history. offBase must represent a repcode in the numeric representation of ZSTD_storeSeq().

623675{
623676 U32 const adjustedRepCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0; /* [ 0 - 3 ] */
623677 assert(OFFBASE_IS_REPCODE(offBase));
623678 if (adjustedRepCode == ZSTD_REP_NUM) {
623679 assert(ll0);
623680 /* litlength == 0 and offCode == 2 implies selection of first repcode - 1
623681 * This is only valid if it results in a valid offset value, aka > 0.
623682 * Note : it may happen that `rep[0]==1` in exceptional circumstances.
623683 * In which case this function will return 0, which is an invalid offset.
Here is the caller graph for this function:

◆ ZSTD_seqStore_resolveOffCodes()

void duckdb_zstd::ZSTD_seqStore_resolveOffCodes ( repcodes_t *const dRepcodes,
repcodes_t *const cRepcodes,
const seqStore_t *const seqStore,
U32 const nbSeq )
static

ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise due to emission of RLE/raw blocks that disturb the offset history, and replaces any repcodes within the seqStore that may be invalid.

dRepcodes are updated as would be on the decompression side. cRepcodes are updated exactly in accordance with the seqStore.

Note : this function assumes seq->offBase respects the following numbering scheme : 0 : invalid 1-3 : repcode 1-3 4+ : real_offset+3

623700 : this function assumes seq->offBase respects the following numbering scheme :
623701 * 0 : invalid
623702 * 1-3 : repcode 1-3
623703 * 4+ : real_offset+3
623704 */
623705static void
623706ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRepcodes,
623707 const seqStore_t* const seqStore, U32 const nbSeq)
623708{
623709 U32 idx = 0;
623710 U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq;
623711 for (; idx < nbSeq; ++idx) {
623712 seqDef* const seq = seqStore->sequencesStart + idx;
623713 U32 const ll0 = (seq->litLength == 0) && (idx != longLitLenIdx);
623714 U32 const offBase = seq->offBase;
623715 assert(offBase > 0);
623716 if (OFFBASE_IS_REPCODE(offBase)) {
623717 U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offBase, ll0);
623718 U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offBase, ll0);
623719 /* Adjust simulated decompression repcode history if we come across a mismatch. Replace
623720 * the repcode with the offset it actually references, determined by the compression
623721 * repcode history.
623722 */
623723 if (dRawOffset != cRawOffset) {
623724 seq->offBase = OFFSET_TO_OFFBASE(cRawOffset);
623725 }
623726 }
static void ZSTD_seqStore_resolveOffCodes(repcodes_t *const dRepcodes, repcodes_t *const cRepcodes, const seqStore_t *const seqStore, U32 const nbSeq)
Definition duckdb.cpp:623699
static U32 ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, const U32 ll0)
Definition duckdb.cpp:623667
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressSeqStore_singleBlock()

size_t duckdb_zstd::ZSTD_compressSeqStore_singleBlock ( ZSTD_CCtx * zc,
const seqStore_t *const seqStore,
repcodes_t *const dRep,
repcodes_t *const cRep,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 lastBlock,
U32 isPartition )
static
623747{
623748 const U32 rleMaxLength = 25;
623749 BYTE* op = (BYTE*)dst;
623750 const BYTE* ip = (const BYTE*)src;
623751 size_t cSize;
623752 size_t cSeqsSize;
623753
623754 /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
623755 repcodes_t const dRepOriginal = *dRep;
623756 DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock");
623757 if (isPartition)
623758 ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
623759
623760 RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit");
623761 cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
623762 &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
623763 &zc->appliedParams,
623764 op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
623765 srcSize,
623766 zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
623767 zc->bmi2);
623768 FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
623769
623770 if (!zc->isFirstBlock &&
623771 cSeqsSize < rleMaxLength &&
623772 ZSTD_isRLE((BYTE const*)src, srcSize)) {
623773 /* We don't want to emit our first block as a RLE even if it qualifies because
623774 * doing so will cause the decoder (cli only) to throw a "should consume all input error."
623775 * This is only an issue for zstd <= v1.4.3
623776 */
623777 cSeqsSize = 1;
623778 }
623779
623780 /* Sequence collection not supported when block splitting */
623781 if (zc->seqCollector.collectSequences) {
623782 FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed");
623783 ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
623784 return 0;
623785 }
623786
623787 if (cSeqsSize == 0) {
623788 cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
623789 FORWARD_IF_ERROR(cSize, "Nocompress block failed");
623790 DEBUGLOG(4, "Writing out nocompress block, size: %zu", cSize);
623791 *dRep = dRepOriginal; /* reset simulated decompression repcode history */
623792 } else if (cSeqsSize == 1) {
623793 cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
623794 FORWARD_IF_ERROR(cSize, "RLE compress block failed");
623795 DEBUGLOG(4, "Writing out RLE block, size: %zu", cSize);
623796 *dRep = dRepOriginal; /* reset simulated decompression repcode history */
623797 } else {
623798 ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
623799 writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
623800 cSize = ZSTD_blockHeaderSize + cSeqsSize;
623801 DEBUGLOG(4, "Writing out compressed block, size: %zu", cSize);

◆ ZSTD_deriveBlockSplitsHelper()

void duckdb_zstd::ZSTD_deriveBlockSplitsHelper ( seqStoreSplits * splits,
size_t startIdx,
size_t endIdx,
ZSTD_CCtx * zc,
const seqStore_t * origSeqStore )
static
623835{
623836 seqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk;
623837 seqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore;
623838 seqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore;
623839 size_t estimatedOriginalSize;
623840 size_t estimatedFirstHalfSize;
623841 size_t estimatedSecondHalfSize;
623842 size_t midIdx = (startIdx + endIdx)/2;
623843
623844 DEBUGLOG(5, "ZSTD_deriveBlockSplitsHelper: startIdx=%zu endIdx=%zu", startIdx, endIdx);
623845 assert(endIdx >= startIdx);
623846 if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS) {
623847 DEBUGLOG(6, "ZSTD_deriveBlockSplitsHelper: Too few sequences (%zu)", endIdx - startIdx);
623848 return;
623849 }
623850 ZSTD_deriveSeqStoreChunk(fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
623851 ZSTD_deriveSeqStoreChunk(firstHalfSeqStore, origSeqStore, startIdx, midIdx);
623852 ZSTD_deriveSeqStoreChunk(secondHalfSeqStore, origSeqStore, midIdx, endIdx);
623853 estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(fullSeqStoreChunk, zc);
623854 estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(firstHalfSeqStore, zc);
623855 estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(secondHalfSeqStore, zc);
623856 DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",
623857 estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);
623858 if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {
623859 return;
623860 }
623861 if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
#define ZSTD_MAX_NB_BLOCK_SPLITS
Definition duckdb.cpp:617908

◆ ZSTD_deriveBlockSplits()

size_t duckdb_zstd::ZSTD_deriveBlockSplits ( ZSTD_CCtx * zc,
U32 partitions[],
U32 nbSeq )
static
623876{
623877 seqStoreSplits splits;
623878 splits.splitLocations = partitions;
623879 splits.idx = 0;
623880 if (nbSeq <= 4) {
623881 DEBUGLOG(5, "ZSTD_deriveBlockSplits: Too few sequences to split (%u <= 4)", nbSeq);
623882 /* Refuse to try and split anything with less than 4 sequences */
Definition duckdb.cpp:623804

◆ ZSTD_compressBlock_splitBlock_internal()

size_t duckdb_zstd::ZSTD_compressBlock_splitBlock_internal ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
const void * src,
size_t blockSize,
U32 lastBlock,
U32 nbSeq )
static
623901{
623902 size_t cSize = 0;
623903 const BYTE* ip = (const BYTE*)src;
623904 BYTE* op = (BYTE*)dst;
623905 size_t i = 0;
623906 size_t srcBytesTotal = 0;
623907 U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */
623908 seqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
623909 seqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;
623910 size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
623911
623912 /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
623913 * may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
623914 * separate repcode histories that simulate repcode history on compression and decompression side,
623915 * and use the histories to determine whether we must replace a particular repcode with its raw offset.
623916 *
623917 * 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
623918 * or RLE. This allows us to retrieve the offset value that an invalid repcode references within
623919 * a nocompress/RLE block.
623920 * 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
623921 * the replacement offset value rather than the original repcode to update the repcode history.
623922 * dRep also will be the final repcode history sent to the next block.
623923 *
623924 * See ZSTD_seqStore_resolveOffCodes() for more details.
623925 */
623926 repcodes_t dRep;
623927 repcodes_t cRep;
623928 ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
623929 ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
623930 ZSTD_memset(nextSeqStore, 0, sizeof(seqStore_t));
623931
623932 DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
623933 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
623934 (unsigned)zc->blockState.matchState.nextToUpdate);
623935
623936 if (numSplits == 0) {
623937 size_t cSizeSingleBlock =
623938 ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
623939 &dRep, &cRep,
623940 op, dstCapacity,
623941 ip, blockSize,
623942 lastBlock, 0 /* isPartition */);
623943 FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
623944 DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
623945 assert(zc->blockSize <= ZSTD_BLOCKSIZE_MAX);
623946 assert(cSizeSingleBlock <= zc->blockSize + ZSTD_blockHeaderSize);
623947 return cSizeSingleBlock;
623948 }
623949
623950 ZSTD_deriveSeqStoreChunk(currSeqStore, &zc->seqStore, 0, partitions[0]);
623951 for (i = 0; i <= numSplits; ++i) {
623952 size_t cSizeChunk;
623953 U32 const lastPartition = (i == numSplits);
623954 U32 lastBlockEntireSrc = 0;
623955
623956 size_t srcBytes = ZSTD_countSeqStoreLiteralsBytes(currSeqStore) + ZSTD_countSeqStoreMatchBytes(currSeqStore);
623957 srcBytesTotal += srcBytes;
623958 if (lastPartition) {
623959 /* This is the final partition, need to account for possible last literals */
623960 srcBytes += blockSize - srcBytesTotal;
623961 lastBlockEntireSrc = lastBlock;
623962 } else {
623963 ZSTD_deriveSeqStoreChunk(nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
623964 }
623965
623966 cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, currSeqStore,
623967 &dRep, &cRep,
623968 op, dstCapacity,
623969 ip, srcBytes,
623970 lastBlockEntireSrc, 1 /* isPartition */);
623971 DEBUGLOG(5, "Estimated size: %zu vs %zu : actual size",
623972 ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(currSeqStore, zc), cSizeChunk);
623973 FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
623974
623975 ip += srcBytes;
623976 op += cSizeChunk;
623977 dstCapacity -= cSizeChunk;
623978 cSize += cSizeChunk;
623979 *currSeqStore = *nextSeqStore;
623980 assert(cSizeChunk <= zc->blockSize + ZSTD_blockHeaderSize);

◆ ZSTD_compressBlock_splitBlock()

size_t duckdb_zstd::ZSTD_compressBlock_splitBlock ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 lastBlock )
static
623993{
623994 U32 nbSeq;
623995 size_t cSize;
623996 DEBUGLOG(4, "ZSTD_compressBlock_splitBlock");
623997 assert(zc->appliedParams.useBlockSplitter == ZSTD_ps_enable);
623998
623999 { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
624000 FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
624001 if (bss == ZSTDbss_noCompress) {
624002 if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
624003 zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
624004 RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
624005 cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
624006 FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
624007 DEBUGLOG(4, "ZSTD_compressBlock_splitBlock: Nocompress block");
624008 return cSize;
624009 }

◆ ZSTD_compressBlock_internal()

size_t duckdb_zstd::ZSTD_compressBlock_internal ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 frame )
static
624022{
624023 /* This is an estimated upper bound for the length of an rle block.
624024 * This isn't the actual upper bound.
624025 * Finding the real threshold needs further investigation.
624026 */
624027 const U32 rleMaxLength = 25;
624028 size_t cSize;
624029 const BYTE* ip = (const BYTE*)src;
624030 BYTE* op = (BYTE*)dst;
624031 DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
624032 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
624033 (unsigned)zc->blockState.matchState.nextToUpdate);
624034
624035 { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
624036 FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
624037 if (bss == ZSTDbss_noCompress) {
624038 RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
624039 cSize = 0;
624040 goto out;
624041 }
624042 }
624043
624044 if (zc->seqCollector.collectSequences) {
624045 FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed");
624046 ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
624047 return 0;
624048 }
624049
624050 /* encode sequences and literals */
624051 cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
624052 &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
624053 &zc->appliedParams,
624054 dst, dstCapacity,
624055 srcSize,
624056 zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
624057 zc->bmi2);
624058
624059 if (frame &&
624060 /* We don't want to emit our first block as a RLE even if it qualifies because
624061 * doing so will cause the decoder (cli only) to throw a "should consume all input error."
624062 * This is only an issue for zstd <= v1.4.3
624063 */
624064 !zc->isFirstBlock &&
624065 cSize < rleMaxLength &&
624066 ZSTD_isRLE(ip, srcSize))
624067 {
624068 cSize = 1;
624069 op[0] = ip[0];
624070 }
624071
624072out:
624073 if (!ZSTD_isError(cSize) && cSize > 1) {
624074 ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
624075 }
624076 /* We check that dictionaries have offset codes available for the first
624077 * block. After the first block, the offcode table might not have large

◆ ZSTD_compressBlock_targetCBlockSize_body()

size_t duckdb_zstd::ZSTD_compressBlock_targetCBlockSize_body ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const size_t bss,
U32 lastBlock )
static
624090{
624091 DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
624092 if (bss == ZSTDbss_compress) {
624093 if (/* We don't want to emit our first block as a RLE even if it qualifies because
624094 * doing so will cause the decoder (cli only) to throw a "should consume all input error."
624095 * This is only an issue for zstd <= v1.4.3
624096 */
624097 !zc->isFirstBlock &&
624098 ZSTD_maybeRLE(&zc->seqStore) &&
624099 ZSTD_isRLE((BYTE const*)src, srcSize))
624100 {
624101 return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
624102 }
624103 /* Attempt superblock compression.
624104 *
624105 * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
624106 * standard ZSTD_compressBound(). This is a problem, because even if we have
624107 * space now, taking an extra byte now could cause us to run out of space later
624108 * and violate ZSTD_compressBound().
624109 *
624110 * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
624111 *
624112 * In order to respect ZSTD_compressBound() we must attempt to emit a raw
624113 * uncompressed block in these cases:
624114 * * cSize == 0: Return code for an uncompressed block.
624115 * * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
624116 * ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
624117 * output space.
624118 * * cSize >= blockBound(srcSize): We have expanded the block too much so
624119 * emit an uncompressed block.
624120 */
624121 { size_t const cSize =
624122 ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
624123 if (cSize != ERROR(dstSize_tooSmall)) {
624124 size_t const maxCSize =
624125 srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
624126 FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
624127 if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {
624128 ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
624129 return cSize;
624130 }
624131 }
624132 }
624133 } /* if (bss == ZSTDbss_compress)*/

◆ ZSTD_compressBlock_targetCBlockSize()

size_t duckdb_zstd::ZSTD_compressBlock_targetCBlockSize ( ZSTD_CCtx * zc,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 lastBlock )
static
624146{
624147 size_t cSize = 0;
624148 const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
624149 DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
624150 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
624151 FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
624152
624153 cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);

◆ ZSTD_overflowCorrectIfNeeded()

void duckdb_zstd::ZSTD_overflowCorrectIfNeeded ( ZSTD_matchState_t * ms,
ZSTD_cwksp * ws,
ZSTD_CCtx_params const * params,
void const * ip,
void const * iend )
static
624167{
624168 U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
624169 U32 const maxDist = (U32)1 << params->cParams.windowLog;
624170 if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
624171 U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
624172 ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
624173 ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
624174 ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
624175 ZSTD_cwksp_mark_tables_dirty(ws);
624176 ZSTD_reduceIndex(ms, params, correction);
624177 ZSTD_cwksp_mark_tables_clean(ws);

◆ ZSTD_compress_frameChunk()

size_t duckdb_zstd::ZSTD_compress_frameChunk ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 lastFrameChunk )
static

ZSTD_compress_frameChunk() : Compress a chunk of data into one or multiple blocks. All blocks will be terminated, all input will be consumed. Function will issue an error if there is not enough dstCapacity to hold the compressed content. Frame is supposed already started (header already produced)

Returns
: compressed size, or an error code
624197{
624198 size_t blockSize = cctx->blockSize;
624199 size_t remaining = srcSize;
624200 const BYTE* ip = (const BYTE*)src;
624201 BYTE* const ostart = (BYTE*)dst;
624202 BYTE* op = ostart;
624203 U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
624204
624205 assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
624206
624207 DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
624208 if (cctx->appliedParams.fParams.checksumFlag && srcSize)
624209 XXH64_update(&cctx->xxhState, src, srcSize);
624210
624211 while (remaining) {
624212 ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
624213 U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
624214
624215 /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
624216 * additional 1. We need to revisit and change this logic to be more consistent */
624217 RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1,
624218 dstSize_tooSmall,
624219 "not enough space to store compressed block");
624220 if (remaining < blockSize) blockSize = remaining;
624221
624222 ZSTD_overflowCorrectIfNeeded(
624223 ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
624224 ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
624225 ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
624226
624227 /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
624228 if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
624229
624230 { size_t cSize;
624231 if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
624232 cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
624233 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
624234 assert(cSize > 0);
624235 assert(cSize <= blockSize + ZSTD_blockHeaderSize);
624236 } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
624237 cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
624238 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
624239 assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
624240 } else {
624241 cSize = ZSTD_compressBlock_internal(cctx,
624242 op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
624243 ip, blockSize, 1 /* frame */);
624244 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
624245
624246 if (cSize == 0) { /* block is not compressible */
624247 cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
624248 FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
624249 } else {
624250 U32 const cBlockHeader = cSize == 1 ?
624251 lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
624252 lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
624253 MEM_writeLE24(op, cBlockHeader);
624254 cSize += ZSTD_blockHeaderSize;
624255 }
624256 } /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/
624257
624258
624259 ip += blockSize;
624260 assert(remaining >= blockSize);
624261 remaining -= blockSize;
624262 op += cSize;
624263 assert(dstCapacity >= cSize);
624264 dstCapacity -= cSize;
624265 cctx->isFirstBlock = 0;
int checksumFlag
Definition duckdb.cpp:408458
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_writeFrameHeader()

size_t duckdb_zstd::ZSTD_writeFrameHeader ( void * dst,
size_t dstCapacity,
const ZSTD_CCtx_params * params,
U64 pledgedSrcSize,
U32 dictID )
static
624277{ BYTE* const op = (BYTE*)dst;
624278 U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
624279 U32 const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
624280 U32 const checksumFlag = params->fParams.checksumFlag>0;
624281 U32 const windowSize = (U32)1 << params->cParams.windowLog;
624282 U32 const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
624283 BYTE const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
624284 U32 const fcsCode = params->fParams.contentSizeFlag ?
624285 (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
624286 BYTE const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
624287 size_t pos=0;
624288
624289 assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
624290 RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
624291 "dst buf is too small to fit worst-case frame header size.");
624292 DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
624293 !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
624294 if (params->format == ZSTD_f_zstd1) {
624295 MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
624296 pos = 4;
624297 }
624298 op[pos++] = frameHeaderDescriptionByte;
624299 if (!singleSegment) op[pos++] = windowLogByte;
624300 switch(dictIDSizeCode)
624301 {
624302 default:
624303 assert(0); /* impossible */
624304 ZSTD_FALLTHROUGH;
624305 case 0 : break;
624306 case 1 : op[pos] = (BYTE)(dictID); pos++; break;
624307 case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
624308 case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
624309 }
624310 switch(fcsCode)
624311 {
624312 default:
624313 assert(0); /* impossible */
624314 ZSTD_FALLTHROUGH;

◆ ZSTD_compressContinue_internal()

size_t duckdb_zstd::ZSTD_compressContinue_internal ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
U32 frame,
U32 lastFrameChunk )
static
624374{
624375 ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
624376 size_t fhSize = 0;
624377
624378 DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
624379 cctx->stage, (unsigned)srcSize);
624380 RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
624381 "missing init (ZSTD_compressBegin)");
624382
624383 if (frame && (cctx->stage==ZSTDcs_init)) {
624384 fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
624385 cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
624386 FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
624387 assert(fhSize <= dstCapacity);
624388 dstCapacity -= fhSize;
624389 dst = (char*)dst + fhSize;
624390 cctx->stage = ZSTDcs_ongoing;
624391 }
624392
624393 if (!srcSize) return fhSize; /* do not generate an empty block if no input */
624394
624395 if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
624396 ms->forceNonContiguous = 0;
624397 ms->nextToUpdate = ms->window.dictLimit;
624398 }
624399 if (cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
624400 ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
624401 }
624402
624403 if (!frame) {
624404 /* overflow check and correction for block mode */
624405 ZSTD_overflowCorrectIfNeeded(
624406 ms, &cctx->workspace, &cctx->appliedParams,
624407 src, (BYTE const*)src + srcSize);
624408 }
624409
624410 DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
624411 { size_t const cSize = frame ?
624412 ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
624413 ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
624414 FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
624415 cctx->consumedSrcSize += srcSize;
624416 cctx->producedCSize += (cSize + fhSize);
624417 assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
624418 if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
624419 ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
624421 cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
624422 srcSize_wrong,
MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_window_update(ZSTD_window_t *window, void const *src, size_t srcSize, int forceNonContiguous)
Definition duckdb.cpp:618762
static size_t ZSTD_compress_frameChunk(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastFrameChunk)
Definition duckdb.cpp:624186

◆ ZSTD_getBlockSize_deprecated()

size_t duckdb_zstd::ZSTD_getBlockSize_deprecated ( const ZSTD_CCtx * cctx)
static
624443{
624444 return ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize);
624445}

◆ ZSTD_loadDictionaryContent()

size_t duckdb_zstd::ZSTD_loadDictionaryContent ( ZSTD_matchState_t * ms,
ldmState_t * ls,
ZSTD_cwksp * ws,
ZSTD_CCtx_params const * params,
const void * src,
size_t srcSize,
ZSTD_dictTableLoadMethod_e dtlm,
ZSTD_tableFillPurpose_e tfp )
static

ZSTD_loadDictionaryContent() :

Returns
: 0, or an error code
624472{
624473 return ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize);
624474}
624475
624479static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
624480 ldmState_t* ls,
624481 ZSTD_cwksp* ws,
624482 ZSTD_CCtx_params const* params,
624483 const void* src, size_t srcSize,
624484 ZSTD_dictTableLoadMethod_e dtlm,
624485 ZSTD_tableFillPurpose_e tfp)
624486{
624487 const BYTE* ip = (const BYTE*) src;
624488 const BYTE* const iend = ip + srcSize;
624489 int const loadLdmDict = params->ldmParams.enableLdm == ZSTD_ps_enable && ls != NULL;
624490
624491 /* Assert that the ms params match the params we're being given */
624492 ZSTD_assertEqualCParams(params->cParams, ms->cParams);
624493
624494 { /* Ensure large dictionaries can't cause index overflow */
624495
624496 /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
624497 * Dictionaries right at the edge will immediately trigger overflow
624498 * correction, but I don't want to insert extra constraints here.
624499 */
624500 U32 maxDictSize = ZSTD_CURRENT_MAX - ZSTD_WINDOW_START_INDEX;
624501
624502 int const CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(&params->cParams);
624503 if (CDictTaggedIndices && tfp == ZSTD_tfp_forCDict) {
624504 /* Some dictionary matchfinders in zstd use "short cache",
624505 * which treats the lower ZSTD_SHORT_CACHE_TAG_BITS of each
624506 * CDict hashtable entry as a tag rather than as part of an index.
624507 * When short cache is used, we need to truncate the dictionary
624508 * so that its indices don't overlap with the tag. */
624509 U32 const shortCacheMaxDictSize = (1u << (32 - ZSTD_SHORT_CACHE_TAG_BITS)) - ZSTD_WINDOW_START_INDEX;
624510 maxDictSize = MIN(maxDictSize, shortCacheMaxDictSize);
624511 assert(!loadLdmDict);
624512 }
624513
624514 /* If the dictionary is too large, only load the suffix of the dictionary. */
624515 if (srcSize > maxDictSize) {
624516 ip = iend - maxDictSize;
624517 src = ip;
624518 srcSize = maxDictSize;
624519 }
624520 }
624521
624522 if (srcSize > ZSTD_CHUNKSIZE_MAX) {
624523 /* We must have cleared our windows when our source is this large. */
624524 assert(ZSTD_window_isEmpty(ms->window));
624525 if (loadLdmDict) assert(ZSTD_window_isEmpty(ls->window));
624526 }
624527 ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
624528
624529 DEBUGLOG(4, "ZSTD_loadDictionaryContent(): useRowMatchFinder=%d", (int)params->useRowMatchFinder);
624530
624531 if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */
624532 ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
624533 ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
624534 ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
624535 }
624536
624537 /* If the dict is larger than we can reasonably index in our tables, only load the suffix. */
624538 if (params->cParams.strategy < ZSTD_btultra) {
624539 U32 maxDictSize = 8U << MIN(MAX(params->cParams.hashLog, params->cParams.chainLog), 28);
624540 if (srcSize > maxDictSize) {
624541 ip = iend - maxDictSize;
624542 src = ip;
624543 srcSize = maxDictSize;
624544 }
624545 }
624546
624547 ms->nextToUpdate = (U32)(ip - ms->window.base);
624548 ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
624549 ms->forceNonContiguous = params->deterministicRefPrefix;
624550
624551 if (srcSize <= HASH_READ_SIZE) return 0;
624552
624553 ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
624554
624555 switch(params->cParams.strategy)
624556 {
624557 case ZSTD_fast:
624558 ZSTD_fillHashTable(ms, iend, dtlm, tfp);
624559 break;
624560 case ZSTD_dfast:
624561#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
624562 ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp);
624563#else
624564 assert(0); /* shouldn't be called: cparams should've been adjusted. */
624565#endif
624566 break;
624567
624568 case ZSTD_greedy:
624569 case ZSTD_lazy:
624570 case ZSTD_lazy2:
624571#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
624572 || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
624573 || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR)
624574 assert(srcSize >= HASH_READ_SIZE);
624575 if (ms->dedicatedDictSearch) {
624576 assert(ms->chainTable != NULL);
624577 ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
624578 } else {
624579 assert(params->useRowMatchFinder != ZSTD_ps_auto);
624580 if (params->useRowMatchFinder == ZSTD_ps_enable) {
624581 size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog);
624582 ZSTD_memset(ms->tagTable, 0, tagTableSize);
624583 ZSTD_row_update(ms, iend-HASH_READ_SIZE);
624584 DEBUGLOG(4, "Using row-based hash table for lazy dict");
624585 } else {
624586 ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
624587 DEBUGLOG(4, "Using chain-based hash table for lazy dict");
624588 }
624589 }
624590#else
624591 assert(0); /* shouldn't be called: cparams should've been adjusted. */
624592#endif
624593 break;
624594
624595 case ZSTD_btlazy2: /* we want the dictionary table fully sorted */
624596 case ZSTD_btopt:
624597 case ZSTD_btultra:
624598 case ZSTD_btultra2:
624599#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
624600 || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
624601 || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
624602 assert(srcSize >= HASH_READ_SIZE);
624603 ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
624604#else
624605 assert(0); /* shouldn't be called: cparams should've been adjusted. */
624606#endif
624607 break;
624608
void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t *ms, const BYTE *const ip)
Definition duckdb.cpp:630585
static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t *ms, ldmState_t *ls, ZSTD_cwksp *ws, ZSTD_CCtx_params const *params, const void *src, size_t srcSize, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp)
Definition duckdb.cpp:624472
Here is the caller graph for this function:

◆ ZSTD_dictNCountRepeat()

FSE_repeat duckdb_zstd::ZSTD_dictNCountRepeat ( short * normalizedCounter,
unsigned dictMaxSymbolValue,
unsigned maxSymbolValue )
static
624623{
624624 U32 s;
624625 if (dictMaxSymbolValue < maxSymbolValue) {
624626 return FSE_repeat_check;
624627 }

◆ ZSTD_loadZstdDictionary()

size_t duckdb_zstd::ZSTD_loadZstdDictionary ( ZSTD_compressedBlockState_t * bs,
ZSTD_matchState_t * ms,
ZSTD_cwksp * ws,
ZSTD_CCtx_params const * params,
const void * dict,
size_t dictSize,
ZSTD_dictTableLoadMethod_e dtlm,
ZSTD_tableFillPurpose_e tfp,
void * workspace )
static

ZSTD_loadZstdDictionary() :

Returns
: dictID, or an error code assumptions : magic number supposed already checked dictSize supposed >= 8
624729 ://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
624730 */
624737 ZSTD_matchState_t* ms,
624738 ZSTD_cwksp* ws,
624739 ZSTD_CCtx_params const* params,
624740 const void* dict, size_t dictSize,
624741 ZSTD_dictTableLoadMethod_e dtlm,
624742 ZSTD_tableFillPurpose_e tfp,
624743 void* workspace)
624744{
624745 const BYTE* dictPtr = (const BYTE*)dict;
624746 const BYTE* const dictEnd = dictPtr + dictSize;
624747 size_t dictID;
624748 size_t eSize;
624749 ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
624750 assert(dictSize >= 8);
624751 assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
624752
624753 dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr + 4 /* skip magic number */ );
624754 eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
624755 FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
624756 dictPtr += eSize;
624757
static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t *bs, ZSTD_matchState_t *ms, ZSTD_cwksp *ws, ZSTD_CCtx_params const *params, const void *dict, size_t dictSize, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, void *workspace)
Definition duckdb.cpp:624729
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compress_insertDictionary()

size_t duckdb_zstd::ZSTD_compress_insertDictionary ( ZSTD_compressedBlockState_t * bs,
ZSTD_matchState_t * ms,
ldmState_t * ls,
ZSTD_cwksp * ws,
const ZSTD_CCtx_params * params,
const void * dict,
size_t dictSize,
ZSTD_dictContentType_e dictContentType,
ZSTD_dictTableLoadMethod_e dtlm,
ZSTD_tableFillPurpose_e tfp,
void * workspace )
static

ZSTD_compress_insertDictionary() :

Returns
: dictID, or an error code
624779{
624780 DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
624781 if ((dict==NULL) || (dictSize<8)) {
624782 RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
624783 return 0;
624784 }
624785
624786 ZSTD_reset_compressedBlockState(bs);
624787
624788 /* dict restricted modes */
624789 if (dictContentType == ZSTD_dct_rawContent)
624790 return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
624791
624792 if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
624793 if (dictContentType == ZSTD_dct_auto) {
624794 DEBUGLOG(4, "raw content dictionary detected");
624796 ms, ls, ws, params, dict, dictSize, dtlm, tfp);
624797 }
624798 RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
Here is the caller graph for this function:

◆ ZSTD_compressBegin_internal()

size_t duckdb_zstd::ZSTD_compressBegin_internal ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
ZSTD_dictContentType_e dictContentType,
ZSTD_dictTableLoadMethod_e dtlm,
const ZSTD_CDict * cdict,
const ZSTD_CCtx_params * params,
U64 pledgedSrcSize,
ZSTD_buffered_policy_e zbuff )
static

ZSTD_compressBegin_internal() : Assumption : either @dict OR @cdict (or none) is non-NULL, never both

Returns
: 0, or an error code
624820{
624821 size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
624822#if ZSTD_TRACE
624823 cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
624824#endif
624825 DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
624826 /* params are supposed to be fully validated at this point */
624828 assert(!((dict) && (cdict))); /* either dict or cdict, not both */
624829 if ( (cdict)
624830 && (cdict->dictContentSize > 0)
624831 && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
624832 || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
624833 || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
624834 || cdict->compressionLevel == 0)
624835 && (params->attachDictPref != ZSTD_dictForceLoad) ) {
624836 return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
624837 }
624838
624839 FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
624840 dictContentSize,
624841 ZSTDcrp_makeClean, zbuff) , "");
624842 { size_t const dictID = cdict ?
624844 cctx->blockState.prevCBlock, &cctx->blockState.matchState,
624845 &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
624846 cdict->dictContentSize, cdict->dictContentType, dtlm,
624847 ZSTD_tfp_forCCtx, cctx->entropyWorkspace)
624849 cctx->blockState.prevCBlock, &cctx->blockState.matchState,
624850 &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
624851 dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->entropyWorkspace);
static size_t ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t *bs, ZSTD_matchState_t *ms, ldmState_t *ls, ZSTD_cwksp *ws, const ZSTD_CCtx_params *params, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, void *workspace)
Definition duckdb.cpp:624762
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressBegin_usingDict_deprecated()

size_t duckdb_zstd::ZSTD_compressBegin_usingDict_deprecated ( ZSTD_CCtx * cctx,
const void * dict,
size_t dictSize,
int compressionLevel )
static
624894{
624895 ZSTD_CCtx_params cctxParams;

◆ ZSTD_writeEpilogue()

size_t duckdb_zstd::ZSTD_writeEpilogue ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity )
static

ZSTD_writeEpilogue() : Ends a frame.

Returns
: nb of bytes written into dst (or an error code)
624920{
624921 BYTE* const ostart = (BYTE*)dst;
624922 BYTE* op = ostart;
624923
624924 DEBUGLOG(4, "ZSTD_writeEpilogue");
624925 RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
624926
624927 /* special case : empty frame */
624928 if (cctx->stage == ZSTDcs_init) {
624929 size_t fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
624930 FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
624931 dstCapacity -= fhSize;
624932 op += fhSize;
624933 cctx->stage = ZSTDcs_ongoing;
624934 }
624935
624936 if (cctx->stage != ZSTDcs_ending) {
624937 /* write one last empty block, make it the "last" block */
624938 U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
624939 ZSTD_STATIC_ASSERT(ZSTD_BLOCKHEADERSIZE == 3);
624940 RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "no room for epilogue");
624941 MEM_writeLE24(op, cBlockHeader24);
624942 op += ZSTD_blockHeaderSize;
624943 dstCapacity -= ZSTD_blockHeaderSize;
624944 }
624945
624946 if (cctx->appliedParams.fParams.checksumFlag) {
624947 U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
624948 RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
624949 DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);

◆ ZSTD_compress()

size_t duckdb_zstd::ZSTD_compress ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
int compressionLevel )
625066{
625067 DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
625068 assert(cctx != NULL);
625069 return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
625070}
625071
625072size_t ZSTD_compress(void* dst, size_t dstCapacity,
625073 const void* src, size_t srcSize,
625074 int compressionLevel)
625075{
625076 size_t result;
625077#if ZSTD_COMPRESS_HEAPMODE
625078 ZSTD_CCtx* cctx = ZSTD_createCCtx();
625079 RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
625080 result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
625081 ZSTD_freeCCtx(cctx);
625082#else
ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx *ctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, int compressionLevel)
Definition duckdb.cpp:625040

◆ ZSTD_initCDict_internal()

size_t duckdb_zstd::ZSTD_initCDict_internal ( ZSTD_CDict * cdict,
const void * dictBuffer,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType,
ZSTD_CCtx_params params )
static
625120 : %u", (unsigned)sizeof(*cdict));
625121 /* cdict may be in the workspace */
625122 return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
625123 + ZSTD_cwksp_sizeof(&cdict->workspace);
625124}
625125
625126static size_t ZSTD_initCDict_internal(
625127 ZSTD_CDict* cdict,
625128 const void* dictBuffer, size_t dictSize,
625129 ZSTD_dictLoadMethod_e dictLoadMethod,
625130 ZSTD_dictContentType_e dictContentType,
625131 ZSTD_CCtx_params params)
625132{
625133 DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
625134 assert(!ZSTD_checkCParams(params.cParams));
625135 cdict->matchState.cParams = params.cParams;
625136 cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
625137 if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
625138 cdict->dictContent = dictBuffer;
625139 } else {
625140 void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
625141 RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
625142 cdict->dictContent = internalBuffer;
625143 ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
625144 }
625145 cdict->dictContentSize = dictSize;
625146 cdict->dictContentType = dictContentType;
625147
625148 cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
625149
625150
625151 /* Reset the state to no dictionary */
625152 ZSTD_reset_compressedBlockState(&cdict->cBlockState);
625153 FORWARD_IF_ERROR(ZSTD_reset_matchState(
625154 &cdict->matchState,
625155 &cdict->workspace,
625156 &params.cParams,
625157 params.useRowMatchFinder,
625158 ZSTDcrp_makeClean,
625159 ZSTDirp_reset,
625160 ZSTD_resetTarget_CDict), "");
625161 /* (Maybe) load the dictionary
625162 * Skips loading the dictionary if it is < 8 bytes.
625163 */
625164 { params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
625165 params.fParams.contentSizeFlag = 1;
625166 { size_t const dictID = ZSTD_compress_insertDictionary(
625167 &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
625168 &params, cdict->dictContent, cdict->dictContentSize,
625169 dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);
625170 FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");

◆ ZSTD_createCDict_advanced_internal()

ZSTD_CDict * duckdb_zstd::ZSTD_createCDict_advanced_internal ( size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_compressionParameters cParams,
ZSTD_paramSwitch_e useRowMatchFinder,
U32 enableDedicatedDictSearch,
ZSTD_customMem customMem )
static
625185{
625186 if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
625187
625188 { size_t const workspaceSize =
625190 ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
625191 ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
625192 (dictLoadMethod == ZSTD_dlm_byRef ? 0
625193 : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
625194 void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
625195 ZSTD_cwksp ws;
625196 ZSTD_CDict* cdict;
625197
625198 if (!workspace) {
625199 ZSTD_customFree(workspace, customMem);
625200 return NULL;
625201 }
625202
625203 ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
625204
625205 cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
625206 assert(cdict != NULL);

◆ ZSTD_compressBegin_usingCDict_internal()

size_t duckdb_zstd::ZSTD_compressBegin_usingCDict_internal ( ZSTD_CCtx *const cctx,
const ZSTD_CDict *const cdict,
ZSTD_frameParameters const fParams,
unsigned long long const pledgedSrcSize )
static
625399{
625400 ZSTD_CCtx_params cctxParams;
625401 DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
625402 RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
625403 /* Initialize the cctxParams from the cdict */
625404 {
625406 params.fParams = fParams;
625407 params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
625408 || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
625409 || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
625410 || cdict->compressionLevel == 0 ) ?
625412 : ZSTD_getCParams(cdict->compressionLevel,
625413 pledgedSrcSize,
625414 cdict->dictContentSize);
625415 ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
625416 }
625417 /* Increase window log to fit the entire dictionary and source if the
625418 * source size is known. Limit the increase to 19, which is the
625419 * window log for compression level 1 with the largest source size.
625420 */
625421 if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
625422 U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
625423 U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
625424 cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict *cdict)
Definition duckdb.cpp:625370
static void ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params *cctxParams, const ZSTD_parameters *params, int compressionLevel)
Definition duckdb.cpp:620086

◆ ZSTD_compress_usingCDict_internal()

size_t duckdb_zstd::ZSTD_compress_usingCDict_internal ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const ZSTD_CDict * cdict,
ZSTD_frameParameters fParams )
static

ZSTD_compress_usingCDict_internal(): Implementation of various ZSTD_compress_usingCDict* functions.

625453{
625454 return ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict);
625455}
625456
625460static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict, ZSTD_frameParameters fParams)
Definition duckdb.cpp:625453

◆ ZSTD_getCParamMode()

ZSTD_cParamMode_e duckdb_zstd::ZSTD_getCParamMode ( ZSTD_CDict const * cdict,
ZSTD_CCtx_params const * params,
U64 pledgedSrcSize )
static
625525 { return ZSTD_BLOCKSIZE_MAX; }
625526
625527size_t ZSTD_CStreamOutSize(void)
625528{
625529 return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
625530}
625531
ZSTDLIB_API size_t ZSTD_CStreamOutSize(void)
Definition duckdb.cpp:625520

◆ ZSTD_nextInputSizeHint()

size_t duckdb_zstd::ZSTD_nextInputSizeHint ( const ZSTD_CCtx * cctx)
static
625662{
625663 if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
625664 return cctx->blockSize - cctx->stableIn_notConsumed;

◆ ZSTD_compressStream_generic()

size_t duckdb_zstd::ZSTD_compressStream_generic ( ZSTD_CStream * zcs,
ZSTD_outBuffer * output,
ZSTD_inBuffer * input,
ZSTD_EndDirective const flushMode )
static

ZSTD_compressStream_generic(): internal function for all compressStream() variants

Returns
: hint size for next input to complete ongoing block
625680{
625681 const char* const istart = (assert(input != NULL), (const char*)input->src);
625682 const char* const iend = (istart != NULL) ? istart + input->size : istart;
625683 const char* ip = (istart != NULL) ? istart + input->pos : istart;
625684 char* const ostart = (assert(output != NULL), (char*)output->dst);
625685 char* const oend = (ostart != NULL) ? ostart + output->size : ostart;
625686 char* op = (ostart != NULL) ? ostart + output->pos : ostart;
625687 U32 someMoreWork = 1;
625688
625689 /* check expectations */
625690 DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%i, srcSize = %zu", (int)flushMode, input->size - input->pos);
625691 assert(zcs != NULL);
625692 if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) {
625693 assert(input->pos >= zcs->stableIn_notConsumed);
625694 input->pos -= zcs->stableIn_notConsumed;
625695 if (ip) ip -= zcs->stableIn_notConsumed;
625696 zcs->stableIn_notConsumed = 0;
625697 }
625698 if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
625699 assert(zcs->inBuff != NULL);
625700 assert(zcs->inBuffSize > 0);
625701 }
625702 if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
625703 assert(zcs->outBuff != NULL);
625704 assert(zcs->outBuffSize > 0);
625705 }
625706 if (input->src == NULL) assert(input->size == 0);
625707 assert(input->pos <= input->size);
625708 if (output->dst == NULL) assert(output->size == 0);
625709 assert(output->pos <= output->size);
625710 assert((U32)flushMode <= (U32)ZSTD_e_end);
625711
625712 while (someMoreWork) {
625713 switch(zcs->streamStage)
625714 {
625715 case zcss_init:
625716 RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
625717
625718 case zcss_load:
625719 if ( (flushMode == ZSTD_e_end)
625720 && ( (size_t)(oend-op) >= ZSTD_compressBound(iend-ip) /* Enough output space */
625721 || zcs->appliedParams.outBufferMode == ZSTD_bm_stable) /* OR we are allowed to return dstSizeTooSmall */
625722 && (zcs->inBuffPos == 0) ) {
625723 /* shortcut to compression pass directly into output buffer */
625724 size_t const cSize = ZSTD_compressEnd_public(zcs,
625725 op, oend-op, ip, iend-ip);
625726 DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
625727 FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
625728 ip = iend;
625729 op += cSize;
625730 zcs->frameEnded = 1;
625731 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
625732 someMoreWork = 0; break;
625733 }
625734 /* complete loading into inBuffer in buffered mode */
625735 if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
625736 size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
625737 size_t const loaded = ZSTD_limitCopy(
625738 zcs->inBuff + zcs->inBuffPos, toLoad,
625739 ip, iend-ip);
625740 zcs->inBuffPos += loaded;
625741 if (ip) ip += loaded;
625742 if ( (flushMode == ZSTD_e_continue)
625743 && (zcs->inBuffPos < zcs->inBuffTarget) ) {
625744 /* not enough input to fill full block : stop here */
625745 someMoreWork = 0; break;
625746 }
625747 if ( (flushMode == ZSTD_e_flush)
625748 && (zcs->inBuffPos == zcs->inToCompress) ) {
625749 /* empty */
625750 someMoreWork = 0; break;
625751 }
625752 } else {
625753 assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
625754 if ( (flushMode == ZSTD_e_continue)
625755 && ( (size_t)(iend - ip) < zcs->blockSize) ) {
625756 /* can't compress a full block : stop here */
625757 zcs->stableIn_notConsumed = (size_t)(iend - ip);
625758 ip = iend; /* pretend to have consumed input */
625759 someMoreWork = 0; break;
625760 }
625761 if ( (flushMode == ZSTD_e_flush)
625762 && (ip == iend) ) {
625763 /* empty */
625764 someMoreWork = 0; break;
625765 }
625766 }
625767 /* compress current block (note : this stage cannot be stopped in the middle) */
625768 DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
625769 { int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
625770 void* cDst;
625771 size_t cSize;
625772 size_t oSize = oend-op;
625773 size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress
625774 : MIN((size_t)(iend - ip), zcs->blockSize);
625775 if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
625776 cDst = op; /* compress into output buffer, to skip flush stage */
625777 else
625778 cDst = zcs->outBuff, oSize = zcs->outBuffSize;
625779 if (inputBuffered) {
625780 unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
625781 cSize = lastBlock ?
625782 ZSTD_compressEnd_public(zcs, cDst, oSize,
625783 zcs->inBuff + zcs->inToCompress, iSize) :
625784 ZSTD_compressContinue_public(zcs, cDst, oSize,
625785 zcs->inBuff + zcs->inToCompress, iSize);
625786 FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
625787 zcs->frameEnded = lastBlock;
625788 /* prepare next block */
625789 zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
625790 if (zcs->inBuffTarget > zcs->inBuffSize)
625791 zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
625792 DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
625793 (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
625794 if (!lastBlock)
625795 assert(zcs->inBuffTarget <= zcs->inBuffSize);
625796 zcs->inToCompress = zcs->inBuffPos;
625797 } else { /* !inputBuffered, hence ZSTD_bm_stable */
625798 unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip + iSize == iend);
625799 cSize = lastBlock ?
625800 ZSTD_compressEnd_public(zcs, cDst, oSize, ip, iSize) :
625801 ZSTD_compressContinue_public(zcs, cDst, oSize, ip, iSize);
625802 /* Consume the input prior to error checking to mirror buffered mode. */
625803 if (ip) ip += iSize;
625804 FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
625805 zcs->frameEnded = lastBlock;
625806 if (lastBlock) assert(ip == iend);
625807 }
625808 if (cDst == op) { /* no need to flush */
625809 op += cSize;
625810 if (zcs->frameEnded) {
625811 DEBUGLOG(5, "Frame completed directly in outBuffer");
625812 someMoreWork = 0;
625813 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
625814 }
625815 break;
625816 }
625817 zcs->outBuffContentSize = cSize;
625818 zcs->outBuffFlushedSize = 0;
625819 zcs->streamStage = zcss_flush; /* pass-through to flush stage */
625820 }
625821 ZSTD_FALLTHROUGH;
625822 case zcss_flush:
625823 DEBUGLOG(5, "flush stage");
625824 assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
625825 { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
625826 size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
625827 zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
625828 DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
625829 (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
625830 if (flushed)
625831 op += flushed;
625832 zcs->outBuffFlushedSize += flushed;
625833 if (toFlush!=flushed) {
625834 /* flush not fully completed, presumably because dst is too small */
625835 assert(op==oend);
625836 someMoreWork = 0;
625837 break;
625838 }
625839 zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
625840 if (zcs->frameEnded) {
625841 DEBUGLOG(5, "Frame completed on flush");
625842 someMoreWork = 0;
625843 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
625844 break;
625845 }
625846 zcs->streamStage = zcss_load;
625847 break;
625848 }
625849
625850 default: /* impossible */
625851 assert(0);
625852 }
Here is the caller graph for this function:

◆ ZSTD_nextInputSizeHint_MTorST()

size_t duckdb_zstd::ZSTD_nextInputSizeHint_MTorST ( const ZSTD_CCtx * cctx)
static
625862{
625863#ifdef ZSTD_MULTITHREAD
625864 if (cctx->appliedParams.nbWorkers >= 1) {

◆ ZSTD_setBufferExpectations()

void duckdb_zstd::ZSTD_setBufferExpectations ( ZSTD_CCtx * cctx,
const ZSTD_outBuffer * output,
const ZSTD_inBuffer * input )
static
625884{
625885 DEBUGLOG(5, "ZSTD_setBufferExpectations (for advanced stable in/out modes)");

◆ ZSTD_checkBufferStability()

size_t duckdb_zstd::ZSTD_checkBufferStability ( ZSTD_CCtx const * cctx,
ZSTD_outBuffer const * output,
ZSTD_inBuffer const * input,
ZSTD_EndDirective endOp )
static
625901{
625902 if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
625903 ZSTD_inBuffer const expect = cctx->expectedInBuffer;
625904 if (expect.src != input->src || expect.pos != input->pos)
625905 RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableInBuffer enabled but input differs!");
625906 }
625907 (void)endOp;

◆ ZSTD_CCtx_init_compressStream2()

size_t duckdb_zstd::ZSTD_CCtx_init_compressStream2 ( ZSTD_CCtx * cctx,
ZSTD_EndDirective endOp,
size_t inSize )
static
625919{
625920 ZSTD_CCtx_params params = cctx->requestedParams;
625921 ZSTD_prefixDict const prefixDict = cctx->prefixDict;
625922 FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
625923 ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
625924 assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
625925 if (cctx->cdict && !cctx->localDict.cdict) {
625926 /* Let the cdict's compression level take priority over the requested params.
625927 * But do not take the cdict's compression level if the "cdict" is actually a localDict
625928 * generated from ZSTD_initLocalDict().
625929 */
625930 params.compressionLevel = cctx->cdict->compressionLevel;
625931 }
625932 DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
625933 if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1; /* auto-determine pledgedSrcSize */
625934
625935 { size_t const dictSize = prefixDict.dict
625936 ? prefixDict.dictSize
625937 : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
625938 ZSTD_cParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
625939 params.cParams = ZSTD_getCParamsFromCCtxParams(
625940 &params, cctx->pledgedSrcSizePlusOne-1,
625941 dictSize, mode);
625942 }
625943
625944 params.useBlockSplitter = ZSTD_resolveBlockSplitterMode(params.useBlockSplitter, &params.cParams);
625945 params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, &params.cParams);
625946 params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
625947 params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);
625948 params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);
625949 params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(params.searchForExternalRepcodes, params.compressionLevel);
625950
625951#ifdef ZSTD_MULTITHREAD
625952 /* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */
625954 ZSTD_hasExtSeqProd(&params) && params.nbWorkers >= 1,
625955 parameter_combination_unsupported,
625956 "External sequence producer isn't supported with nbWorkers >= 1"
625957 );
625958
625959 if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
625960 params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
625961 }
625962 if (params.nbWorkers > 0) {
625963#if ZSTD_TRACE
625964 cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
625965#endif
625966 /* mt context creation */
625967 if (cctx->mtctx == NULL) {
625968 DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
625969 params.nbWorkers);
625970 cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
625971 RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
625972 }
625973 /* mt compression */
625974 DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
625976 cctx->mtctx,
625977 prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
625978 cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
625979 cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
625980 cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
625981 cctx->consumedSrcSize = 0;
625982 cctx->producedCSize = 0;
625983 cctx->streamStage = zcss_load;
625984 cctx->appliedParams = params;
625985 } else
625986#endif /* ZSTD_MULTITHREAD */
625987 { U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
625990 prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
625991 cctx->cdict,
625992 &params, pledgedSrcSize,
625993 ZSTDb_buffered) , "");
625994 assert(cctx->appliedParams.nbWorkers == 0);
625995 cctx->inToCompress = 0;
625996 cctx->inBuffPos = 0;
625997 if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
625998 /* for small input: avoid automatic flush on reaching end of block, since
625999 * it would require to add a 3-bytes null block to end frame
626000 */
626001 cctx->inBuffTarget = cctx->blockSize + (cctx->blockSize == pledgedSrcSize);
626002 } else {
626003 cctx->inBuffTarget = 0;
static size_t ZSTD_initLocalDict(ZSTD_CCtx *cctx)
Definition duckdb.cpp:620949
static size_t ZSTD_compressBegin_internal(ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, const ZSTD_CDict *cdict, const ZSTD_CCtx_params *params, U64 pledgedSrcSize, ZSTD_buffered_policy_e zbuff)
Definition duckdb.cpp:624806

◆ ZSTD_compress2()

size_t duckdb_zstd::ZSTD_compress2 ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
626128 { size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
626129 *dstPos = output.pos;
626130 *srcPos = input.pos;
626131 return cErr;
626132 }
626133}
626134
626135size_t ZSTD_compress2(ZSTD_CCtx* cctx,
626136 void* dst, size_t dstCapacity,
626137 const void* src, size_t srcSize)
626138{
626139 ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
626140 ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
626141 DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
626142 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
626143 /* Enable stable input/output buffers. */
626144 cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
626145 cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
626146 { size_t oPos = 0;
626147 size_t iPos = 0;
626148 size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
626149 dst, dstCapacity, &oPos,
626150 src, srcSize, &iPos,
626151 ZSTD_e_end);
626152 /* Reset to the original values. */
626153 cctx->requestedParams.inBufferMode = originalInBufferMode;
626154 cctx->requestedParams.outBufferMode = originalOutBufferMode;
626155
626156 FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
626157 if (result != 0) { /* compression not completed, due to lack of output space */
ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, size_t *dstPos, const void *src, size_t srcSize, size_t *srcPos, ZSTD_EndDirective endOp)
Definition duckdb.cpp:626106

◆ ZSTD_validateSequence()

size_t duckdb_zstd::ZSTD_validateSequence ( U32 offCode,
U32 matchLength,
U32 minMatch,
size_t posInSrc,
U32 windowLog,
size_t dictSize,
int useSequenceProducer )
static
626173{
626174 U32 const windowSize = 1u << windowLog;
626175 /* posInSrc represents the amount of data the decoder would decode up to this point.
626176 * As long as the amount of data decoded is less than or equal to window size, offsets may be
626177 * larger than the total length of output decoded in order to reference the dict, even larger than
626178 * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
626179 */

◆ ZSTD_finalizeOffBase()

U32 duckdb_zstd::ZSTD_finalizeOffBase ( U32 rawOffset,
const U32 rep[ZSTD_REP_NUM],
U32 ll0 )
static
626190{
626191 U32 offBase = OFFSET_TO_OFFBASE(rawOffset);
626192
626193 if (!ll0 && rawOffset == rep[0]) {
626194 offBase = REPCODE1_TO_OFFBASE;
626195 } else if (rawOffset == rep[1]) {
626196 offBase = REPCODE_TO_OFFBASE(2 - ll0);

◆ ZSTD_selectSequenceCopier()

ZSTD_sequenceCopier duckdb_zstd::ZSTD_selectSequenceCopier ( ZSTD_sequenceFormat_e mode)
static
626418{
626419 ZSTD_sequenceCopier sequenceCopier = NULL;
626420 assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, mode));
626421 if (mode == ZSTD_sf_explicitBlockDelimiters) {

◆ blockSize_explicitDelimiter()

size_t duckdb_zstd::blockSize_explicitDelimiter ( const ZSTD_Sequence * inSeqs,
size_t inSeqsSize,
ZSTD_sequencePosition seqPos )
static
626436{
626437 int end = 0;
626438 size_t blockSize = 0;
626439 size_t spos = seqPos.idx;
626440 DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize);
626441 assert(spos <= inSeqsSize);
626442 while (spos < inSeqsSize) {
626443 end = (inSeqs[spos].offset == 0);
626444 blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength;
626445 if (end) {
626446 if (inSeqs[spos].matchLength != 0)
626447 RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0");
626448 break;

◆ blockSize_noDelimiter()

size_t duckdb_zstd::blockSize_noDelimiter ( size_t blockSize,
size_t remaining )
static

◆ determine_blockSize()

size_t duckdb_zstd::determine_blockSize ( ZSTD_sequenceFormat_e mode,
size_t blockSize,
size_t remaining,
const ZSTD_Sequence * inSeqs,
size_t inSeqsSize,
ZSTD_sequencePosition seqPos )
static
626459{
626460 int const lastBlock = (remaining <= blockSize);
626461 return lastBlock ? remaining : blockSize;
626462}
626463
626464static size_t determine_blockSize(ZSTD_sequenceFormat_e mode,
626465 size_t blockSize, size_t remaining,
626466 const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos)
626467{
626468 DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining);
626469 if (mode == ZSTD_sf_noBlockDelimiters)
626470 return blockSize_noDelimiter(blockSize, remaining);
626471 { size_t const explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos);
626472 FORWARD_IF_ERROR(explicitBlockSize, "Error while determining block size with explicit delimiters");

◆ ZSTD_compressSequences_internal()

size_t duckdb_zstd::ZSTD_compressSequences_internal ( ZSTD_CCtx * cctx,
void * dst,
size_t dstCapacity,
const ZSTD_Sequence * inSeqs,
size_t inSeqsSize,
const void * src,
size_t srcSize )
static
626491{
626492 size_t cSize = 0;
626493 size_t remaining = srcSize;
626494 ZSTD_sequencePosition seqPos = {0, 0, 0};
626495
626496 BYTE const* ip = (BYTE const*)src;
626497 BYTE* op = (BYTE*)dst;
626498 ZSTD_sequenceCopier const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
626499
626500 DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
626501 /* Special case: empty frame */
626502 if (remaining == 0) {
626503 U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
626504 RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
626505 MEM_writeLE32(op, cBlockHeader24);
626506 op += ZSTD_blockHeaderSize;
626507 dstCapacity -= ZSTD_blockHeaderSize;
626508 cSize += ZSTD_blockHeaderSize;
626509 }
626510
626511 while (remaining) {
626512 size_t compressedSeqsSize;
626513 size_t cBlockSize;
626514 size_t additionalByteAdjustment;
626515 size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,
626516 cctx->blockSize, remaining,
626517 inSeqs, inSeqsSize, seqPos);
626518 U32 const lastBlock = (blockSize == remaining);
626519 FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");
626520 assert(blockSize <= remaining);
626521 ZSTD_resetSeqStore(&cctx->seqStore);
626522 DEBUGLOG(5, "Working on new block. Blocksize: %zu (total:%zu)", blockSize, (ip - (const BYTE*)src) + blockSize);
626523
626524 additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize, cctx->appliedParams.searchForExternalRepcodes);
626525 FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
626526 blockSize -= additionalByteAdjustment;
626527
626528 /* If blocks are too small, emit as a nocompress block */
626529 /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
626530 * additional 1. We need to revisit and change this logic to be more consistent */
626531 if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
626532 cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
626533 FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
626534 DEBUGLOG(5, "Block too small, writing out nocompress block: cSize: %zu", cBlockSize);
626535 cSize += cBlockSize;
626536 ip += blockSize;
626537 op += cBlockSize;
626538 remaining -= blockSize;
626539 dstCapacity -= cBlockSize;
626540 continue;
626541 }
626542
626543 RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
626544 compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
626545 &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
626546 &cctx->appliedParams,
626547 op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
626548 blockSize,
626549 cctx->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
626550 cctx->bmi2);
626551 FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
626552 DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
626553
626554 if (!cctx->isFirstBlock &&
626555 ZSTD_maybeRLE(&cctx->seqStore) &&
626556 ZSTD_isRLE(ip, blockSize)) {
626557 /* We don't want to emit our first block as a RLE even if it qualifies because
626558 * doing so will cause the decoder (cli only) to throw a "should consume all input error."
626559 * This is only an issue for zstd <= v1.4.3
626560 */
626561 compressedSeqsSize = 1;
626562 }
626563
626564 if (compressedSeqsSize == 0) {
626565 /* ZSTD_noCompressBlock writes the block header as well */
626566 cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
626567 FORWARD_IF_ERROR(cBlockSize, "ZSTD_noCompressBlock failed");
626568 DEBUGLOG(5, "Writing out nocompress block, size: %zu", cBlockSize);
626569 } else if (compressedSeqsSize == 1) {
626570 cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
626571 FORWARD_IF_ERROR(cBlockSize, "ZSTD_rleCompressBlock failed");
626572 DEBUGLOG(5, "Writing out RLE block, size: %zu", cBlockSize);
626573 } else {
626574 U32 cBlockHeader;
626575 /* Error checking and repcodes update */
626576 ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
626577 if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
626578 cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
626579
626580 /* Write block header into beginning of block*/
626581 cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
626582 MEM_writeLE24(op, cBlockHeader);
626583 cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
626584 DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
626585 }
626586
626587 cSize += cBlockSize;
626588
626589 if (lastBlock) {
626590 break;
626591 } else {
626592 ip += blockSize;
626593 op += cBlockSize;
626594 remaining -= blockSize;
626595 dstCapacity -= cBlockSize;
626596 cctx->isFirstBlock = 0;

◆ inBuffer_forEndFlush()

ZSTD_inBuffer duckdb_zstd::inBuffer_forEndFlush ( const ZSTD_CStream * zcs)
static
626644 : %zu", cSize);
626645 return cSize;
626646}
626647
626648/*====== Finalize ======*/

◆ ZSTD_getCParamRowSize()

U64 duckdb_zstd::ZSTD_getCParamRowSize ( U64 srcSizeHint,
size_t dictSize,
ZSTD_cParamMode_e mode )
static
626888 :
626889 case ZSTD_btultra:
626890 case ZSTD_btultra2:
626891 break;
626892 }
626893}
626894
626895static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
626896{
626897 switch (mode) {
626898 case ZSTD_cpm_unknown:
626899 case ZSTD_cpm_noAttachDict:
626900 case ZSTD_cpm_createCDict:
626901 break;
626902 case ZSTD_cpm_attachDict:
626903 dictSize = 0;
626904 break;
626905 default:
626906 assert(0);

◆ allBytesIdentical()

int duckdb_zstd::allBytesIdentical ( const void * src,
size_t srcSize )
static
627077 : %u -> %u", (U32)srcSize, (U32)(srcSize + flSize));
627078 return srcSize + flSize;
627079}
627080
627081static int allBytesIdentical(const void* src, size_t srcSize)
627082{
627083 assert(srcSize >= 1);
627084 assert(src != NULL);
627085 { const BYTE b = ((const BYTE*)src)[0];

◆ ZSTD_minLiteralsToCompress()

size_t duckdb_zstd::ZSTD_minLiteralsToCompress ( ZSTD_strategy strategy,
HUF_repeat huf_repeat )
static
627129{
627130 assert((int)strategy >= 0);
627131 assert((int)strategy <= 9);
627132 /* btultra2 : min 8 bytes;
627133 * then 2x larger for each successive compression strategy

◆ ZSTD_getFSEMaxSymbolValue()

unsigned duckdb_zstd::ZSTD_getFSEMaxSymbolValue ( FSE_CTable const * ctable)
static

◆ ZSTD_useLowProbCount()

unsigned duckdb_zstd::ZSTD_useLowProbCount ( size_t const nbSeq)
static

Returns true if we should use ncount=-1 else we should use ncount=1 for low probability symbols instead.

◆ ZSTD_NCountCost()

size_t duckdb_zstd::ZSTD_NCountCost ( unsigned const * count,
unsigned const max,
size_t const nbSeq,
unsigned const FSELog )
static

Returns the cost in bytes of encoding the normalized count header. Returns an error if any of the helper functions return an error.

◆ ZSTD_entropyCost()

size_t duckdb_zstd::ZSTD_entropyCost ( unsigned const * count,
unsigned const max,
size_t const total )
static

Returns the cost in bits of encoding the distribution described by count using the entropy bound.

627346{
627347 unsigned cost = 0;
627348 unsigned s;
627349
627350 assert(total > 0);
627351 for (s = 0; s <= max; ++s) {
627352 unsigned norm = (unsigned)((256 * count[s]) / total);
Here is the call graph for this function:

◆ ZSTD_encodeSequences_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::ZSTD_encodeSequences_body ( void * dst,
size_t dstCapacity,
FSE_CTable const * CTable_MatchLength,
BYTE const * mlCodeTable,
FSE_CTable const * CTable_OffsetBits,
BYTE const * ofCodeTable,
FSE_CTable const * CTable_LitLength,
BYTE const * llCodeTable,
seqDef const * sequences,
size_t nbSeq,
int longOffsets )
627547 : assert(0); RETURN_ERROR(GENERIC, "impossible to reach");
627548 }
627549}
627550
627552ZSTD_encodeSequences_body(
627553 void* dst, size_t dstCapacity,
627554 FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
627555 FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
627556 FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
627557 seqDef const* sequences, size_t nbSeq, int longOffsets)
627558{
627559 BIT_CStream_t blockStream;
627560 FSE_CState_t stateMatchLength;
627561 FSE_CState_t stateOffsetBits;
627562 FSE_CState_t stateLitLength;
627563
627565 ERR_isError(BIT_initCStream(&blockStream, dst, dstCapacity)),
627566 dstSize_tooSmall, "not enough space remaining");
627567 DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
627568 (int)(blockStream.endPtr - blockStream.startPtr),
627569 (unsigned)dstCapacity);
627570
627571 /* first symbols */
627572 FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
627573 FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
627574 FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
627575 BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
627576 if (MEM_32bits()) BIT_flushBits(&blockStream);
627577 BIT_addBits(&blockStream, sequences[nbSeq-1].mlBase, ML_bits[mlCodeTable[nbSeq-1]]);
627578 if (MEM_32bits()) BIT_flushBits(&blockStream);
627579 if (longOffsets) {
627580 U32 const ofBits = ofCodeTable[nbSeq-1];
627581 unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
627582 if (extraBits) {
627583 BIT_addBits(&blockStream, sequences[nbSeq-1].offBase, extraBits);
627584 BIT_flushBits(&blockStream);
627585 }
627586 BIT_addBits(&blockStream, sequences[nbSeq-1].offBase >> extraBits,
627587 ofBits - extraBits);
627588 } else {
627589 BIT_addBits(&blockStream, sequences[nbSeq-1].offBase, ofCodeTable[nbSeq-1]);
627590 }
627591 BIT_flushBits(&blockStream);
627592
627593 { size_t n;
627594 for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
627595 BYTE const llCode = llCodeTable[n];
627596 BYTE const ofCode = ofCodeTable[n];
627597 BYTE const mlCode = mlCodeTable[n];
627598 U32 const llBits = LL_bits[llCode];
627599 U32 const ofBits = ofCode;
627600 U32 const mlBits = ML_bits[mlCode];
627601 DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
627602 (unsigned)sequences[n].litLength,
627603 (unsigned)sequences[n].mlBase + MINMATCH,
627604 (unsigned)sequences[n].offBase);
627605 /* 32b*/ /* 64b*/
627606 /* (7)*/ /* (7)*/
627607 FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
627608 FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
627609 if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
627610 FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
627611 if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
627612 BIT_flushBits(&blockStream); /* (7)*/
627613 BIT_addBits(&blockStream, sequences[n].litLength, llBits);
627614 if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
627615 BIT_addBits(&blockStream, sequences[n].mlBase, mlBits);
627616 if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
627617 if (longOffsets) {
627618 unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
627619 if (extraBits) {
627620 BIT_addBits(&blockStream, sequences[n].offBase, extraBits);
627621 BIT_flushBits(&blockStream); /* (7)*/
627622 }
627623 BIT_addBits(&blockStream, sequences[n].offBase >> extraBits,
627624 ofBits - extraBits); /* 31 */
627625 } else {
627626 BIT_addBits(&blockStream, sequences[n].offBase, ofBits); /* 31 */
627627 }
627628 BIT_flushBits(&blockStream); /* (7)*/
627629 DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
627630 } }
627631
627632 DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
627633 FSE_flushCState(&blockStream, &stateMatchLength);
627634 DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
627635 FSE_flushCState(&blockStream, &stateOffsetBits);
627636 DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);

◆ ZSTD_encodeSequences_default()

size_t duckdb_zstd::ZSTD_encodeSequences_default ( void * dst,
size_t dstCapacity,
FSE_CTable const * CTable_MatchLength,
BYTE const * mlCodeTable,
FSE_CTable const * CTable_OffsetBits,
BYTE const * ofCodeTable,
FSE_CTable const * CTable_LitLength,
BYTE const * llCodeTable,
seqDef const * sequences,
size_t nbSeq,
int longOffsets )
static
627639 { size_t const streamSize = BIT_closeCStream(&blockStream);
627640 RETURN_ERROR_IF(streamSize==0, dstSize_tooSmall, "not enough space");
627641 return streamSize;
627642 }
627643}
627644
627645static size_t
627646ZSTD_encodeSequences_default(
627647 void* dst, size_t dstCapacity,
627648 FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
627649 FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
627650 FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
627651 seqDef const* sequences, size_t nbSeq, int longOffsets)

◆ ZSTD_compressSubBlock_literal()

size_t duckdb_zstd::ZSTD_compressSubBlock_literal ( const HUF_CElt * hufTable,
const ZSTD_hufCTablesMetadata_t * hufMetadata,
const BYTE * literals,
size_t litSize,
void * dst,
size_t dstSize,
const int bmi2,
int writeEntropy,
int * entropyWritten )
static

ZSTD_compressSubBlock_literal() : Compresses literals section for a sub-block. When we have to write the Huffman table we will sometimes choose a header size larger than necessary. This is because we have to pick the header size before we know the table size + compressed size, so we have a bound on the table size. If we guessed incorrectly, we fall back to uncompressed literals.

We write the header when writeEntropy=1 and set entropyWritten=1 when we succeeded in writing the header, otherwise it is set to 0.

hufMetadata->hType has literals block type info. If it is set_basic, all sub-blocks literals section will be Raw_Literals_Block. If it is set_rle, all sub-blocks literals section will be RLE_Literals_Block. If it is set_compressed, first sub-block's literals section will be Compressed_Literals_Block If it is set_compressed, first sub-block's literals section will be Treeless_Literals_Block and the following sub-blocks' literals sections will be Treeless_Literals_Block.

Returns
: compressed size of literals section of a sub-block Or 0 if unable to compress. Or error code
627754 : compressed size of literals section of a sub-block
627755 * Or 0 if unable to compress.
627756 * Or error code */
627757static size_t
627758ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
627759 const ZSTD_hufCTablesMetadata_t* hufMetadata,
627760 const BYTE* literals, size_t litSize,
627761 void* dst, size_t dstSize,
627762 const int bmi2, int writeEntropy, int* entropyWritten)
627763{
627764 size_t const header = writeEntropy ? 200 : 0;
627765 size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));
627766 BYTE* const ostart = (BYTE*)dst;
627767 BYTE* const oend = ostart + dstSize;
627768 BYTE* op = ostart + lhSize;
627769 U32 const singleStream = lhSize == 3;
627770 symbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;
627771 size_t cLitSize = 0;
627772
627773 DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);
627774
627775 *entropyWritten = 0;
627776 if (litSize == 0 || hufMetadata->hType == set_basic) {
627777 DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");
627778 return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
627779 } else if (hufMetadata->hType == set_rle) {
627780 DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");
627781 return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);
627782 }
627783
627784 assert(litSize > 0);
627785 assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);
627786
627787 if (writeEntropy && hufMetadata->hType == set_compressed) {
627788 ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);
627789 op += hufMetadata->hufDesSize;
627790 cLitSize += hufMetadata->hufDesSize;
627791 DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);
627792 }
627793
627794 { int const flags = bmi2 ? HUF_flags_bmi2 : 0;
627795 const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags)
627796 : HUF_compress4X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags);
627797 op += cSize;
627798 cLitSize += cSize;
627799 if (cSize == 0 || ERR_isError(cSize)) {
627800 DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));
627801 return 0;
627802 }
627803 /* If we expand and we aren't writing a header then emit uncompressed */
627804 if (!writeEntropy && cLitSize >= litSize) {
627805 DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");
627806 return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
627807 }
627808 /* If we are writing headers then allow expansion that doesn't change our header size. */
627809 if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {
627810 assert(cLitSize > litSize);
627811 DEBUGLOG(5, "Literals expanded beyond allowed header size");
627812 return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
627813 }
627814 DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);
627815 }
627816
627817 /* Build header */
627818 switch(lhSize)
627819 {
627820 case 3: /* 2 - 2 - 10 - 10 */
627821 { U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
627822 MEM_writeLE24(ostart, lhc);
627823 break;
627824 }
627825 case 4: /* 2 - 2 - 14 - 14 */
627826 { U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);
627827 MEM_writeLE32(ostart, lhc);
627828 break;
627829 }
627830 case 5: /* 2 - 2 - 18 - 18 */
627831 { U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);
627832 MEM_writeLE32(ostart, lhc);
627833 ostart[4] = (BYTE)(cLitSize >> 10);
627834 break;
627835 }
static size_t ZSTD_compressSubBlock_literal(const HUF_CElt *hufTable, const ZSTD_hufCTablesMetadata_t *hufMetadata, const BYTE *literals, size_t litSize, void *dst, size_t dstSize, const int bmi2, int writeEntropy, int *entropyWritten)
Definition duckdb.cpp:627751
ZSTDLIB_API const char * ZSTD_getErrorName(size_t code)
Definition duckdb.cpp:614331
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_seqDecompressedSize()

size_t duckdb_zstd::ZSTD_seqDecompressedSize ( seqStore_t const * seqStore,
const seqDef * sequences,
size_t nbSeqs,
size_t litSize,
int lastSubBlock )
static
627840 : %u -> %u", (U32)litSize, (U32)(op-ostart));
627841 return (size_t)(op-ostart);
627842}
627843
627844static size_t
627845ZSTD_seqDecompressedSize(seqStore_t const* seqStore,
627846 const seqDef* sequences, size_t nbSeqs,
627847 size_t litSize, int lastSubBlock)
627848{
627849 size_t matchLengthSum = 0;
627850 size_t litLengthSum = 0;
627851 size_t n;
627852 for (n=0; n<nbSeqs; n++) {
627853 const ZSTD_sequenceLength seqLen = ZSTD_getSequenceLength(seqStore, sequences+n);
627854 litLengthSum += seqLen.litLength;
627855 matchLengthSum += seqLen.matchLength;
627856 }
627857 DEBUGLOG(5, "ZSTD_seqDecompressedSize: %u sequences from %p: %u literals + %u matchlength",
627858 (unsigned)nbSeqs, (const void*)sequences,
627859 (unsigned)litLengthSum, (unsigned)matchLengthSum);

◆ ZSTD_compressSubBlock_sequences()

size_t duckdb_zstd::ZSTD_compressSubBlock_sequences ( const ZSTD_fseCTables_t * fseTables,
const ZSTD_fseCTablesMetadata_t * fseMetadata,
const seqDef * sequences,
size_t nbSeq,
const BYTE * llCode,
const BYTE * mlCode,
const BYTE * ofCode,
const ZSTD_CCtx_params * cctxParams,
void * dst,
size_t dstCapacity,
const int bmi2,
int writeEntropy,
int * entropyWritten )
static

ZSTD_compressSubBlock_sequences() : Compresses sequences section for a sub-block. fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have symbol compression modes for the super-block. The first successfully compressed block will have these in its header. We set entropyWritten=1 when we succeed in compressing the sequences. The following sub-blocks will always have repeat mode.

Returns
: compressed size of sequences section of a sub-block Or 0 if it is unable to compress Or error code.
627875 : compressed size of sequences section of a sub-block
627876 * Or 0 if it is unable to compress
627877 * Or error code. */
627878static size_t
627880 const ZSTD_fseCTablesMetadata_t* fseMetadata,
627881 const seqDef* sequences, size_t nbSeq,
627882 const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
627883 const ZSTD_CCtx_params* cctxParams,
627884 void* dst, size_t dstCapacity,
627885 const int bmi2, int writeEntropy, int* entropyWritten)
627886{
627887 const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
627888 BYTE* const ostart = (BYTE*)dst;
627889 BYTE* const oend = ostart + dstCapacity;
627890 BYTE* op = ostart;
627891 BYTE* seqHead;
627892
627893 DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);
627894
627895 *entropyWritten = 0;
627896 /* Sequences Header */
627897 RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
627898 dstSize_tooSmall, "");
627899 if (nbSeq < 128)
627900 *op++ = (BYTE)nbSeq;
627901 else if (nbSeq < LONGNBSEQ)
627902 op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
627903 else
627904 op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
627905 if (nbSeq==0) {
627906 return (size_t)(op - ostart);
627907 }
627908
627909 /* seqHead : flags for FSE encoding type */
627910 seqHead = op++;
627911
627912 DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));
627913
627914 if (writeEntropy) {
627915 const U32 LLtype = fseMetadata->llType;
627916 const U32 Offtype = fseMetadata->ofType;
627917 const U32 MLtype = fseMetadata->mlType;
627918 DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);
627919 *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
627920 ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);
627921 op += fseMetadata->fseTablesSize;
627922 } else {
627923 const U32 repeat = set_repeat;
627924 *seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));
627925 }
627926
627927 { size_t const bitstreamSize = ZSTD_encodeSequences(
627928 op, (size_t)(oend - op),
627929 fseTables->matchlengthCTable, mlCode,
627930 fseTables->offcodeCTable, ofCode,
627931 fseTables->litlengthCTable, llCode,
627932 sequences, nbSeq,
627933 longOffsets, bmi2);
627934 FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
627935 op += bitstreamSize;
627936 /* zstd versions <= 1.3.4 mistakenly report corruption when
627937 * FSE_readNCount() receives a buffer < 4 bytes.
627938 * Fixed by https://github.com/facebook/zstd/pull/1146.
627939 * This can happen when the last set_compressed table present is 2
627940 * bytes and the bitstream is only one byte.
627941 * In this exceedingly rare case, we will simply emit an uncompressed
627942 * block, since it isn't worth optimizing.
627943 */
627944#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
627945 if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {
627946 /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
627947 assert(fseMetadata->lastCountSize + bitstreamSize == 3);
627948 DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
627949 "emitting an uncompressed block.");
627950 return 0;
627951 }
627952#endif
627953 DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);
627954 }
627955
627956 /* zstd versions <= 1.4.0 mistakenly report error when
627957 * sequences section body size is less than 3 bytes.
627958 * Fixed by https://github.com/facebook/zstd/pull/1664.
627959 * This can happen when the previous sequences section block is compressed
627960 * with rle mode and the current block's sequences section is compressed
627961 * with repeat mode where sequences section body size can be 1 byte.
627962 */
627963#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
627964 if (op-seqHead < 4) {
627965 DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "
627966 "an uncompressed block when sequences are < 4 bytes");
static size_t ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t *fseTables, const ZSTD_fseCTablesMetadata_t *fseMetadata, const seqDef *sequences, size_t nbSeq, const BYTE *llCode, const BYTE *mlCode, const BYTE *ofCode, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, const int bmi2, int writeEntropy, int *entropyWritten)
Definition duckdb.cpp:627872
Definition duckdb.cpp:617618
Definition duckdb.cpp:617585
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressSubBlock()

size_t duckdb_zstd::ZSTD_compressSubBlock ( const ZSTD_entropyCTables_t * entropy,
const ZSTD_entropyCTablesMetadata_t * entropyMetadata,
const seqDef * sequences,
size_t nbSeq,
const BYTE * literals,
size_t litSize,
const BYTE * llCode,
const BYTE * mlCode,
const BYTE * ofCode,
const ZSTD_CCtx_params * cctxParams,
void * dst,
size_t dstCapacity,
const int bmi2,
int writeLitEntropy,
int writeSeqEntropy,
int * litEntropyWritten,
int * seqEntropyWritten,
U32 lastBlock )
static

ZSTD_compressSubBlock() : Compresses a single sub-block.

Returns
: compressed size of the sub-block Or 0 if it failed to compress.
627990{
627991 BYTE* const ostart = (BYTE*)dst;
627992 BYTE* const oend = ostart + dstCapacity;
627993 BYTE* op = ostart + ZSTD_blockHeaderSize;
627994 DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",
627995 litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
627996 { size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
627997 &entropyMetadata->hufMetadata, literals, litSize,
627998 op, (size_t)(oend-op),
627999 bmi2, writeLitEntropy, litEntropyWritten);
628000 FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
628001 if (cLitSize == 0) return 0;
628002 op += cLitSize;
628003 }
628004 { size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,
628005 &entropyMetadata->fseMetadata,
628006 sequences, nbSeq,
628007 llCode, mlCode, ofCode,
628008 cctxParams,
628009 op, (size_t)(oend-op),
628010 bmi2, writeSeqEntropy, seqEntropyWritten);
628011 FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
628012 if (cSeqSize == 0) return 0;
628013 op += cSeqSize;
628014 }
Here is the caller graph for this function:

◆ ZSTD_estimateSubBlockSize_literal()

size_t duckdb_zstd::ZSTD_estimateSubBlockSize_literal ( const BYTE * literals,
size_t litSize,
const ZSTD_hufCTables_t * huf,
const ZSTD_hufCTablesMetadata_t * hufMetadata,
void * workspace,
size_t wkspSize,
int writeEntropy )
static
628016 { size_t cSize = (size_t)(op-ostart) - ZSTD_blockHeaderSize;
628017 U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
628018 MEM_writeLE24(ostart, cBlockHeader24);
628019 }
628020 return (size_t)(op-ostart);
628021}
628022
628023static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
628024 const ZSTD_hufCTables_t* huf,
628025 const ZSTD_hufCTablesMetadata_t* hufMetadata,
628026 void* workspace, size_t wkspSize,
628027 int writeEntropy)
628028{
628029 unsigned* const countWksp = (unsigned*)workspace;
628030 unsigned maxSymbolValue = 255;
628031 size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
628032
628033 if (hufMetadata->hType == set_basic) return litSize;
628034 else if (hufMetadata->hType == set_rle) return 1;
628035 else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
628036 size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
628037 if (ZSTD_isError(largest)) return litSize;

◆ ZSTD_estimateSubBlockSize_symbolType()

size_t duckdb_zstd::ZSTD_estimateSubBlockSize_symbolType ( symbolEncodingType_e type,
const BYTE * codeTable,
unsigned maxCode,
size_t nbSeq,
const FSE_CTable * fseCTable,
const U8 * additionalBits,
short const * defaultNorm,
U32 defaultNormLog,
U32 defaultMax,
void * workspace,
size_t wkspSize )
static
628052{
628053 unsigned* const countWksp = (unsigned*)workspace;
628054 const BYTE* ctp = codeTable;
628055 const BYTE* const ctStart = ctp;
628056 const BYTE* const ctEnd = ctStart + nbSeq;
628057 size_t cSymbolTypeSizeEstimateInBits = 0;
628058 unsigned max = maxCode;
628059
628060 HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */
628061 if (type == set_basic) {
628062 /* We selected this encoding type, so it must be valid. */
628063 assert(max <= defaultMax);
628064 cSymbolTypeSizeEstimateInBits = max <= defaultMax
628065 ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)
628066 : ERROR(GENERIC);
628067 } else if (type == set_rle) {
628068 cSymbolTypeSizeEstimateInBits = 0;
628069 } else if (type == set_compressed || type == set_repeat) {
628070 cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
628071 }
628072 if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;

◆ ZSTD_estimateSubBlockSize_sequences()

size_t duckdb_zstd::ZSTD_estimateSubBlockSize_sequences ( const BYTE * ofCodeTable,
const BYTE * llCodeTable,
const BYTE * mlCodeTable,
size_t nbSeq,
const ZSTD_fseCTables_t * fseTables,
const ZSTD_fseCTablesMetadata_t * fseMetadata,
void * workspace,
size_t wkspSize,
int writeEntropy )
static
628089{
628090 size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
628091 size_t cSeqSizeEstimate = 0;
628092 if (nbSeq == 0) return sequencesSectionHeaderSize;
628093 cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,
628094 nbSeq, fseTables->offcodeCTable, NULL,
628095 OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
628096 workspace, wkspSize);
628097 cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,
628098 nbSeq, fseTables->litlengthCTable, LL_bits,
628099 LL_defaultNorm, LL_defaultNormLog, MaxLL,
628100 workspace, wkspSize);

◆ ZSTD_estimateSubBlockSize()

EstimatedBlockSize duckdb_zstd::ZSTD_estimateSubBlockSize ( const BYTE * literals,
size_t litSize,
const BYTE * ofCodeTable,
const BYTE * llCodeTable,
const BYTE * mlCodeTable,
size_t nbSeq,
const ZSTD_entropyCTables_t * entropy,
const ZSTD_entropyCTablesMetadata_t * entropyMetadata,
void * workspace,
size_t wkspSize,
int writeLitEntropy,
int writeSeqEntropy )
static
628109 {
628110 size_t estLitSize;
628111 size_t estBlockSize;
628112} EstimatedBlockSize;
628113static EstimatedBlockSize ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
628114 const BYTE* ofCodeTable,
628115 const BYTE* llCodeTable,
628116 const BYTE* mlCodeTable,
628117 size_t nbSeq,
628118 const ZSTD_entropyCTables_t* entropy,
628119 const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
628120 void* workspace, size_t wkspSize,
628121 int writeLitEntropy, int writeSeqEntropy)
628122{
628123 EstimatedBlockSize ebs;
628124 ebs.estLitSize = ZSTD_estimateSubBlockSize_literal(literals, litSize,
628125 &entropy->huf, &entropyMetadata->hufMetadata,

◆ ZSTD_needSequenceEntropyTables()

int duckdb_zstd::ZSTD_needSequenceEntropyTables ( ZSTD_fseCTablesMetadata_t const * fseMetadata)
static
628135{
628136 if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)

◆ countLiterals()

size_t duckdb_zstd::countLiterals ( seqStore_t const * seqStore,
const seqDef * sp,
size_t seqCount )
static
628146{
628147 size_t n, total = 0;

◆ sizeBlockSequences()

size_t duckdb_zstd::sizeBlockSequences ( const seqDef * sp,
size_t nbSeqs,
size_t targetBudget,
size_t avgLitCost,
size_t avgSeqCost,
int firstSubBlock )
static
628161{
628162 size_t n, budget = 0, inSize=0;
628163 /* entropy headers */
628164 size_t const headerSize = (size_t)firstSubBlock * 120 * BYTESCALE; /* generous estimate */
628165 assert(firstSubBlock==0 || firstSubBlock==1);
628166 budget += headerSize;
628167
628168 /* first sequence => at least one sequence*/
628169 budget += sp[0].litLength * avgLitCost + avgSeqCost;
628170 if (budget > targetBudget) return 1;
628171 inSize = sp[0].litLength + (sp[0].mlBase+MINMATCH);
628172
628173 /* loop over sequences */
628174 for (n=1; n<nbSeqs; n++) {
628175 size_t currentCost = sp[n].litLength * avgLitCost + avgSeqCost;
628176 budget += currentCost;
628177 inSize += sp[n].litLength + (sp[n].mlBase+MINMATCH);
628178 /* stop when sub-block budget is reached */
628179 if ( (budget > targetBudget)

◆ ZSTD_compressSubBlock_multi()

size_t duckdb_zstd::ZSTD_compressSubBlock_multi ( const seqStore_t * seqStorePtr,
const ZSTD_compressedBlockState_t * prevCBlock,
ZSTD_compressedBlockState_t * nextCBlock,
const ZSTD_entropyCTablesMetadata_t * entropyMetadata,
const ZSTD_CCtx_params * cctxParams,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const int bmi2,
U32 lastBlock,
void * workspace,
size_t wkspSize )
static

ZSTD_compressSubBlock_multi() : Breaks super-block into multiple sub-blocks and compresses them. Entropy will be written into the first block. The following blocks use repeat_mode to compress. Sub-blocks are all compressed, except the last one when beneficial.

Returns
: compressed size of the super block (which features multiple ZSTD blocks) or 0 if it failed to compress.
628204{
628205 const seqDef* const sstart = seqStorePtr->sequencesStart;
628206 const seqDef* const send = seqStorePtr->sequences;
628207 const seqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */
628208 size_t const nbSeqs = (size_t)(send - sstart);
628209 const BYTE* const lstart = seqStorePtr->litStart;
628210 const BYTE* const lend = seqStorePtr->lit;
628211 const BYTE* lp = lstart;
628212 size_t const nbLiterals = (size_t)(lend - lstart);
628213 BYTE const* ip = (BYTE const*)src;
628214 BYTE const* const iend = ip + srcSize;
628215 BYTE* const ostart = (BYTE*)dst;
628216 BYTE* const oend = ostart + dstCapacity;
628217 BYTE* op = ostart;
628218 const BYTE* llCodePtr = seqStorePtr->llCode;
628219 const BYTE* mlCodePtr = seqStorePtr->mlCode;
628220 const BYTE* ofCodePtr = seqStorePtr->ofCode;
628221 size_t const minTarget = ZSTD_TARGETCBLOCKSIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */
628222 size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
628223 int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
628224 int writeSeqEntropy = 1;
628225
628226 DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
628227 (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
628228
628229 /* let's start by a general estimation for the full block */
628230 if (nbSeqs > 0) {
628231 EstimatedBlockSize const ebs =
628232 ZSTD_estimateSubBlockSize(lp, nbLiterals,
628233 ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
628234 &nextCBlock->entropy, entropyMetadata,
628235 workspace, wkspSize,
628236 writeLitEntropy, writeSeqEntropy);
628237 /* quick estimation */
628238 size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
628239 size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
628240 const size_t nbSubBlocks = MAX((ebs.estBlockSize + (targetCBlockSize/2)) / targetCBlockSize, 1);
628241 size_t n, avgBlockBudget, blockBudgetSupp=0;
628242 avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
628243 DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
628244 (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
628245 (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
628246 /* simplification: if estimates states that the full superblock doesn't compress, just bail out immediately
628247 * this will result in the production of a single uncompressed block covering @srcSize.*/
628248 if (ebs.estBlockSize > srcSize) return 0;
628249
628250 /* compress and write sub-blocks */
628251 assert(nbSubBlocks>0);
628252 for (n=0; n < nbSubBlocks-1; n++) {
628253 /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
628254 size_t const seqCount = sizeBlockSequences(sp, (size_t)(send-sp),
628255 avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
628256 /* if reached last sequence : break to last sub-block (simplification) */
628257 assert(seqCount <= (size_t)(send-sp));
628258 if (sp + seqCount == send) break;
628259 assert(seqCount > 0);
628260 /* compress sub-block */
628261 { int litEntropyWritten = 0;
628262 int seqEntropyWritten = 0;
628263 size_t litSize = countLiterals(seqStorePtr, sp, seqCount);
628264 const size_t decompressedSize =
628265 ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 0);
628266 size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
628267 sp, seqCount,
628268 lp, litSize,
628269 llCodePtr, mlCodePtr, ofCodePtr,
628270 cctxParams,
628271 op, (size_t)(oend-op),
628272 bmi2, writeLitEntropy, writeSeqEntropy,
628273 &litEntropyWritten, &seqEntropyWritten,
628274 0);
628275 FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
628276
628277 /* check compressibility, update state components */
628278 if (cSize > 0 && cSize < decompressedSize) {
628279 DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
628280 (unsigned)decompressedSize, (unsigned)cSize);
628281 assert(ip + decompressedSize <= iend);
628282 ip += decompressedSize;
628283 lp += litSize;
628284 op += cSize;
628285 llCodePtr += seqCount;
628286 mlCodePtr += seqCount;
628287 ofCodePtr += seqCount;
628288 /* Entropy only needs to be written once */
628289 if (litEntropyWritten) {
628290 writeLitEntropy = 0;
628291 }
628292 if (seqEntropyWritten) {
628293 writeSeqEntropy = 0;
628294 }
628295 sp += seqCount;
628296 blockBudgetSupp = 0;
628297 } }
628298 /* otherwise : do not compress yet, coalesce current sub-block with following one */
628299 }
628300 } /* if (nbSeqs > 0) */
628301
628302 /* write last block */
628303 DEBUGLOG(5, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
628304 { int litEntropyWritten = 0;
628305 int seqEntropyWritten = 0;
628306 size_t litSize = (size_t)(lend - lp);
628307 size_t seqCount = (size_t)(send - sp);
628308 const size_t decompressedSize =
628309 ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
628310 size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
628311 sp, seqCount,
628312 lp, litSize,
628313 llCodePtr, mlCodePtr, ofCodePtr,
628314 cctxParams,
628315 op, (size_t)(oend-op),
628316 bmi2, writeLitEntropy, writeSeqEntropy,
628317 &litEntropyWritten, &seqEntropyWritten,
628318 lastBlock);
628319 FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
628320
628321 /* update pointers, the nb of literals borrowed from next sequence must be preserved */
628322 if (cSize > 0 && cSize < decompressedSize) {
628323 DEBUGLOG(5, "Last sub-block compressed %u bytes => %u bytes",
628324 (unsigned)decompressedSize, (unsigned)cSize);
628325 assert(ip + decompressedSize <= iend);
628326 ip += decompressedSize;
628327 lp += litSize;
628328 op += cSize;
628329 llCodePtr += seqCount;
628330 mlCodePtr += seqCount;
628331 ofCodePtr += seqCount;
628332 /* Entropy only needs to be written once */
628333 if (litEntropyWritten) {
628334 writeLitEntropy = 0;
628335 }
628336 if (seqEntropyWritten) {
628337 writeSeqEntropy = 0;
628338 }
628339 sp += seqCount;
628340 }
628341 }
628342
628343
628344 if (writeLitEntropy) {
628345 DEBUGLOG(5, "Literal entropy tables were never written");
628346 ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
628347 }
628348 if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
628349 /* If we haven't written our entropy tables, then we've violated our contract and
628350 * must emit an uncompressed block.
628351 */
628352 DEBUGLOG(5, "Sequence entropy tables were never written => cancel, emit an uncompressed block");
628353 return 0;
628354 }
628355
628356 if (ip < iend) {
628357 /* some data left : last part of the block sent uncompressed */
628358 size_t const rSize = (size_t)((iend - ip));
628359 size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
628360 DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
628361 FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
628362 assert(cSize != 0);
628363 op += cSize;
628364 /* We have to regenerate the repcodes because we've skipped some sequences */
628365 if (sp < send) {
628366 const seqDef* seq;
628367 repcodes_t rep;
628368 ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
628369 for (seq = sstart; seq < sp; ++seq) {
628370 ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
628371 }
628372 ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const *seqStore, seqDef const *seq)
Definition duckdb.cpp:614236
static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t *entropy, const ZSTD_entropyCTablesMetadata_t *entropyMetadata, const seqDef *sequences, size_t nbSeq, const BYTE *literals, size_t litSize, const BYTE *llCode, const BYTE *mlCode, const BYTE *ofCode, const ZSTD_CCtx_params *cctxParams, void *dst, size_t dstCapacity, const int bmi2, int writeLitEntropy, int writeSeqEntropy, int *litEntropyWritten, int *seqEntropyWritten, U32 lastBlock)
Definition duckdb.cpp:627972
Definition duckdb.cpp:628102
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_fillDoubleHashTableForCDict()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_fillDoubleHashTableForCDict ( ZSTD_matchState_t * ms,
void const * end,
ZSTD_dictTableLoadMethod_e dtlm )
static
628429 {
628430
628431#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
628432
628433static
628435void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms,
628436 void const* end, ZSTD_dictTableLoadMethod_e dtlm)
628437{
628438 const ZSTD_compressionParameters* const cParams = &ms->cParams;
628439 U32* const hashLarge = ms->hashTable;
628440 U32 const hBitsL = cParams->hashLog + ZSTD_SHORT_CACHE_TAG_BITS;
628441 U32 const mls = cParams->minMatch;
628442 U32* const hashSmall = ms->chainTable;
628443 U32 const hBitsS = cParams->chainLog + ZSTD_SHORT_CACHE_TAG_BITS;
628444 const BYTE* const base = ms->window.base;
628445 const BYTE* ip = base + ms->nextToUpdate;
628446 const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
628447 const U32 fastHashFillStep = 3;
628448
628449 /* Always insert every fastHashFillStep position into the hash tables.
628450 * Insert the other positions into the large hash table if their entry
628451 * is empty.
628452 */
628453 for (; ip + fastHashFillStep - 1 <= iend; ip += fastHashFillStep) {
628454 U32 const curr = (U32)(ip - base);
628455 U32 i;
628456 for (i = 0; i < fastHashFillStep; ++i) {
628457 size_t const smHashAndTag = ZSTD_hashPtr(ip + i, hBitsS, mls);
628458 size_t const lgHashAndTag = ZSTD_hashPtr(ip + i, hBitsL, 8);
628459 if (i == 0) {
628460 ZSTD_writeTaggedIndex(hashSmall, smHashAndTag, curr + i);
628461 }
628462 if (i == 0 || hashLarge[lgHashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS] == 0) {
#define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
Definition duckdb.cpp:608284

◆ ZSTD_fillDoubleHashTableForCCtx()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_fillDoubleHashTableForCCtx ( ZSTD_matchState_t * ms,
void const * end,
ZSTD_dictTableLoadMethod_e dtlm )
static
628475{
628476 const ZSTD_compressionParameters* const cParams = &ms->cParams;
628477 U32* const hashLarge = ms->hashTable;
628478 U32 const hBitsL = cParams->hashLog;
628479 U32 const mls = cParams->minMatch;
628480 U32* const hashSmall = ms->chainTable;
628481 U32 const hBitsS = cParams->chainLog;
628482 const BYTE* const base = ms->window.base;
628483 const BYTE* ip = base + ms->nextToUpdate;
628484 const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
628485 const U32 fastHashFillStep = 3;
628486
628487 /* Always insert every fastHashFillStep position into the hash tables.
628488 * Insert the other positions into the large hash table if their entry
628489 * is empty.
628490 */
628491 for (; ip + fastHashFillStep - 1 <= iend; ip += fastHashFillStep) {
628492 U32 const curr = (U32)(ip - base);
628493 U32 i;
628494 for (i = 0; i < fastHashFillStep; ++i) {
628495 size_t const smHash = ZSTD_hashPtr(ip + i, hBitsS, mls);
628496 size_t const lgHash = ZSTD_hashPtr(ip + i, hBitsL, 8);
628497 if (i == 0)
628498 hashSmall[smHash] = curr + i;

◆ ZSTD_compressBlock_doubleFast_noDict_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_doubleFast_noDict_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls )
628525{
628526 ZSTD_compressionParameters const* cParams = &ms->cParams;
628527 U32* const hashLong = ms->hashTable;
628528 const U32 hBitsL = cParams->hashLog;
628529 U32* const hashSmall = ms->chainTable;
628530 const U32 hBitsS = cParams->chainLog;
628531 const BYTE* const base = ms->window.base;
628532 const BYTE* const istart = (const BYTE*)src;
628533 const BYTE* anchor = istart;
628534 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
628535 /* presumes that, if there is a dictionary, it must be using Attach mode */
628536 const U32 prefixLowestIndex = ZSTD_getLowestPrefixIndex(ms, endIndex, cParams->windowLog);
628537 const BYTE* const prefixLowest = base + prefixLowestIndex;
628538 const BYTE* const iend = istart + srcSize;
628539 const BYTE* const ilimit = iend - HASH_READ_SIZE;
628540 U32 offset_1=rep[0], offset_2=rep[1];
628541 U32 offsetSaved1 = 0, offsetSaved2 = 0;
628542
628543 size_t mLength;
628544 U32 offset;
628545 U32 curr;
628546
628547 /* how many positions to search before increasing step size */
628548 const size_t kStepIncr = 1 << kSearchStrength;
628549 /* the position at which to increment the step size if no match is found */
628550 const BYTE* nextStep;
628551 size_t step; /* the current step size */
628552
628553 size_t hl0; /* the long hash at ip */
628554 size_t hl1; /* the long hash at ip1 */
628555
628556 U32 idxl0; /* the long match index for ip */
628557 U32 idxl1; /* the long match index for ip1 */
628558
628559 const BYTE* matchl0; /* the long match for ip */
628560 const BYTE* matchs0; /* the short match for ip */
628561 const BYTE* matchl1; /* the long match for ip1 */
628562
628563 const BYTE* ip = istart; /* the current position */
628564 const BYTE* ip1; /* the next position */
628565
628566 DEBUGLOG(5, "ZSTD_compressBlock_doubleFast_noDict_generic");
628567
628568 /* init */
628569 ip += ((ip - prefixLowest) == 0);
628570 {
628571 U32 const current = (U32)(ip - base);
628572 U32 const windowLow = ZSTD_getLowestPrefixIndex(ms, current, cParams->windowLog);
628573 U32 const maxRep = current - windowLow;
628574 if (offset_2 > maxRep) offsetSaved2 = offset_2, offset_2 = 0;
628575 if (offset_1 > maxRep) offsetSaved1 = offset_1, offset_1 = 0;
628576 }
628577
628578 /* Outer Loop: one iteration per match found and stored */
628579 while (1) {
628580 step = 1;
628581 nextStep = ip + kStepIncr;
628582 ip1 = ip + step;
628583
628584 if (ip1 > ilimit) {
628585 goto _cleanup;
628586 }
628587
628588 hl0 = ZSTD_hashPtr(ip, hBitsL, 8);
628589 idxl0 = hashLong[hl0];
628590 matchl0 = base + idxl0;
628591
628592 /* Inner Loop: one iteration per search / position */
628593 do {
628594 const size_t hs0 = ZSTD_hashPtr(ip, hBitsS, mls);
628595 const U32 idxs0 = hashSmall[hs0];
628596 curr = (U32)(ip-base);
628597 matchs0 = base + idxs0;
628598
628599 hashLong[hl0] = hashSmall[hs0] = curr; /* update hash tables */
628600
628601 /* check noDict repcode */
628602 if ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1))) {
628603 mLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
628604 ip++;
628605 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, REPCODE1_TO_OFFBASE, mLength);
628606 goto _match_stored;
628607 }
628608
628609 hl1 = ZSTD_hashPtr(ip1, hBitsL, 8);
628610
628611 if (idxl0 > prefixLowestIndex) {
628612 /* check prefix long match */
628613 if (MEM_read64(matchl0) == MEM_read64(ip)) {
628614 mLength = ZSTD_count(ip+8, matchl0+8, iend) + 8;
628615 offset = (U32)(ip-matchl0);
628616 while (((ip>anchor) & (matchl0>prefixLowest)) && (ip[-1] == matchl0[-1])) { ip--; matchl0--; mLength++; } /* catch up */
628617 goto _match_found;
628618 }
628619 }
628620
628621 idxl1 = hashLong[hl1];
628622 matchl1 = base + idxl1;
628623
628624 if (idxs0 > prefixLowestIndex) {
628625 /* check prefix short match */
628626 if (MEM_read32(matchs0) == MEM_read32(ip)) {
628627 goto _search_next_long;
628628 }
628629 }
628630
628631 if (ip1 >= nextStep) {
628632 PREFETCH_L1(ip1 + 64);
628633 PREFETCH_L1(ip1 + 128);
628634 step++;
628635 nextStep += kStepIncr;
628636 }
628637 ip = ip1;
628638 ip1 += step;
628639
628640 hl0 = hl1;
628641 idxl0 = idxl1;
628642 matchl0 = matchl1;
628643 #if defined(__aarch64__)
628644 PREFETCH_L1(ip+256);
628645 #endif
628646 } while (ip1 <= ilimit);
628647
628648_cleanup:
628649 /* If offset_1 started invalid (offsetSaved1 != 0) and became valid (offset_1 != 0),
628650 * rotate saved offsets. See comment in ZSTD_compressBlock_fast_noDict for more context. */
628651 offsetSaved2 = ((offsetSaved1 != 0) && (offset_1 != 0)) ? offsetSaved1 : offsetSaved2;
628652
628653 /* save reps for next block */
628654 rep[0] = offset_1 ? offset_1 : offsetSaved1;
628655 rep[1] = offset_2 ? offset_2 : offsetSaved2;
628656
628657 /* Return the last literals size */
628658 return (size_t)(iend - anchor);
628659
628660_search_next_long:
628661
628662 /* check prefix long +1 match */
628663 if (idxl1 > prefixLowestIndex) {
628664 if (MEM_read64(matchl1) == MEM_read64(ip1)) {
628665 ip = ip1;
628666 mLength = ZSTD_count(ip+8, matchl1+8, iend) + 8;
628667 offset = (U32)(ip-matchl1);
628668 while (((ip>anchor) & (matchl1>prefixLowest)) && (ip[-1] == matchl1[-1])) { ip--; matchl1--; mLength++; } /* catch up */
628669 goto _match_found;
628670 }
628671 }
628672
628673 /* if no long +1 match, explore the short match we found */
628674 mLength = ZSTD_count(ip+4, matchs0+4, iend) + 4;
628675 offset = (U32)(ip - matchs0);
628676 while (((ip>anchor) & (matchs0>prefixLowest)) && (ip[-1] == matchs0[-1])) { ip--; matchs0--; mLength++; } /* catch up */
628677
628678 /* fall-through */
628679
628680_match_found: /* requires ip, offset, mLength */
628681 offset_2 = offset_1;
628682 offset_1 = offset;
628683
628684 if (step < 4) {
628685 /* It is unsafe to write this value back to the hashtable when ip1 is
628686 * greater than or equal to the new ip we will have after we're done
628687 * processing this match. Rather than perform that test directly
628688 * (ip1 >= ip + mLength), which costs speed in practice, we do a simpler
628689 * more predictable test. The minmatch even if we take a short match is
628690 * 4 bytes, so as long as step, the distance between ip and ip1
628691 * (initially) is less than 4, we know ip1 < new ip. */
628692 hashLong[hl1] = (U32)(ip1 - base);
628693 }
628694
628695 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
628696
628697_match_stored:
628698 /* match found */
628699 ip += mLength;
628700 anchor = ip;
628701
628702 if (ip <= ilimit) {
628703 /* Complementary insertion */
628704 /* done after iLimit test, as candidates could be > iend-8 */
628705 { U32 const indexToInsert = curr+2;
628706 hashLong[ZSTD_hashPtr(base+indexToInsert, hBitsL, 8)] = indexToInsert;
628707 hashLong[ZSTD_hashPtr(ip-2, hBitsL, 8)] = (U32)(ip-2-base);
628708 hashSmall[ZSTD_hashPtr(base+indexToInsert, hBitsS, mls)] = indexToInsert;
628709 hashSmall[ZSTD_hashPtr(ip-1, hBitsS, mls)] = (U32)(ip-1-base);
628710 }
628711
628712 /* check immediate repcode */
628713 while ( (ip <= ilimit)
628714 && ( (offset_2>0)
628715 & (MEM_read32(ip) == MEM_read32(ip - offset_2)) )) {
628716 /* store sequence */
628717 size_t const rLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
628718 U32 const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; /* swap offset_2 <=> offset_1 */
628719 hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = (U32)(ip-base);
628720 hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = (U32)(ip-base);
628721 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, rLength);

◆ ZSTD_compressBlock_doubleFast_dictMatchState_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_doubleFast_dictMatchState_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls )
628737{
628738 ZSTD_compressionParameters const* cParams = &ms->cParams;
628739 U32* const hashLong = ms->hashTable;
628740 const U32 hBitsL = cParams->hashLog;
628741 U32* const hashSmall = ms->chainTable;
628742 const U32 hBitsS = cParams->chainLog;
628743 const BYTE* const base = ms->window.base;
628744 const BYTE* const istart = (const BYTE*)src;
628745 const BYTE* ip = istart;
628746 const BYTE* anchor = istart;
628747 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
628748 /* presumes that, if there is a dictionary, it must be using Attach mode */
628749 const U32 prefixLowestIndex = ZSTD_getLowestPrefixIndex(ms, endIndex, cParams->windowLog);
628750 const BYTE* const prefixLowest = base + prefixLowestIndex;
628751 const BYTE* const iend = istart + srcSize;
628752 const BYTE* const ilimit = iend - HASH_READ_SIZE;
628753 U32 offset_1=rep[0], offset_2=rep[1];
628754
628755 const ZSTD_matchState_t* const dms = ms->dictMatchState;
628756 const ZSTD_compressionParameters* const dictCParams = &dms->cParams;
628757 const U32* const dictHashLong = dms->hashTable;
628758 const U32* const dictHashSmall = dms->chainTable;
628759 const U32 dictStartIndex = dms->window.dictLimit;
628760 const BYTE* const dictBase = dms->window.base;
628761 const BYTE* const dictStart = dictBase + dictStartIndex;
628762 const BYTE* const dictEnd = dms->window.nextSrc;
628763 const U32 dictIndexDelta = prefixLowestIndex - (U32)(dictEnd - dictBase);
628764 const U32 dictHBitsL = dictCParams->hashLog + ZSTD_SHORT_CACHE_TAG_BITS;
628765 const U32 dictHBitsS = dictCParams->chainLog + ZSTD_SHORT_CACHE_TAG_BITS;
628766 const U32 dictAndPrefixLength = (U32)((ip - prefixLowest) + (dictEnd - dictStart));
628767
628768 DEBUGLOG(5, "ZSTD_compressBlock_doubleFast_dictMatchState_generic");
628769
628770 /* if a dictionary is attached, it must be within window range */
628771 assert(ms->window.dictLimit + (1U << cParams->windowLog) >= endIndex);
628772
628773 if (ms->prefetchCDictTables) {
628774 size_t const hashTableBytes = (((size_t)1) << dictCParams->hashLog) * sizeof(U32);
628775 size_t const chainTableBytes = (((size_t)1) << dictCParams->chainLog) * sizeof(U32);
628776 PREFETCH_AREA(dictHashLong, hashTableBytes);
628777 PREFETCH_AREA(dictHashSmall, chainTableBytes);
628778 }
628779
628780 /* init */
628781 ip += (dictAndPrefixLength == 0);
628782
628783 /* dictMatchState repCode checks don't currently handle repCode == 0
628784 * disabling. */
628785 assert(offset_1 <= dictAndPrefixLength);
628786 assert(offset_2 <= dictAndPrefixLength);
628787
628788 /* Main Search Loop */
628789 while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */
628790 size_t mLength;
628791 U32 offset;
628792 size_t const h2 = ZSTD_hashPtr(ip, hBitsL, 8);
628793 size_t const h = ZSTD_hashPtr(ip, hBitsS, mls);
628794 size_t const dictHashAndTagL = ZSTD_hashPtr(ip, dictHBitsL, 8);
628795 size_t const dictHashAndTagS = ZSTD_hashPtr(ip, dictHBitsS, mls);
628796 U32 const dictMatchIndexAndTagL = dictHashLong[dictHashAndTagL >> ZSTD_SHORT_CACHE_TAG_BITS];
628797 U32 const dictMatchIndexAndTagS = dictHashSmall[dictHashAndTagS >> ZSTD_SHORT_CACHE_TAG_BITS];
628798 int const dictTagsMatchL = ZSTD_comparePackedTags(dictMatchIndexAndTagL, dictHashAndTagL);
628799 int const dictTagsMatchS = ZSTD_comparePackedTags(dictMatchIndexAndTagS, dictHashAndTagS);
628800 U32 const curr = (U32)(ip-base);
628801 U32 const matchIndexL = hashLong[h2];
628802 U32 matchIndexS = hashSmall[h];
628803 const BYTE* matchLong = base + matchIndexL;
628804 const BYTE* match = base + matchIndexS;
628805 const U32 repIndex = curr + 1 - offset_1;
628806 const BYTE* repMatch = (repIndex < prefixLowestIndex) ?
628807 dictBase + (repIndex - dictIndexDelta) :
628808 base + repIndex;
628809 hashLong[h2] = hashSmall[h] = curr; /* update hash tables */
628810
628811 /* check repcode */
628812 if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
628813 && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
628814 const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
628815 mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
628816 ip++;
628817 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, REPCODE1_TO_OFFBASE, mLength);
628818 goto _match_stored;
628819 }
628820
628821 if (matchIndexL > prefixLowestIndex) {
628822 /* check prefix long match */
628823 if (MEM_read64(matchLong) == MEM_read64(ip)) {
628824 mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8;
628825 offset = (U32)(ip-matchLong);
628826 while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
628827 goto _match_found;
628828 }
628829 } else if (dictTagsMatchL) {
628830 /* check dictMatchState long match */
628831 U32 const dictMatchIndexL = dictMatchIndexAndTagL >> ZSTD_SHORT_CACHE_TAG_BITS;
628832 const BYTE* dictMatchL = dictBase + dictMatchIndexL;
628833 assert(dictMatchL < dictEnd);
628834
628835 if (dictMatchL > dictStart && MEM_read64(dictMatchL) == MEM_read64(ip)) {
628836 mLength = ZSTD_count_2segments(ip+8, dictMatchL+8, iend, dictEnd, prefixLowest) + 8;
628837 offset = (U32)(curr - dictMatchIndexL - dictIndexDelta);
628838 while (((ip>anchor) & (dictMatchL>dictStart)) && (ip[-1] == dictMatchL[-1])) { ip--; dictMatchL--; mLength++; } /* catch up */
628839 goto _match_found;
628840 } }
628841
628842 if (matchIndexS > prefixLowestIndex) {
628843 /* check prefix short match */
628844 if (MEM_read32(match) == MEM_read32(ip)) {
628845 goto _search_next_long;
628846 }
628847 } else if (dictTagsMatchS) {
628848 /* check dictMatchState short match */
628849 U32 const dictMatchIndexS = dictMatchIndexAndTagS >> ZSTD_SHORT_CACHE_TAG_BITS;
628850 match = dictBase + dictMatchIndexS;
628851 matchIndexS = dictMatchIndexS + dictIndexDelta;
628852
628853 if (match > dictStart && MEM_read32(match) == MEM_read32(ip)) {
628854 goto _search_next_long;
628855 } }
628856
628857 ip += ((ip-anchor) >> kSearchStrength) + 1;
628858#if defined(__aarch64__)
628859 PREFETCH_L1(ip+256);
628860#endif
628861 continue;
628862
628863_search_next_long:
628864 { size_t const hl3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
628865 size_t const dictHashAndTagL3 = ZSTD_hashPtr(ip+1, dictHBitsL, 8);
628866 U32 const matchIndexL3 = hashLong[hl3];
628867 U32 const dictMatchIndexAndTagL3 = dictHashLong[dictHashAndTagL3 >> ZSTD_SHORT_CACHE_TAG_BITS];
628868 int const dictTagsMatchL3 = ZSTD_comparePackedTags(dictMatchIndexAndTagL3, dictHashAndTagL3);
628869 const BYTE* matchL3 = base + matchIndexL3;
628870 hashLong[hl3] = curr + 1;
628871
628872 /* check prefix long +1 match */
628873 if (matchIndexL3 > prefixLowestIndex) {
628874 if (MEM_read64(matchL3) == MEM_read64(ip+1)) {
628875 mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8;
628876 ip++;
628877 offset = (U32)(ip-matchL3);
628878 while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */
628879 goto _match_found;
628880 }
628881 } else if (dictTagsMatchL3) {
628882 /* check dict long +1 match */
628883 U32 const dictMatchIndexL3 = dictMatchIndexAndTagL3 >> ZSTD_SHORT_CACHE_TAG_BITS;
628884 const BYTE* dictMatchL3 = dictBase + dictMatchIndexL3;
628885 assert(dictMatchL3 < dictEnd);
628886 if (dictMatchL3 > dictStart && MEM_read64(dictMatchL3) == MEM_read64(ip+1)) {
628887 mLength = ZSTD_count_2segments(ip+1+8, dictMatchL3+8, iend, dictEnd, prefixLowest) + 8;
628888 ip++;
628889 offset = (U32)(curr + 1 - dictMatchIndexL3 - dictIndexDelta);
628890 while (((ip>anchor) & (dictMatchL3>dictStart)) && (ip[-1] == dictMatchL3[-1])) { ip--; dictMatchL3--; mLength++; } /* catch up */
628891 goto _match_found;
628892 } } }
628893
628894 /* if no long +1 match, explore the short match we found */
628895 if (matchIndexS < prefixLowestIndex) {
628896 mLength = ZSTD_count_2segments(ip+4, match+4, iend, dictEnd, prefixLowest) + 4;
628897 offset = (U32)(curr - matchIndexS);
628898 while (((ip>anchor) & (match>dictStart)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
628899 } else {
628900 mLength = ZSTD_count(ip+4, match+4, iend) + 4;
628901 offset = (U32)(ip - match);
628902 while (((ip>anchor) & (match>prefixLowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
628903 }
628904
628905_match_found:
628906 offset_2 = offset_1;
628907 offset_1 = offset;
628908
628909 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
628910
628911_match_stored:
628912 /* match found */
628913 ip += mLength;
628914 anchor = ip;
628915
628916 if (ip <= ilimit) {
628917 /* Complementary insertion */
628918 /* done after iLimit test, as candidates could be > iend-8 */
628919 { U32 const indexToInsert = curr+2;
628920 hashLong[ZSTD_hashPtr(base+indexToInsert, hBitsL, 8)] = indexToInsert;
628921 hashLong[ZSTD_hashPtr(ip-2, hBitsL, 8)] = (U32)(ip-2-base);
628922 hashSmall[ZSTD_hashPtr(base+indexToInsert, hBitsS, mls)] = indexToInsert;
628923 hashSmall[ZSTD_hashPtr(ip-1, hBitsS, mls)] = (U32)(ip-1-base);
628924 }
628925
628926 /* check immediate repcode */
628927 while (ip <= ilimit) {
628928 U32 const current2 = (U32)(ip-base);
628929 U32 const repIndex2 = current2 - offset_2;
628930 const BYTE* repMatch2 = repIndex2 < prefixLowestIndex ?
628931 dictBase + repIndex2 - dictIndexDelta :
628932 base + repIndex2;
628933 if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */)
628934 && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
628935 const BYTE* const repEnd2 = repIndex2 < prefixLowestIndex ? dictEnd : iend;
628936 size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixLowest) + 4;
628937 U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
628938 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, repLength2);
628939 hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = current2;
628940 hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = current2;
628941 ip += repLength2;
628942 anchor = ip;
628943 continue;
628944 }
628945 break;
628946 }
628947 }
628948 } /* while (ip < ilimit) */
628949
MEM_STATIC size_t ZSTD_count_2segments(const BYTE *ip, const BYTE *match, const BYTE *iEnd, const BYTE *mEnd, const BYTE *iStart)
Definition duckdb.cpp:618289

◆ ZSTD_compressBlock_doubleFast_extDict_generic()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_doubleFast_extDict_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls )
static
629023{
629024 ZSTD_compressionParameters const* cParams = &ms->cParams;
629025 U32* const hashLong = ms->hashTable;
629026 U32 const hBitsL = cParams->hashLog;
629027 U32* const hashSmall = ms->chainTable;
629028 U32 const hBitsS = cParams->chainLog;
629029 const BYTE* const istart = (const BYTE*)src;
629030 const BYTE* ip = istart;
629031 const BYTE* anchor = istart;
629032 const BYTE* const iend = istart + srcSize;
629033 const BYTE* const ilimit = iend - 8;
629034 const BYTE* const base = ms->window.base;
629035 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
629036 const U32 lowLimit = ZSTD_getLowestMatchIndex(ms, endIndex, cParams->windowLog);
629037 const U32 dictStartIndex = lowLimit;
629038 const U32 dictLimit = ms->window.dictLimit;
629039 const U32 prefixStartIndex = (dictLimit > lowLimit) ? dictLimit : lowLimit;
629040 const BYTE* const prefixStart = base + prefixStartIndex;
629041 const BYTE* const dictBase = ms->window.dictBase;
629042 const BYTE* const dictStart = dictBase + dictStartIndex;
629043 const BYTE* const dictEnd = dictBase + prefixStartIndex;
629044 U32 offset_1=rep[0], offset_2=rep[1];
629045
629046 DEBUGLOG(5, "ZSTD_compressBlock_doubleFast_extDict_generic (srcSize=%zu)", srcSize);
629047
629048 /* if extDict is invalidated due to maxDistance, switch to "regular" variant */
629049 if (prefixStartIndex == dictStartIndex)
629050 return ZSTD_compressBlock_doubleFast(ms, seqStore, rep, src, srcSize);
629051
629052 /* Search Loop */
629053 while (ip < ilimit) { /* < instead of <=, because (ip+1) */
629054 const size_t hSmall = ZSTD_hashPtr(ip, hBitsS, mls);
629055 const U32 matchIndex = hashSmall[hSmall];
629056 const BYTE* const matchBase = matchIndex < prefixStartIndex ? dictBase : base;
629057 const BYTE* match = matchBase + matchIndex;
629058
629059 const size_t hLong = ZSTD_hashPtr(ip, hBitsL, 8);
629060 const U32 matchLongIndex = hashLong[hLong];
629061 const BYTE* const matchLongBase = matchLongIndex < prefixStartIndex ? dictBase : base;
629062 const BYTE* matchLong = matchLongBase + matchLongIndex;
629063
629064 const U32 curr = (U32)(ip-base);
629065 const U32 repIndex = curr + 1 - offset_1; /* offset_1 expected <= curr +1 */
629066 const BYTE* const repBase = repIndex < prefixStartIndex ? dictBase : base;
629067 const BYTE* const repMatch = repBase + repIndex;
629068 size_t mLength;
629069 hashSmall[hSmall] = hashLong[hLong] = curr; /* update hash table */
629070
629071 if ((((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow : ensure repIndex doesn't overlap dict + prefix */
629072 & (offset_1 <= curr+1 - dictStartIndex)) /* note: we are searching at curr+1 */
629073 && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
629074 const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
629075 mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixStart) + 4;
629076 ip++;
629077 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, REPCODE1_TO_OFFBASE, mLength);
629078 } else {
629079 if ((matchLongIndex > dictStartIndex) && (MEM_read64(matchLong) == MEM_read64(ip))) {
629080 const BYTE* const matchEnd = matchLongIndex < prefixStartIndex ? dictEnd : iend;
629081 const BYTE* const lowMatchPtr = matchLongIndex < prefixStartIndex ? dictStart : prefixStart;
629082 U32 offset;
629083 mLength = ZSTD_count_2segments(ip+8, matchLong+8, iend, matchEnd, prefixStart) + 8;
629084 offset = curr - matchLongIndex;
629085 while (((ip>anchor) & (matchLong>lowMatchPtr)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
629086 offset_2 = offset_1;
629087 offset_1 = offset;
629088 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
629089
629090 } else if ((matchIndex > dictStartIndex) && (MEM_read32(match) == MEM_read32(ip))) {
629091 size_t const h3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
629092 U32 const matchIndex3 = hashLong[h3];
629093 const BYTE* const match3Base = matchIndex3 < prefixStartIndex ? dictBase : base;
629094 const BYTE* match3 = match3Base + matchIndex3;
629095 U32 offset;
629096 hashLong[h3] = curr + 1;
629097 if ( (matchIndex3 > dictStartIndex) && (MEM_read64(match3) == MEM_read64(ip+1)) ) {
629098 const BYTE* const matchEnd = matchIndex3 < prefixStartIndex ? dictEnd : iend;
629099 const BYTE* const lowMatchPtr = matchIndex3 < prefixStartIndex ? dictStart : prefixStart;
629100 mLength = ZSTD_count_2segments(ip+9, match3+8, iend, matchEnd, prefixStart) + 8;
629101 ip++;
629102 offset = curr+1 - matchIndex3;
629103 while (((ip>anchor) & (match3>lowMatchPtr)) && (ip[-1] == match3[-1])) { ip--; match3--; mLength++; } /* catch up */
629104 } else {
629105 const BYTE* const matchEnd = matchIndex < prefixStartIndex ? dictEnd : iend;
629106 const BYTE* const lowMatchPtr = matchIndex < prefixStartIndex ? dictStart : prefixStart;
629107 mLength = ZSTD_count_2segments(ip+4, match+4, iend, matchEnd, prefixStart) + 4;
629108 offset = curr - matchIndex;
629109 while (((ip>anchor) & (match>lowMatchPtr)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
629110 }
629111 offset_2 = offset_1;
629112 offset_1 = offset;
629113 ZSTD_storeSeq(seqStore, (size_t)(ip-anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
629114
629115 } else {
629116 ip += ((ip-anchor) >> kSearchStrength) + 1;
629117 continue;
629118 } }
629119
629120 /* move to next sequence start */
629121 ip += mLength;
629122 anchor = ip;
629123
629124 if (ip <= ilimit) {
629125 /* Complementary insertion */
629126 /* done after iLimit test, as candidates could be > iend-8 */
629127 { U32 const indexToInsert = curr+2;
629128 hashLong[ZSTD_hashPtr(base+indexToInsert, hBitsL, 8)] = indexToInsert;
629129 hashLong[ZSTD_hashPtr(ip-2, hBitsL, 8)] = (U32)(ip-2-base);
629130 hashSmall[ZSTD_hashPtr(base+indexToInsert, hBitsS, mls)] = indexToInsert;
629131 hashSmall[ZSTD_hashPtr(ip-1, hBitsS, mls)] = (U32)(ip-1-base);
629132 }
629133
629134 /* check immediate repcode */
629135 while (ip <= ilimit) {
629136 U32 const current2 = (U32)(ip-base);
629137 U32 const repIndex2 = current2 - offset_2;
629138 const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2;
629139 if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) /* intentional overflow : ensure repIndex2 doesn't overlap dict + prefix */
629140 & (offset_2 <= current2 - dictStartIndex))
629141 && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
629142 const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
629143 size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
629144 U32 const tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
629145 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, repLength2);
629146 hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = current2;
629147 hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = current2;
629148 ip += repLength2;
629149 anchor = ip;
629150 continue;
629151 }
629152 break;
629153 } } }
629154
MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t *ms, U32 curr, unsigned windowLog)
Definition duckdb.cpp:618802

◆ ZSTD_fillHashTableForCDict()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_fillHashTableForCDict ( ZSTD_matchState_t * ms,
const void *const end,
ZSTD_dictTableLoadMethod_e dtlm )
static
629212 {
629213
629214static
629216void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms,
629217 const void* const end,
629218 ZSTD_dictTableLoadMethod_e dtlm)
629219{
629220 const ZSTD_compressionParameters* const cParams = &ms->cParams;
629221 U32* const hashTable = ms->hashTable;
629222 U32 const hBits = cParams->hashLog + ZSTD_SHORT_CACHE_TAG_BITS;
629223 U32 const mls = cParams->minMatch;
629224 const BYTE* const base = ms->window.base;
629225 const BYTE* ip = base + ms->nextToUpdate;
629226 const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
629227 const U32 fastHashFillStep = 3;
629228
629229 /* Currently, we always use ZSTD_dtlm_full for filling CDict tables.
629230 * Feel free to remove this assert if there's a good reason! */
629231 assert(dtlm == ZSTD_dtlm_full);
629232
629233 /* Always insert every fastHashFillStep position into the hash table.
629234 * Insert the other positions if their hash entry is empty.
629235 */
629236 for ( ; ip + fastHashFillStep < iend + 2; ip += fastHashFillStep) {
629237 U32 const curr = (U32)(ip - base);
629238 { size_t const hashAndTag = ZSTD_hashPtr(ip, hBits, mls);
629239 ZSTD_writeTaggedIndex(hashTable, hashAndTag, curr); }
629240
629241 if (dtlm == ZSTD_dtlm_fast) continue;
629242 /* Only load extra positions for ZSTD_dtlm_full */

◆ ZSTD_fillHashTableForCCtx()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_fillHashTableForCCtx ( ZSTD_matchState_t * ms,
const void *const end,
ZSTD_dictTableLoadMethod_e dtlm )
static
629246 { /* not yet filled */
629247 ZSTD_writeTaggedIndex(hashTable, hashAndTag, curr + p);
629248 } } } }
629249}
629250
629251static
629253void ZSTD_fillHashTableForCCtx(ZSTD_matchState_t* ms,
629254 const void* const end,
629255 ZSTD_dictTableLoadMethod_e dtlm)
629256{
629257 const ZSTD_compressionParameters* const cParams = &ms->cParams;
629258 U32* const hashTable = ms->hashTable;
629259 U32 const hBits = cParams->hashLog;
629260 U32 const mls = cParams->minMatch;
629261 const BYTE* const base = ms->window.base;
629262 const BYTE* ip = base + ms->nextToUpdate;
629263 const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
629264 const U32 fastHashFillStep = 3;
629265
629266 /* Currently, we always use ZSTD_dtlm_fast for filling CCtx tables.
629267 * Feel free to remove this assert if there's a good reason! */
629268 assert(dtlm == ZSTD_dtlm_fast);
629269
629270 /* Always insert every fastHashFillStep position into the hash table.
629271 * Insert the other positions if their hash entry is empty.
629272 */
629273 for ( ; ip + fastHashFillStep < iend + 2; ip += fastHashFillStep) {
629274 U32 const curr = (U32)(ip - base);
629275 size_t const hash0 = ZSTD_hashPtr(ip, hBits, mls);
629276 hashTable[hash0] = curr;
629277 if (dtlm == ZSTD_dtlm_fast) continue;
629278 /* Only load extra positions for ZSTD_dtlm_full */

◆ ZSTD_compressBlock_fast_noDict_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_fast_noDict_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls,
U32 const hasStep )

If you squint hard enough (and ignore repcodes), the search operation at any given position is broken into 4 stages:

  1. Hash (map position to hash value via input read)
  2. Lookup (map hash val to index via hashtable read)
  3. Load (map index to value at that position via input read)
  4. Compare

Each of these steps involves a memory read at an address which is computed from the previous step. This means these steps must be sequenced and their latencies are cumulative.

Rather than do 1->2->3->4 sequentially for a single position before moving onto the next, this implementation interleaves these operations across the next few positions:

R = Repcode Read & Compare H = Hash T = Table Lookup M = Match Read & Compare

Pos | Time --> -—+----------------— N | ... M N+1 | ... TM N+2 | R H T M N+3 | H TM N+4 | R H T M N+5 | H ... N+6 | R ...

This is very much analogous to the pipelining of execution in a CPU. And just like a CPU, we have to dump the pipeline when we find a match (i.e., take a branch).

When this happens, we throw away our current state, and do the following prep to re-enter the loop:

Pos | Time --> -—+----------------— N | H T N+1 | H

This is also the work we do at the beginning to enter the loop initially.

629352{
629353 const ZSTD_compressionParameters* const cParams = &ms->cParams;
629354 U32* const hashTable = ms->hashTable;
629355 U32 const hlog = cParams->hashLog;
629356 /* support stepSize of 0 */
629357 size_t const stepSize = hasStep ? (cParams->targetLength + !(cParams->targetLength) + 1) : 2;
629358 const BYTE* const base = ms->window.base;
629359 const BYTE* const istart = (const BYTE*)src;
629360 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
629361 const U32 prefixStartIndex = ZSTD_getLowestPrefixIndex(ms, endIndex, cParams->windowLog);
629362 const BYTE* const prefixStart = base + prefixStartIndex;
629363 const BYTE* const iend = istart + srcSize;
629364 const BYTE* const ilimit = iend - HASH_READ_SIZE;
629365
629366 const BYTE* anchor = istart;
629367 const BYTE* ip0 = istart;
629368 const BYTE* ip1;
629369 const BYTE* ip2;
629370 const BYTE* ip3;
629371 U32 current0;
629372
629373 U32 rep_offset1 = rep[0];
629374 U32 rep_offset2 = rep[1];
629375 U32 offsetSaved1 = 0, offsetSaved2 = 0;
629376
629377 size_t hash0; /* hash for ip0 */
629378 size_t hash1; /* hash for ip1 */
629379 U32 idx; /* match idx for ip0 */
629380 U32 mval; /* src value at match idx */
629381
629382 U32 offcode;
629383 const BYTE* match0;
629384 size_t mLength;
629385
629386 /* ip0 and ip1 are always adjacent. The targetLength skipping and
629387 * uncompressibility acceleration is applied to every other position,
629388 * matching the behavior of #1562. step therefore represents the gap
629389 * between pairs of positions, from ip0 to ip2 or ip1 to ip3. */
629390 size_t step;
629391 const BYTE* nextStep;
629392 const size_t kStepIncr = (1 << (kSearchStrength - 1));
629393
629394 DEBUGLOG(5, "ZSTD_compressBlock_fast_generic");
629395 ip0 += (ip0 == prefixStart);
629396 { U32 const curr = (U32)(ip0 - base);
629397 U32 const windowLow = ZSTD_getLowestPrefixIndex(ms, curr, cParams->windowLog);
629398 U32 const maxRep = curr - windowLow;
629399 if (rep_offset2 > maxRep) offsetSaved2 = rep_offset2, rep_offset2 = 0;
629400 if (rep_offset1 > maxRep) offsetSaved1 = rep_offset1, rep_offset1 = 0;
629401 }
629402
629403 /* start each op */
629404_start: /* Requires: ip0 */
629405
629406 step = stepSize;
629407 nextStep = ip0 + kStepIncr;
629408
629409 /* calculate positions, ip0 - anchor == 0, so we skip step calc */
629410 ip1 = ip0 + 1;
629411 ip2 = ip0 + step;
629412 ip3 = ip2 + 1;
629413
629414 if (ip3 >= ilimit) {
629415 goto _cleanup;
629416 }
629417
629418 hash0 = ZSTD_hashPtr(ip0, hlog, mls);
629419 hash1 = ZSTD_hashPtr(ip1, hlog, mls);
629420
629421 idx = hashTable[hash0];
629422
629423 do {
629424 /* load repcode match for ip[2]*/
629425 const U32 rval = MEM_read32(ip2 - rep_offset1);
629426
629427 /* write back hash table entry */
629428 current0 = (U32)(ip0 - base);
629429 hashTable[hash0] = current0;
629430
629431 /* check repcode at ip[2] */
629432 if ((MEM_read32(ip2) == rval) & (rep_offset1 > 0)) {
629433 ip0 = ip2;
629434 match0 = ip0 - rep_offset1;
629435 mLength = ip0[-1] == match0[-1];
629436 ip0 -= mLength;
629437 match0 -= mLength;
629438 offcode = REPCODE1_TO_OFFBASE;
629439 mLength += 4;
629440
629441 /* First write next hash table entry; we've already calculated it.
629442 * This write is known to be safe because the ip1 is before the
629443 * repcode (ip2). */
629444 hashTable[hash1] = (U32)(ip1 - base);
629445
629446 goto _match;
629447 }
629448
629449 /* load match for ip[0] */
629450 if (idx >= prefixStartIndex) {
629451 mval = MEM_read32(base + idx);
629452 } else {
629453 mval = MEM_read32(ip0) ^ 1; /* guaranteed to not match. */
629454 }
629455
629456 /* check match at ip[0] */
629457 if (MEM_read32(ip0) == mval) {
629458 /* found a match! */
629459
629460 /* First write next hash table entry; we've already calculated it.
629461 * This write is known to be safe because the ip1 == ip0 + 1, so
629462 * we know we will resume searching after ip1 */
629463 hashTable[hash1] = (U32)(ip1 - base);
629464
629465 goto _offset;
629466 }
629467
629468 /* lookup ip[1] */
629469 idx = hashTable[hash1];
629470
629471 /* hash ip[2] */
629472 hash0 = hash1;
629473 hash1 = ZSTD_hashPtr(ip2, hlog, mls);
629474
629475 /* advance to next positions */
629476 ip0 = ip1;
629477 ip1 = ip2;
629478 ip2 = ip3;
629479
629480 /* write back hash table entry */
629481 current0 = (U32)(ip0 - base);
629482 hashTable[hash0] = current0;
629483
629484 /* load match for ip[0] */
629485 if (idx >= prefixStartIndex) {
629486 mval = MEM_read32(base + idx);
629487 } else {
629488 mval = MEM_read32(ip0) ^ 1; /* guaranteed to not match. */
629489 }
629490
629491 /* check match at ip[0] */
629492 if (MEM_read32(ip0) == mval) {
629493 /* found a match! */
629494
629495 /* first write next hash table entry; we've already calculated it */
629496 if (step <= 4) {
629497 /* We need to avoid writing an index into the hash table >= the
629498 * position at which we will pick up our searching after we've
629499 * taken this match.
629500 *
629501 * The minimum possible match has length 4, so the earliest ip0
629502 * can be after we take this match will be the current ip0 + 4.
629503 * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely
629504 * write this position.
629505 */
629506 hashTable[hash1] = (U32)(ip1 - base);
629507 }
629508
629509 goto _offset;
629510 }
629511
629512 /* lookup ip[1] */
629513 idx = hashTable[hash1];
629514
629515 /* hash ip[2] */
629516 hash0 = hash1;
629517 hash1 = ZSTD_hashPtr(ip2, hlog, mls);
629518
629519 /* advance to next positions */
629520 ip0 = ip1;
629521 ip1 = ip2;
629522 ip2 = ip0 + step;
629523 ip3 = ip1 + step;
629524
629525 /* calculate step */
629526 if (ip2 >= nextStep) {
629527 step++;
629528 PREFETCH_L1(ip1 + 64);
629529 PREFETCH_L1(ip1 + 128);
629530 nextStep += kStepIncr;
629531 }
629532 } while (ip3 < ilimit);
629533
629534_cleanup:
629535 /* Note that there are probably still a couple positions we could search.
629536 * However, it seems to be a meaningful performance hit to try to search
629537 * them. So let's not. */
629538
629539 /* When the repcodes are outside of the prefix, we set them to zero before the loop.
629540 * When the offsets are still zero, we need to restore them after the block to have a correct
629541 * repcode history. If only one offset was invalid, it is easy. The tricky case is when both
629542 * offsets were invalid. We need to figure out which offset to refill with.
629543 * - If both offsets are zero they are in the same order.
629544 * - If both offsets are non-zero, we won't restore the offsets from `offsetSaved[12]`.
629545 * - If only one is zero, we need to decide which offset to restore.
629546 * - If rep_offset1 is non-zero, then rep_offset2 must be offsetSaved1.
629547 * - It is impossible for rep_offset2 to be non-zero.
629548 *
629549 * So if rep_offset1 started invalid (offsetSaved1 != 0) and became valid (rep_offset1 != 0), then
629550 * set rep[0] = rep_offset1 and rep[1] = offsetSaved1.
629551 */
629552 offsetSaved2 = ((offsetSaved1 != 0) && (rep_offset1 != 0)) ? offsetSaved1 : offsetSaved2;
629553
629554 /* save reps for next block */
629555 rep[0] = rep_offset1 ? rep_offset1 : offsetSaved1;
629556 rep[1] = rep_offset2 ? rep_offset2 : offsetSaved2;
629557
629558 /* Return the last literals size */
629559 return (size_t)(iend - anchor);
629560
629561_offset: /* Requires: ip0, idx */
629562
629563 /* Compute the offset code. */
629564 match0 = base + idx;
629565 rep_offset2 = rep_offset1;
629566 rep_offset1 = (U32)(ip0-match0);
629567 offcode = OFFSET_TO_OFFBASE(rep_offset1);
629568 mLength = 4;
629569
629570 /* Count the backwards match length. */
629571 while (((ip0>anchor) & (match0>prefixStart)) && (ip0[-1] == match0[-1])) {
629572 ip0--;
629573 match0--;
629574 mLength++;
629575 }
629576
629577_match: /* Requires: ip0, match0, offcode */
629578
629579 /* Count the forward length. */
629580 mLength += ZSTD_count(ip0 + mLength, match0 + mLength, iend);
629581
629582 ZSTD_storeSeq(seqStore, (size_t)(ip0 - anchor), anchor, iend, offcode, mLength);
629583
629584 ip0 += mLength;
629585 anchor = ip0;
629586
629587 /* Fill table and check for immediate repcode. */
629588 if (ip0 <= ilimit) {
629589 /* Fill Table */
629590 assert(base+current0+2 > istart); /* check base overflow */
629591 hashTable[ZSTD_hashPtr(base+current0+2, hlog, mls)] = current0+2; /* here because current+2 could be > iend-8 */
629592 hashTable[ZSTD_hashPtr(ip0-2, hlog, mls)] = (U32)(ip0-2-base);
629593
629594 if (rep_offset2 > 0) { /* rep_offset2==0 means rep_offset2 is invalidated */
629595 while ( (ip0 <= ilimit) && (MEM_read32(ip0) == MEM_read32(ip0 - rep_offset2)) ) {
629596 /* store sequence */
629597 size_t const rLength = ZSTD_count(ip0+4, ip0+4-rep_offset2, iend) + 4;
629598 { U32 const tmpOff = rep_offset2; rep_offset2 = rep_offset1; rep_offset1 = tmpOff; } /* swap rep_offset2 <=> rep_offset1 */
629599 hashTable[ZSTD_hashPtr(ip0, hlog, mls)] = (U32)(ip0-base);
629600 ip0 += rLength;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressBlock_fast_dictMatchState_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_fast_dictMatchState_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls,
U32 const hasStep )
629668{
629669 const ZSTD_compressionParameters* const cParams = &ms->cParams;
629670 U32* const hashTable = ms->hashTable;
629671 U32 const hlog = cParams->hashLog;
629672 /* support stepSize of 0 */
629673 U32 const stepSize = cParams->targetLength + !(cParams->targetLength);
629674 const BYTE* const base = ms->window.base;
629675 const BYTE* const istart = (const BYTE*)src;
629676 const BYTE* ip0 = istart;
629677 const BYTE* ip1 = ip0 + stepSize; /* we assert below that stepSize >= 1 */
629678 const BYTE* anchor = istart;
629679 const U32 prefixStartIndex = ms->window.dictLimit;
629680 const BYTE* const prefixStart = base + prefixStartIndex;
629681 const BYTE* const iend = istart + srcSize;
629682 const BYTE* const ilimit = iend - HASH_READ_SIZE;
629683 U32 offset_1=rep[0], offset_2=rep[1];
629684
629685 const ZSTD_matchState_t* const dms = ms->dictMatchState;
629686 const ZSTD_compressionParameters* const dictCParams = &dms->cParams ;
629687 const U32* const dictHashTable = dms->hashTable;
629688 const U32 dictStartIndex = dms->window.dictLimit;
629689 const BYTE* const dictBase = dms->window.base;
629690 const BYTE* const dictStart = dictBase + dictStartIndex;
629691 const BYTE* const dictEnd = dms->window.nextSrc;
629692 const U32 dictIndexDelta = prefixStartIndex - (U32)(dictEnd - dictBase);
629693 const U32 dictAndPrefixLength = (U32)(istart - prefixStart + dictEnd - dictStart);
629694 const U32 dictHBits = dictCParams->hashLog + ZSTD_SHORT_CACHE_TAG_BITS;
629695
629696 /* if a dictionary is still attached, it necessarily means that
629697 * it is within window size. So we just check it. */
629698 const U32 maxDistance = 1U << cParams->windowLog;
629699 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
629700 assert(endIndex - prefixStartIndex <= maxDistance);
629701 (void)maxDistance; (void)endIndex; /* these variables are not used when assert() is disabled */
629702
629703 (void)hasStep; /* not currently specialized on whether it's accelerated */
629704
629705 /* ensure there will be no underflow
629706 * when translating a dict index into a local index */
629707 assert(prefixStartIndex >= (U32)(dictEnd - dictBase));
629708
629709 if (ms->prefetchCDictTables) {
629710 size_t const hashTableBytes = (((size_t)1) << dictCParams->hashLog) * sizeof(U32);
629711 PREFETCH_AREA(dictHashTable, hashTableBytes);
629712 }
629713
629714 /* init */
629715 DEBUGLOG(5, "ZSTD_compressBlock_fast_dictMatchState_generic");
629716 ip0 += (dictAndPrefixLength == 0);
629717 /* dictMatchState repCode checks don't currently handle repCode == 0
629718 * disabling. */
629719 assert(offset_1 <= dictAndPrefixLength);
629720 assert(offset_2 <= dictAndPrefixLength);
629721
629722 /* Outer search loop */
629723 assert(stepSize >= 1);
629724 while (ip1 <= ilimit) { /* repcode check at (ip0 + 1) is safe because ip0 < ip1 */
629725 size_t mLength;
629726 size_t hash0 = ZSTD_hashPtr(ip0, hlog, mls);
629727
629728 size_t const dictHashAndTag0 = ZSTD_hashPtr(ip0, dictHBits, mls);
629729 U32 dictMatchIndexAndTag = dictHashTable[dictHashAndTag0 >> ZSTD_SHORT_CACHE_TAG_BITS];
629730 int dictTagsMatch = ZSTD_comparePackedTags(dictMatchIndexAndTag, dictHashAndTag0);
629731
629732 U32 matchIndex = hashTable[hash0];
629733 U32 curr = (U32)(ip0 - base);
629734 size_t step = stepSize;
629735 const size_t kStepIncr = 1 << kSearchStrength;
629736 const BYTE* nextStep = ip0 + kStepIncr;
629737
629738 /* Inner search loop */
629739 while (1) {
629740 const BYTE* match = base + matchIndex;
629741 const U32 repIndex = curr + 1 - offset_1;
629742 const BYTE* repMatch = (repIndex < prefixStartIndex) ?
629743 dictBase + (repIndex - dictIndexDelta) :
629744 base + repIndex;
629745 const size_t hash1 = ZSTD_hashPtr(ip1, hlog, mls);
629746 size_t const dictHashAndTag1 = ZSTD_hashPtr(ip1, dictHBits, mls);
629747 hashTable[hash0] = curr; /* update hash table */
629748
629749 if (((U32) ((prefixStartIndex - 1) - repIndex) >=
629750 3) /* intentional underflow : ensure repIndex isn't overlapping dict + prefix */
629751 && (MEM_read32(repMatch) == MEM_read32(ip0 + 1))) {
629752 const BYTE* const repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
629753 mLength = ZSTD_count_2segments(ip0 + 1 + 4, repMatch + 4, iend, repMatchEnd, prefixStart) + 4;
629754 ip0++;
629755 ZSTD_storeSeq(seqStore, (size_t) (ip0 - anchor), anchor, iend, REPCODE1_TO_OFFBASE, mLength);
629756 break;
629757 }
629758
629759 if (dictTagsMatch) {
629760 /* Found a possible dict match */
629761 const U32 dictMatchIndex = dictMatchIndexAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;
629762 const BYTE* dictMatch = dictBase + dictMatchIndex;
629763 if (dictMatchIndex > dictStartIndex &&
629764 MEM_read32(dictMatch) == MEM_read32(ip0)) {
629765 /* To replicate extDict parse behavior, we only use dict matches when the normal matchIndex is invalid */
629766 if (matchIndex <= prefixStartIndex) {
629767 U32 const offset = (U32) (curr - dictMatchIndex - dictIndexDelta);
629768 mLength = ZSTD_count_2segments(ip0 + 4, dictMatch + 4, iend, dictEnd, prefixStart) + 4;
629769 while (((ip0 > anchor) & (dictMatch > dictStart))
629770 && (ip0[-1] == dictMatch[-1])) {
629771 ip0--;
629772 dictMatch--;
629773 mLength++;
629774 } /* catch up */
629775 offset_2 = offset_1;
629776 offset_1 = offset;
629777 ZSTD_storeSeq(seqStore, (size_t) (ip0 - anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
629778 break;
629779 }
629780 }
629781 }
629782
629783 if (matchIndex > prefixStartIndex && MEM_read32(match) == MEM_read32(ip0)) {
629784 /* found a regular match */
629785 U32 const offset = (U32) (ip0 - match);
629786 mLength = ZSTD_count(ip0 + 4, match + 4, iend) + 4;
629787 while (((ip0 > anchor) & (match > prefixStart))
629788 && (ip0[-1] == match[-1])) {
629789 ip0--;
629790 match--;
629791 mLength++;
629792 } /* catch up */
629793 offset_2 = offset_1;
629794 offset_1 = offset;
629795 ZSTD_storeSeq(seqStore, (size_t) (ip0 - anchor), anchor, iend, OFFSET_TO_OFFBASE(offset), mLength);
629796 break;
629797 }
629798
629799 /* Prepare for next iteration */
629800 dictMatchIndexAndTag = dictHashTable[dictHashAndTag1 >> ZSTD_SHORT_CACHE_TAG_BITS];
629801 dictTagsMatch = ZSTD_comparePackedTags(dictMatchIndexAndTag, dictHashAndTag1);
629802 matchIndex = hashTable[hash1];
629803
629804 if (ip1 >= nextStep) {
629805 step++;
629806 nextStep += kStepIncr;
629807 }
629808 ip0 = ip1;
629809 ip1 = ip1 + step;
629810 if (ip1 > ilimit) goto _cleanup;
629811
629812 curr = (U32)(ip0 - base);
629813 hash0 = hash1;
629814 } /* end inner search loop */
629815
629816 /* match found */
629817 assert(mLength);
629818 ip0 += mLength;
629819 anchor = ip0;
629820
629821 if (ip0 <= ilimit) {
629822 /* Fill Table */
629823 assert(base+curr+2 > istart); /* check base overflow */
629824 hashTable[ZSTD_hashPtr(base+curr+2, hlog, mls)] = curr+2; /* here because curr+2 could be > iend-8 */
629825 hashTable[ZSTD_hashPtr(ip0-2, hlog, mls)] = (U32)(ip0-2-base);
629826
629827 /* check immediate repcode */
629828 while (ip0 <= ilimit) {
629829 U32 const current2 = (U32)(ip0-base);
629830 U32 const repIndex2 = current2 - offset_2;
629831 const BYTE* repMatch2 = repIndex2 < prefixStartIndex ?
629832 dictBase - dictIndexDelta + repIndex2 :
629833 base + repIndex2;
629834 if ( ((U32)((prefixStartIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */)
629835 && (MEM_read32(repMatch2) == MEM_read32(ip0))) {
629836 const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
629837 size_t const repLength2 = ZSTD_count_2segments(ip0+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
629838 U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
629839 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, repLength2);
629840 hashTable[ZSTD_hashPtr(ip0, hlog, mls)] = current2;
629841 ip0 += repLength2;
629842 anchor = ip0;
629843 continue;
629844 }
629845 break;
629846 }
629847 }
629848
629849 /* Prepare for next iteration */
629850 assert(ip0 == anchor);
629851 ip1 = ip0 + stepSize;
629852 }
629853
629854_cleanup:

◆ ZSTD_compressBlock_fast_extDict_generic()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_fast_extDict_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
void const * src,
size_t srcSize,
U32 const mls,
U32 const hasStep )
static
629895{
629896 const ZSTD_compressionParameters* const cParams = &ms->cParams;
629897 U32* const hashTable = ms->hashTable;
629898 U32 const hlog = cParams->hashLog;
629899 /* support stepSize of 0 */
629900 size_t const stepSize = cParams->targetLength + !(cParams->targetLength) + 1;
629901 const BYTE* const base = ms->window.base;
629902 const BYTE* const dictBase = ms->window.dictBase;
629903 const BYTE* const istart = (const BYTE*)src;
629904 const BYTE* anchor = istart;
629905 const U32 endIndex = (U32)((size_t)(istart - base) + srcSize);
629906 const U32 lowLimit = ZSTD_getLowestMatchIndex(ms, endIndex, cParams->windowLog);
629907 const U32 dictStartIndex = lowLimit;
629908 const BYTE* const dictStart = dictBase + dictStartIndex;
629909 const U32 dictLimit = ms->window.dictLimit;
629910 const U32 prefixStartIndex = dictLimit < lowLimit ? lowLimit : dictLimit;
629911 const BYTE* const prefixStart = base + prefixStartIndex;
629912 const BYTE* const dictEnd = dictBase + prefixStartIndex;
629913 const BYTE* const iend = istart + srcSize;
629914 const BYTE* const ilimit = iend - 8;
629915 U32 offset_1=rep[0], offset_2=rep[1];
629916 U32 offsetSaved1 = 0, offsetSaved2 = 0;
629917
629918 const BYTE* ip0 = istart;
629919 const BYTE* ip1;
629920 const BYTE* ip2;
629921 const BYTE* ip3;
629922 U32 current0;
629923
629924
629925 size_t hash0; /* hash for ip0 */
629926 size_t hash1; /* hash for ip1 */
629927 U32 idx; /* match idx for ip0 */
629928 const BYTE* idxBase; /* base pointer for idx */
629929
629930 U32 offcode;
629931 const BYTE* match0;
629932 size_t mLength;
629933 const BYTE* matchEnd = 0; /* initialize to avoid warning, assert != 0 later */
629934
629935 size_t step;
629936 const BYTE* nextStep;
629937 const size_t kStepIncr = (1 << (kSearchStrength - 1));
629938
629939 (void)hasStep; /* not currently specialized on whether it's accelerated */
629940
629941 DEBUGLOG(5, "ZSTD_compressBlock_fast_extDict_generic (offset_1=%u)", offset_1);
629942
629943 /* switch to "regular" variant if extDict is invalidated due to maxDistance */
629944 if (prefixStartIndex == dictStartIndex)
629945 return ZSTD_compressBlock_fast(ms, seqStore, rep, src, srcSize);
629946
629947 { U32 const curr = (U32)(ip0 - base);
629948 U32 const maxRep = curr - dictStartIndex;
629949 if (offset_2 >= maxRep) offsetSaved2 = offset_2, offset_2 = 0;
629950 if (offset_1 >= maxRep) offsetSaved1 = offset_1, offset_1 = 0;
629951 }
629952
629953 /* start each op */
629954_start: /* Requires: ip0 */
629955
629956 step = stepSize;
629957 nextStep = ip0 + kStepIncr;
629958
629959 /* calculate positions, ip0 - anchor == 0, so we skip step calc */
629960 ip1 = ip0 + 1;
629961 ip2 = ip0 + step;
629962 ip3 = ip2 + 1;
629963
629964 if (ip3 >= ilimit) {
629965 goto _cleanup;
629966 }
629967
629968 hash0 = ZSTD_hashPtr(ip0, hlog, mls);
629969 hash1 = ZSTD_hashPtr(ip1, hlog, mls);
629970
629971 idx = hashTable[hash0];
629972 idxBase = idx < prefixStartIndex ? dictBase : base;
629973
629974 do {
629975 { /* load repcode match for ip[2] */
629976 U32 const current2 = (U32)(ip2 - base);
629977 U32 const repIndex = current2 - offset_1;
629978 const BYTE* const repBase = repIndex < prefixStartIndex ? dictBase : base;
629979 U32 rval;
629980 if ( ((U32)(prefixStartIndex - repIndex) >= 4) /* intentional underflow */
629981 & (offset_1 > 0) ) {
629982 rval = MEM_read32(repBase + repIndex);
629983 } else {
629984 rval = MEM_read32(ip2) ^ 1; /* guaranteed to not match. */
629985 }
629986
629987 /* write back hash table entry */
629988 current0 = (U32)(ip0 - base);
629989 hashTable[hash0] = current0;
629990
629991 /* check repcode at ip[2] */
629992 if (MEM_read32(ip2) == rval) {
629993 ip0 = ip2;
629994 match0 = repBase + repIndex;
629995 matchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
629996 assert((match0 != prefixStart) & (match0 != dictStart));
629997 mLength = ip0[-1] == match0[-1];
629998 ip0 -= mLength;
629999 match0 -= mLength;
630000 offcode = REPCODE1_TO_OFFBASE;
630001 mLength += 4;
630002 goto _match;
630003 } }
630004
630005 { /* load match for ip[0] */
630006 U32 const mval = idx >= dictStartIndex ?
630007 MEM_read32(idxBase + idx) :
630008 MEM_read32(ip0) ^ 1; /* guaranteed not to match */
630009
630010 /* check match at ip[0] */
630011 if (MEM_read32(ip0) == mval) {
630012 /* found a match! */
630013 goto _offset;
630014 } }
630015
630016 /* lookup ip[1] */
630017 idx = hashTable[hash1];
630018 idxBase = idx < prefixStartIndex ? dictBase : base;
630019
630020 /* hash ip[2] */
630021 hash0 = hash1;
630022 hash1 = ZSTD_hashPtr(ip2, hlog, mls);
630023
630024 /* advance to next positions */
630025 ip0 = ip1;
630026 ip1 = ip2;
630027 ip2 = ip3;
630028
630029 /* write back hash table entry */
630030 current0 = (U32)(ip0 - base);
630031 hashTable[hash0] = current0;
630032
630033 { /* load match for ip[0] */
630034 U32 const mval = idx >= dictStartIndex ?
630035 MEM_read32(idxBase + idx) :
630036 MEM_read32(ip0) ^ 1; /* guaranteed not to match */
630037
630038 /* check match at ip[0] */
630039 if (MEM_read32(ip0) == mval) {
630040 /* found a match! */
630041 goto _offset;
630042 } }
630043
630044 /* lookup ip[1] */
630045 idx = hashTable[hash1];
630046 idxBase = idx < prefixStartIndex ? dictBase : base;
630047
630048 /* hash ip[2] */
630049 hash0 = hash1;
630050 hash1 = ZSTD_hashPtr(ip2, hlog, mls);
630051
630052 /* advance to next positions */
630053 ip0 = ip1;
630054 ip1 = ip2;
630055 ip2 = ip0 + step;
630056 ip3 = ip1 + step;
630057
630058 /* calculate step */
630059 if (ip2 >= nextStep) {
630060 step++;
630061 PREFETCH_L1(ip1 + 64);
630062 PREFETCH_L1(ip1 + 128);
630063 nextStep += kStepIncr;
630064 }
630065 } while (ip3 < ilimit);
630066
630067_cleanup:
630068 /* Note that there are probably still a couple positions we could search.
630069 * However, it seems to be a meaningful performance hit to try to search
630070 * them. So let's not. */
630071
630072 /* If offset_1 started invalid (offsetSaved1 != 0) and became valid (offset_1 != 0),
630073 * rotate saved offsets. See comment in ZSTD_compressBlock_fast_noDict for more context. */
630074 offsetSaved2 = ((offsetSaved1 != 0) && (offset_1 != 0)) ? offsetSaved1 : offsetSaved2;
630075
630076 /* save reps for next block */
630077 rep[0] = offset_1 ? offset_1 : offsetSaved1;
630078 rep[1] = offset_2 ? offset_2 : offsetSaved2;
630079
630080 /* Return the last literals size */
630081 return (size_t)(iend - anchor);
630082
630083_offset: /* Requires: ip0, idx, idxBase */
630084
630085 /* Compute the offset code. */
630086 { U32 const offset = current0 - idx;
630087 const BYTE* const lowMatchPtr = idx < prefixStartIndex ? dictStart : prefixStart;
630088 matchEnd = idx < prefixStartIndex ? dictEnd : iend;
630089 match0 = idxBase + idx;
630090 offset_2 = offset_1;
630091 offset_1 = offset;
630092 offcode = OFFSET_TO_OFFBASE(offset);
630093 mLength = 4;
630094
630095 /* Count the backwards match length. */
630096 while (((ip0>anchor) & (match0>lowMatchPtr)) && (ip0[-1] == match0[-1])) {
630097 ip0--;
630098 match0--;
630099 mLength++;
630100 } }
630101
630102_match: /* Requires: ip0, match0, offcode, matchEnd */
630103
630104 /* Count the forward length. */
630105 assert(matchEnd != 0);
630106 mLength += ZSTD_count_2segments(ip0 + mLength, match0 + mLength, iend, matchEnd, prefixStart);
630107
630108 ZSTD_storeSeq(seqStore, (size_t)(ip0 - anchor), anchor, iend, offcode, mLength);
630109
630110 ip0 += mLength;
630111 anchor = ip0;
630112
630113 /* write next hash table entry */
630114 if (ip1 < ip0) {
630115 hashTable[hash1] = (U32)(ip1 - base);
630116 }
630117
630118 /* Fill table and check for immediate repcode. */
630119 if (ip0 <= ilimit) {
630120 /* Fill Table */
630121 assert(base+current0+2 > istart); /* check base overflow */
630122 hashTable[ZSTD_hashPtr(base+current0+2, hlog, mls)] = current0+2; /* here because current+2 could be > iend-8 */
630123 hashTable[ZSTD_hashPtr(ip0-2, hlog, mls)] = (U32)(ip0-2-base);
630124
630125 while (ip0 <= ilimit) {
630126 U32 const repIndex2 = (U32)(ip0-base) - offset_2;
630127 const BYTE* const repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2;
630128 if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) & (offset_2 > 0)) /* intentional underflow */
630129 && (MEM_read32(repMatch2) == MEM_read32(ip0)) ) {
630130 const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
630131 size_t const repLength2 = ZSTD_count_2segments(ip0+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
630132 { U32 const tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; } /* swap offset_2 <=> offset_1 */
630133 ZSTD_storeSeq(seqStore, 0 /*litlen*/, anchor, iend, REPCODE1_TO_OFFBASE, repLength2);
630134 hashTable[ZSTD_hashPtr(ip0, hlog, mls)] = (U32)(ip0-base);
630135 ip0 += repLength2;
630136 anchor = ip0;

◆ ZSTD_updateDUBT()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_updateDUBT ( ZSTD_matchState_t * ms,
const BYTE * ip,
const BYTE * iend,
U32 mls )
static
630213{
630214 const ZSTD_compressionParameters* const cParams = &ms->cParams;
630215 U32* const hashTable = ms->hashTable;
630216 U32 const hashLog = cParams->hashLog;
630217
630218 U32* const bt = ms->chainTable;
630219 U32 const btLog = cParams->chainLog - 1;
630220 U32 const btMask = (1 << btLog) - 1;
630221
630222 const BYTE* const base = ms->window.base;
630223 U32 const target = (U32)(ip - base);
630224 U32 idx = ms->nextToUpdate;
630225
630226 if (idx != target)
630227 DEBUGLOG(7, "ZSTD_updateDUBT, from %u to %u (dictLimit:%u)",
630228 idx, target, ms->window.dictLimit);
630229 assert(ip + 8 <= iend); /* condition for ZSTD_hashPtr */
630230 (void)iend;
630231
630232 assert(idx >= ms->window.dictLimit); /* condition for valid base+idx */
630233 for ( ; idx < target ; idx++) {
630234 size_t const h = ZSTD_hashPtr(base + idx, hashLog, mls); /* assumption : ip + 8 <= iend */
630235 U32 const matchIndex = hashTable[h];
630236
630237 U32* const nextCandidatePtr = bt + 2*(idx&btMask);
630238 U32* const sortMarkPtr = nextCandidatePtr + 1;
630239

◆ ZSTD_insertDUBT1()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_insertDUBT1 ( const ZSTD_matchState_t * ms,
U32 curr,
const BYTE * inputEnd,
U32 nbCompares,
U32 btLow,
const ZSTD_dictMode_e dictMode )
static

ZSTD_insertDUBT1() : sort one already inserted but unsorted position assumption : curr >= btlow == (curr - btmask) doesn't fail

630259{
630260 const ZSTD_compressionParameters* const cParams = &ms->cParams;
630261 U32* const bt = ms->chainTable;
630262 U32 const btLog = cParams->chainLog - 1;
630263 U32 const btMask = (1 << btLog) - 1;
630264 size_t commonLengthSmaller=0, commonLengthLarger=0;
630265 const BYTE* const base = ms->window.base;
630266 const BYTE* const dictBase = ms->window.dictBase;
630267 const U32 dictLimit = ms->window.dictLimit;
630268 const BYTE* const ip = (curr>=dictLimit) ? base + curr : dictBase + curr;
630269 const BYTE* const iend = (curr>=dictLimit) ? inputEnd : dictBase + dictLimit;
630270 const BYTE* const dictEnd = dictBase + dictLimit;
630271 const BYTE* const prefixStart = base + dictLimit;
630272 const BYTE* match;
630273 U32* smallerPtr = bt + 2*(curr&btMask);
630274 U32* largerPtr = smallerPtr + 1;
630275 U32 matchIndex = *smallerPtr; /* this candidate is unsorted : next sorted candidate is reached through *smallerPtr, while *largerPtr contains previous unsorted candidate (which is already saved and can be overwritten) */
630276 U32 dummy32; /* to be nullified at the end */
630277 U32 const windowValid = ms->window.lowLimit;
630278 U32 const maxDistance = 1U << cParams->windowLog;
630279 U32 const windowLow = (curr - windowValid > maxDistance) ? curr - maxDistance : windowValid;
630280
630281
630282 DEBUGLOG(8, "ZSTD_insertDUBT1(%u) (dictLimit=%u, lowLimit=%u)",
630283 curr, dictLimit, windowLow);
630284 assert(curr >= btLow);
630285 assert(ip < iend); /* condition for ZSTD_count */
630286
630287 for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
630288 U32* const nextPtr = bt + 2*(matchIndex & btMask);
630289 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
630290 assert(matchIndex < curr);
630291 /* note : all candidates are now supposed sorted,
630292 * but it's still possible to have nextPtr[1] == ZSTD_DUBT_UNSORTED_MARK
630293 * when a real index has the same value as ZSTD_DUBT_UNSORTED_MARK */
630294
630295 if ( (dictMode != ZSTD_extDict)
630296 || (matchIndex+matchLength >= dictLimit) /* both in current segment*/
630297 || (curr < dictLimit) /* both in extDict */) {
630298 const BYTE* const mBase = ( (dictMode != ZSTD_extDict)
630299 || (matchIndex+matchLength >= dictLimit)) ?
630300 base : dictBase;
630301 assert( (matchIndex+matchLength >= dictLimit) /* might be wrong if extDict is incorrectly set to 0 */
630302 || (curr < dictLimit) );
630303 match = mBase + matchIndex;
630304 matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
630305 } else {
630306 match = dictBase + matchIndex;
630307 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
630308 if (matchIndex+matchLength >= dictLimit)
630309 match = base + matchIndex; /* preparation for next read of match[matchLength] */
630310 }
630311
630312 DEBUGLOG(8, "ZSTD_insertDUBT1: comparing %u with %u : found %u common bytes ",
630313 curr, matchIndex, (U32)matchLength);
630314
630315 if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
630316 break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
630317 }
630318
630319 if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
630320 /* match is smaller than current */
630321 *smallerPtr = matchIndex; /* update smaller idx */
630322 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
630323 if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
630324 DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is smaller : next => %u",
630325 matchIndex, btLow, nextPtr[1]);
630326 smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
630327 matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
630328 } else {
630329 /* match is larger than current */
630330 *largerPtr = matchIndex;
630331 commonLengthLarger = matchLength;
630332 if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
630333 DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is larger => %u",
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_DUBT_findBetterDictMatch()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_DUBT_findBetterDictMatch ( const ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iend,
size_t * offsetPtr,
size_t bestLength,
U32 nbCompares,
U32 const mls,
const ZSTD_dictMode_e dictMode )
static
630353{
630354 const ZSTD_matchState_t * const dms = ms->dictMatchState;
630355 const ZSTD_compressionParameters* const dmsCParams = &dms->cParams;
630356 const U32 * const dictHashTable = dms->hashTable;
630357 U32 const hashLog = dmsCParams->hashLog;
630358 size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
630359 U32 dictMatchIndex = dictHashTable[h];
630360
630361 const BYTE* const base = ms->window.base;
630362 const BYTE* const prefixStart = base + ms->window.dictLimit;
630363 U32 const curr = (U32)(ip-base);
630364 const BYTE* const dictBase = dms->window.base;
630365 const BYTE* const dictEnd = dms->window.nextSrc;
630366 U32 const dictHighLimit = (U32)(dms->window.nextSrc - dms->window.base);
630367 U32 const dictLowLimit = dms->window.lowLimit;
630368 U32 const dictIndexDelta = ms->window.lowLimit - dictHighLimit;
630369
630370 U32* const dictBt = dms->chainTable;
630371 U32 const btLog = dmsCParams->chainLog - 1;
630372 U32 const btMask = (1 << btLog) - 1;
630373 U32 const btLow = (btMask >= dictHighLimit - dictLowLimit) ? dictLowLimit : dictHighLimit - btMask;
630374
630375 size_t commonLengthSmaller=0, commonLengthLarger=0;
630376
630377 (void)dictMode;
630378 assert(dictMode == ZSTD_dictMatchState);
630379
630380 for (; nbCompares && (dictMatchIndex > dictLowLimit); --nbCompares) {
630381 U32* const nextPtr = dictBt + 2*(dictMatchIndex & btMask);
630382 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
630383 const BYTE* match = dictBase + dictMatchIndex;
630384 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
630385 if (dictMatchIndex+matchLength >= dictHighLimit)
630386 match = base + dictMatchIndex + dictIndexDelta; /* to prepare for next usage of match[matchLength] */
630387
630388 if (matchLength > bestLength) {
630389 U32 matchIndex = dictMatchIndex + dictIndexDelta;
630390 if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr-matchIndex+1) - ZSTD_highbit32((U32)offsetPtr[0]+1)) ) {
630391 DEBUGLOG(9, "ZSTD_DUBT_findBetterDictMatch(%u) : found better match length %u -> %u and offsetCode %u -> %u (dictMatchIndex %u, matchIndex %u)",
630392 curr, (U32)bestLength, (U32)matchLength, (U32)*offsetPtr, OFFSET_TO_OFFBASE(curr - matchIndex), dictMatchIndex, matchIndex);
630393 bestLength = matchLength, *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
630394 }
630395 if (ip+matchLength == iend) { /* reached end of input : ip[matchLength] is not valid, no way to know if it's larger or smaller than match */
630396 break; /* drop, to guarantee consistency (miss a little bit of compression) */
630397 }
630398 }
630399
630400 if (match[matchLength] < ip[matchLength]) {
630401 if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
630402 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
630403 dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
630404 } else {
630405 /* match is larger than current */
630406 if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
630407 commonLengthLarger = matchLength;
630408 dictMatchIndex = nextPtr[0];
630409 }
630410 }
630411
630412 if (bestLength >= MINMATCH) {

◆ ZSTD_DUBT_findBestMatch()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_DUBT_findBestMatch ( ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iend,
size_t * offBasePtr,
U32 const mls,
const ZSTD_dictMode_e dictMode )
static
630429{
630430 const ZSTD_compressionParameters* const cParams = &ms->cParams;
630431 U32* const hashTable = ms->hashTable;
630432 U32 const hashLog = cParams->hashLog;
630433 size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
630434 U32 matchIndex = hashTable[h];
630435
630436 const BYTE* const base = ms->window.base;
630437 U32 const curr = (U32)(ip-base);
630438 U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
630439
630440 U32* const bt = ms->chainTable;
630441 U32 const btLog = cParams->chainLog - 1;
630442 U32 const btMask = (1 << btLog) - 1;
630443 U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;
630444 U32 const unsortLimit = MAX(btLow, windowLow);
630445
630446 U32* nextCandidate = bt + 2*(matchIndex&btMask);
630447 U32* unsortedMark = bt + 2*(matchIndex&btMask) + 1;
630448 U32 nbCompares = 1U << cParams->searchLog;
630449 U32 nbCandidates = nbCompares;
630450 U32 previousCandidate = 0;
630451
630452 DEBUGLOG(7, "ZSTD_DUBT_findBestMatch (%u) ", curr);
630453 assert(ip <= iend-8); /* required for h calculation */
630454 assert(dictMode != ZSTD_dedicatedDictSearch);
630455
630456 /* reach end of unsorted candidates list */
630457 while ( (matchIndex > unsortLimit)
630458 && (*unsortedMark == ZSTD_DUBT_UNSORTED_MARK)
630459 && (nbCandidates > 1) ) {
630460 DEBUGLOG(8, "ZSTD_DUBT_findBestMatch: candidate %u is unsorted",
630461 matchIndex);
630462 *unsortedMark = previousCandidate; /* the unsortedMark becomes a reversed chain, to move up back to original position */
630463 previousCandidate = matchIndex;
630464 matchIndex = *nextCandidate;
630465 nextCandidate = bt + 2*(matchIndex&btMask);
630466 unsortedMark = bt + 2*(matchIndex&btMask) + 1;
630467 nbCandidates --;
630468 }
630469
630470 /* nullify last candidate if it's still unsorted
630471 * simplification, detrimental to compression ratio, beneficial for speed */
630472 if ( (matchIndex > unsortLimit)
630473 && (*unsortedMark==ZSTD_DUBT_UNSORTED_MARK) ) {
630474 DEBUGLOG(7, "ZSTD_DUBT_findBestMatch: nullify last unsorted candidate %u",
630475 matchIndex);
630476 *nextCandidate = *unsortedMark = 0;
630477 }
630478
630479 /* batch sort stacked candidates */
630480 matchIndex = previousCandidate;
630481 while (matchIndex) { /* will end on matchIndex == 0 */
630482 U32* const nextCandidateIdxPtr = bt + 2*(matchIndex&btMask) + 1;
630483 U32 const nextCandidateIdx = *nextCandidateIdxPtr;
630484 ZSTD_insertDUBT1(ms, matchIndex, iend,
630485 nbCandidates, unsortLimit, dictMode);
630486 matchIndex = nextCandidateIdx;
630487 nbCandidates++;
630488 }
630489
630490 /* find longest match */
630491 { size_t commonLengthSmaller = 0, commonLengthLarger = 0;
630492 const BYTE* const dictBase = ms->window.dictBase;
630493 const U32 dictLimit = ms->window.dictLimit;
630494 const BYTE* const dictEnd = dictBase + dictLimit;
630495 const BYTE* const prefixStart = base + dictLimit;
630496 U32* smallerPtr = bt + 2*(curr&btMask);
630497 U32* largerPtr = bt + 2*(curr&btMask) + 1;
630498 U32 matchEndIdx = curr + 8 + 1;
630499 U32 dummy32; /* to be nullified at the end */
630500 size_t bestLength = 0;
630501
630502 matchIndex = hashTable[h];
630503 hashTable[h] = curr; /* Update Hash Table */
630504
630505 for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
630506 U32* const nextPtr = bt + 2*(matchIndex & btMask);
630507 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
630508 const BYTE* match;
630509
630510 if ((dictMode != ZSTD_extDict) || (matchIndex+matchLength >= dictLimit)) {
630511 match = base + matchIndex;
630512 matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
630513 } else {
630514 match = dictBase + matchIndex;
630515 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
630516 if (matchIndex+matchLength >= dictLimit)
630517 match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
630518 }
630519
630520 if (matchLength > bestLength) {
630521 if (matchLength > matchEndIdx - matchIndex)
630522 matchEndIdx = matchIndex + (U32)matchLength;
630523 if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr - matchIndex + 1) - ZSTD_highbit32((U32)*offBasePtr)) )
630524 bestLength = matchLength, *offBasePtr = OFFSET_TO_OFFBASE(curr - matchIndex);
630525 if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
630526 if (dictMode == ZSTD_dictMatchState) {
630527 nbCompares = 0; /* in addition to avoiding checking any
630528 * further in this loop, make sure we
630529 * skip checking in the dictionary. */
630530 }
630531 break; /* drop, to guarantee consistency (miss a little bit of compression) */
630532 }
630533 }
630534
630535 if (match[matchLength] < ip[matchLength]) {
630536 /* match is smaller than current */
630537 *smallerPtr = matchIndex; /* update smaller idx */
630538 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
630539 if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
630540 smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
630541 matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
630542 } else {
630543 /* match is larger than current */
630544 *largerPtr = matchIndex;
630545 commonLengthLarger = matchLength;
630546 if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
630547 largerPtr = nextPtr;
630548 matchIndex = nextPtr[0];
630549 } }
630550
630551 *smallerPtr = *largerPtr = 0;
630552
630553 assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
630554 if (dictMode == ZSTD_dictMatchState && nbCompares) {
630555 bestLength = ZSTD_DUBT_findBetterDictMatch(
630556 ms, ip, iend,
630557 offBasePtr, bestLength, nbCompares,
630558 mls, dictMode);
630559 }
630560
630561 assert(matchEndIdx > curr+8); /* ensure nextToUpdate is increased */
630562 ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
630563 if (bestLength >= MINMATCH) {
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_insertDUBT1(const ZSTD_matchState_t *ms, U32 curr, const BYTE *inputEnd, U32 nbCompares, U32 btLow, const ZSTD_dictMode_e dictMode)
Definition duckdb.cpp:630248

◆ ZSTD_BtFindBestMatch()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_BtFindBestMatch ( ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iLimit,
size_t * offBasePtr,
const U32 mls,
const ZSTD_dictMode_e dictMode )

ZSTD_BtFindBestMatch() : Tree updater, providing best match

◆ ZSTD_dedicatedDictSearch_lazy_search()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::ZSTD_dedicatedDictSearch_lazy_search ( size_t * offsetPtr,
size_t ml,
U32 nbAttempts,
const ZSTD_matchState_t *const dms,
const BYTE *const ip,
const BYTE *const iLimit,
const BYTE *const prefixStart,
const U32 curr,
const U32 dictLimit,
const size_t ddsIdx )
630714 {
630715 const U32 ddsLowestIndex = dms->window.dictLimit;
630716 const BYTE* const ddsBase = dms->window.base;
630717 const BYTE* const ddsEnd = dms->window.nextSrc;
630718 const U32 ddsSize = (U32)(ddsEnd - ddsBase);
630719 const U32 ddsIndexDelta = dictLimit - ddsSize;
630720 const U32 bucketSize = (1 << ZSTD_LAZY_DDSS_BUCKET_LOG);
630721 const U32 bucketLimit = nbAttempts < bucketSize - 1 ? nbAttempts : bucketSize - 1;
630722 U32 ddsAttempt;
630723 U32 matchIndex;
630724
630725 for (ddsAttempt = 0; ddsAttempt < bucketSize - 1; ddsAttempt++) {
630726 PREFETCH_L1(ddsBase + dms->hashTable[ddsIdx + ddsAttempt]);
630727 }
630728
630729 {
630730 U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
630731 U32 const chainIndex = chainPackedPointer >> 8;
630732
630733 PREFETCH_L1(&dms->chainTable[chainIndex]);
630734 }
630735
630736 for (ddsAttempt = 0; ddsAttempt < bucketLimit; ddsAttempt++) {
630737 size_t currentMl=0;
630738 const BYTE* match;
630739 matchIndex = dms->hashTable[ddsIdx + ddsAttempt];
630740 match = ddsBase + matchIndex;
630741
630742 if (!matchIndex) {
630743 return ml;
630744 }
630745
630746 /* guaranteed by table construction */
630747 (void)ddsLowestIndex;
630748 assert(matchIndex >= ddsLowestIndex);
630749 assert(match+4 <= ddsEnd);
630750 if (MEM_read32(match) == MEM_read32(ip)) {
630751 /* assumption : matchIndex <= dictLimit-4 (by table construction) */
630752 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
630753 }
630754
630755 /* save best solution */
630756 if (currentMl > ml) {
630757 ml = currentMl;
630758 *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + ddsIndexDelta));
630759 if (ip+currentMl == iLimit) {
630760 /* best possible, avoids read overflow on next attempt */
630761 return ml;
630762 }
630763 }
630764 }
630765
630766 {
630767 U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
630768 U32 chainIndex = chainPackedPointer >> 8;
630769 U32 const chainLength = chainPackedPointer & 0xFF;
630770 U32 const chainAttempts = nbAttempts - ddsAttempt;
630771 U32 const chainLimit = chainAttempts > chainLength ? chainLength : chainAttempts;
630772 U32 chainAttempt;
630773
630774 for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++) {
630775 PREFETCH_L1(ddsBase + dms->chainTable[chainIndex + chainAttempt]);
630776 }
630777
630778 for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++, chainIndex++) {
630779 size_t currentMl=0;
630780 const BYTE* match;
630781 matchIndex = dms->chainTable[chainIndex];
630782 match = ddsBase + matchIndex;
630783
630784 /* guaranteed by table construction */
630785 assert(matchIndex >= ddsLowestIndex);
630786 assert(match+4 <= ddsEnd);
630787 if (MEM_read32(match) == MEM_read32(ip)) {
630788 /* assumption : matchIndex <= dictLimit-4 (by table construction) */
630789 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
630790 }
630791
630792 /* save best solution */
630793 if (currentMl > ml) {
630794 ml = currentMl;

◆ ZSTD_insertAndFindFirstIndex_internal()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_insertAndFindFirstIndex_internal ( ZSTD_matchState_t * ms,
const ZSTD_compressionParameters *const cParams,
const BYTE * ip,
U32 const mls,
U32 const lazySkipping )
630817{
630818 U32* const hashTable = ms->hashTable;
630819 const U32 hashLog = cParams->hashLog;
630820 U32* const chainTable = ms->chainTable;
630821 const U32 chainMask = (1 << cParams->chainLog) - 1;
630822 const BYTE* const base = ms->window.base;
630823 const U32 target = (U32)(ip - base);
630824 U32 idx = ms->nextToUpdate;
630825
630826 while(idx < target) { /* catch up */
630827 size_t const h = ZSTD_hashPtr(base+idx, hashLog, mls);
630828 NEXT_IN_CHAIN(idx, chainMask) = hashTable[h];
630829 hashTable[h] = idx;
630830 idx++;
630831 /* Stop inserting every position when in the lazy skipping mode. */

◆ ZSTD_HcFindBestMatch()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_HcFindBestMatch ( ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iLimit,
size_t * offsetPtr,
const U32 mls,
const ZSTD_dictMode_e dictMode )
630853{
630854 const ZSTD_compressionParameters* const cParams = &ms->cParams;
630855 U32* const chainTable = ms->chainTable;
630856 const U32 chainSize = (1 << cParams->chainLog);
630857 const U32 chainMask = chainSize-1;
630858 const BYTE* const base = ms->window.base;
630859 const BYTE* const dictBase = ms->window.dictBase;
630860 const U32 dictLimit = ms->window.dictLimit;
630861 const BYTE* const prefixStart = base + dictLimit;
630862 const BYTE* const dictEnd = dictBase + dictLimit;
630863 const U32 curr = (U32)(ip-base);
630864 const U32 maxDistance = 1U << cParams->windowLog;
630865 const U32 lowestValid = ms->window.lowLimit;
630866 const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
630867 const U32 isDictionary = (ms->loadedDictEnd != 0);
630868 const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
630869 const U32 minChain = curr > chainSize ? curr - chainSize : 0;
630870 U32 nbAttempts = 1U << cParams->searchLog;
630871 size_t ml=4-1;
630872
630873 const ZSTD_matchState_t* const dms = ms->dictMatchState;
630874 const U32 ddsHashLog = dictMode == ZSTD_dedicatedDictSearch
630875 ? dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
630876 const size_t ddsIdx = dictMode == ZSTD_dedicatedDictSearch
630877 ? ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
630878
630879 U32 matchIndex;
630880
630881 if (dictMode == ZSTD_dedicatedDictSearch) {
630882 const U32* entry = &dms->hashTable[ddsIdx];
630883 PREFETCH_L1(entry);
630884 }
630885
630886 /* HC4 match finder */
630887 matchIndex = ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, mls, ms->lazySkipping);
630888
630889 for ( ; (matchIndex>=lowLimit) & (nbAttempts>0) ; nbAttempts--) {
630890 size_t currentMl=0;
630891 if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
630892 const BYTE* const match = base + matchIndex;
630893 assert(matchIndex >= dictLimit); /* ensures this is true if dictMode != ZSTD_extDict */
630894 /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
630895 if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3)) /* potentially better */
630896 currentMl = ZSTD_count(ip, match, iLimit);
630897 } else {
630898 const BYTE* const match = dictBase + matchIndex;
630899 assert(match+4 <= dictEnd);
630900 if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
630901 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
630902 }
630903
630904 /* save best solution */
630905 if (currentMl > ml) {
630906 ml = currentMl;
630907 *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
630908 if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
630909 }
630910
630911 if (matchIndex <= minChain) break;
630912 matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask);
630913 }
630914
630915 assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
630916 if (dictMode == ZSTD_dedicatedDictSearch) {
630917 ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts, dms,
630918 ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
630919 } else if (dictMode == ZSTD_dictMatchState) {
630920 const U32* const dmsChainTable = dms->chainTable;
630921 const U32 dmsChainSize = (1 << dms->cParams.chainLog);
630922 const U32 dmsChainMask = dmsChainSize - 1;
630923 const U32 dmsLowestIndex = dms->window.dictLimit;
630924 const BYTE* const dmsBase = dms->window.base;
630925 const BYTE* const dmsEnd = dms->window.nextSrc;
630926 const U32 dmsSize = (U32)(dmsEnd - dmsBase);
630927 const U32 dmsIndexDelta = dictLimit - dmsSize;
630928 const U32 dmsMinChain = dmsSize > dmsChainSize ? dmsSize - dmsChainSize : 0;
630929
630930 matchIndex = dms->hashTable[ZSTD_hashPtr(ip, dms->cParams.hashLog, mls)];
630931
630932 for ( ; (matchIndex>=dmsLowestIndex) & (nbAttempts>0) ; nbAttempts--) {
630933 size_t currentMl=0;
630934 const BYTE* const match = dmsBase + matchIndex;
630935 assert(match+4 <= dmsEnd);
630936 if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
630937 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
630938
630939 /* save best solution */
630940 if (currentMl > ml) {
630941 ml = currentMl;
630942 assert(curr > matchIndex + dmsIndexDelta);
630943 *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));
630944 if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
630945 }
630946
630947 if (matchIndex <= dmsMinChain) break;

◆ ZSTD_VecMask_next()

MEM_STATIC U32 duckdb_zstd::ZSTD_VecMask_next ( ZSTD_VecMask val)

◆ ZSTD_row_nextIndex()

FORCE_INLINE_TEMPLATE U32 duckdb_zstd::ZSTD_row_nextIndex ( BYTE *const tagRow,
U32 const rowMask )

◆ ZSTD_isAligned()

MEM_STATIC int duckdb_zstd::ZSTD_isAligned ( void const * ptr,
size_t align )

◆ ZSTD_row_prefetch()

FORCE_INLINE_TEMPLATE void duckdb_zstd::ZSTD_row_prefetch ( U32 const * hashTable,
BYTE const * tagTable,
U32 const relRow,
U32 const rowLog )
630997 {
630998 PREFETCH_L1(hashTable + relRow);
630999 if (rowLog >= 5) {
631000 PREFETCH_L1(hashTable + relRow + 16);
631001 /* Note: prefetching more of the hash table does not appear to be beneficial for 128-entry rows */
631002 }
631003 PREFETCH_L1(tagTable + relRow);

◆ ZSTD_row_fillHashCache()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_row_fillHashCache ( ZSTD_matchState_t * ms,
const BYTE * base,
U32 const rowLog,
U32 const mls,
U32 idx,
const BYTE *const iLimit )
631021{
631022 U32 const* const hashTable = ms->hashTable;
631023 BYTE const* const tagTable = ms->tagTable;
631024 U32 const hashLog = ms->rowHashLog;
631025 U32 const maxElemsToPrefetch = (base + idx) > iLimit ? 0 : (U32)(iLimit - (base + idx) + 1);
631026 U32 const lim = idx + MIN(ZSTD_ROW_HASH_CACHE_SIZE, maxElemsToPrefetch);
631027
631028 for (; idx < lim; ++idx) {
631029 U32 const hash = (U32)ZSTD_hashPtrSalted(base + idx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
631030 U32 const row = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
631031 ZSTD_row_prefetch(hashTable, tagTable, row, rowLog);

◆ ZSTD_row_nextCachedHash()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_row_nextCachedHash ( U32 * cache,
U32 const * hashTable,
BYTE const * tagTable,
BYTE const * base,
U32 idx,
U32 const hashLog,
U32 const rowLog,
U32 const mls,
U64 const hashSalt )
631051{
631052 U32 const newHash = (U32)ZSTD_hashPtrSalted(base+idx+ZSTD_ROW_HASH_CACHE_SIZE, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);

◆ ZSTD_row_update_internalImpl()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_row_update_internalImpl ( ZSTD_matchState_t * ms,
U32 updateStartIdx,
U32 const updateEndIdx,
U32 const mls,
U32 const rowLog,
U32 const rowMask,
U32 const useCache )
631070{
631071 U32* const hashTable = ms->hashTable;
631072 BYTE* const tagTable = ms->tagTable;
631073 U32 const hashLog = ms->rowHashLog;
631074 const BYTE* const base = ms->window.base;
631075
631076 DEBUGLOG(6, "ZSTD_row_update_internalImpl(): updateStartIdx=%u, updateEndIdx=%u", updateStartIdx, updateEndIdx);
631077 for (; updateStartIdx < updateEndIdx; ++updateStartIdx) {
631078 U32 const hash = useCache ? ZSTD_row_nextCachedHash(ms->hashCache, hashTable, tagTable, base, updateStartIdx, hashLog, rowLog, mls, ms->hashSalt)
631079 : (U32)ZSTD_hashPtrSalted(base + updateStartIdx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
631080 U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
631081 U32* const row = hashTable + relRow;
631082 BYTE* tagRow = tagTable + relRow;

◆ ZSTD_row_update_internal()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_row_update_internal ( ZSTD_matchState_t * ms,
const BYTE * ip,
U32 const mls,
U32 const rowLog,
U32 const rowMask,
U32 const useCache )
631100{
631101 U32 idx = ms->nextToUpdate;
631102 const BYTE* const base = ms->window.base;
631103 const U32 target = (U32)(ip - base);
631104 const U32 kSkipThreshold = 384;
631105 const U32 kMaxMatchStartPositionsToUpdate = 96;
631106 const U32 kMaxMatchEndPositionsToUpdate = 32;
631107
631108 if (useCache) {
631109 /* Only skip positions when using hash cache, i.e.
631110 * if we are loading a dict, don't skip anything.
631111 * If we decide to skip, then we only update a set number
631112 * of positions at the beginning and end of the match.
631113 */
631114 if (UNLIKELY(target - idx > kSkipThreshold)) {
631115 U32 const bound = idx + kMaxMatchStartPositionsToUpdate;
631116 ZSTD_row_update_internalImpl(ms, idx, bound, mls, rowLog, rowMask, useCache);
631117 idx = target - kMaxMatchEndPositionsToUpdate;

◆ ZSTD_row_matchMaskGroupWidth()

FORCE_INLINE_TEMPLATE U32 duckdb_zstd::ZSTD_row_matchMaskGroupWidth ( const U32 rowEntries)
631145{
631146 assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
631147 assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
631148 (void)rowEntries;
631149#if defined(ZSTD_ARCH_ARM_NEON)
631150 /* NEON path only works for little endian */
631151 if (!MEM_isLittleEndian()) {
631152 return 1;
631153 }
631154 if (rowEntries == 16) {
631155 return 4;
631156 }
631157 if (rowEntries == 32) {
631158 return 2;

◆ ZSTD_row_getMatchMask()

FORCE_INLINE_TEMPLATE ZSTD_VecMask duckdb_zstd::ZSTD_row_getMatchMask ( const BYTE *const tagRow,
const BYTE tag,
const U32 headGrouped,
const U32 rowEntries )
631243{
631244 const BYTE* const src = tagRow;
631245 assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
631246 assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
631247 assert(ZSTD_row_matchMaskGroupWidth(rowEntries) * rowEntries <= sizeof(ZSTD_VecMask) * 8);
631248
631249#if defined(ZSTD_ARCH_X86_SSE2)
631250
631251 return ZSTD_row_getSSEMask(rowEntries / 16, src, tag, headGrouped);
631252
631253#else /* SW or NEON-LE */
631254
631255# if defined(ZSTD_ARCH_ARM_NEON)
631256 /* This NEON path only works for little endian - otherwise use SWAR below */
631257 if (MEM_isLittleEndian()) {
631258 return ZSTD_row_getNEONMask(rowEntries, src, tag, headGrouped);
631259 }
631260# endif /* ZSTD_ARCH_ARM_NEON */
631261 /* SWAR */
631262 { const int chunkSize = sizeof(size_t);
631263 const size_t shiftAmount = ((chunkSize * 8) - chunkSize);
631264 const size_t xFF = ~((size_t)0);
631265 const size_t x01 = xFF / 0xFF;
631266 const size_t x80 = x01 << 7;
631267 const size_t splatChar = tag * x01;
631268 ZSTD_VecMask matches = 0;
631269 int i = rowEntries - chunkSize;
631270 assert((sizeof(size_t) == 4) || (sizeof(size_t) == 8));
631271 if (MEM_isLittleEndian()) { /* runtime check so have two loops */
631272 const size_t extractMagic = (xFF / 0x7F) >> chunkSize;
631273 do {
631274 size_t chunk = MEM_readST(&src[i]);
631275 chunk ^= splatChar;
631276 chunk = (((chunk | x80) - x01) | chunk) & x80;
631277 matches <<= chunkSize;
631278 matches |= (chunk * extractMagic) >> shiftAmount;
631279 i -= chunkSize;
631280 } while (i >= 0);
631281 } else { /* big endian: reverse bits during extraction */
631282 const size_t msb = xFF ^ (xFF >> 1);
631283 const size_t extractMagic = (msb / 0x1FF) | msb;
631284 do {
631285 size_t chunk = MEM_readST(&src[i]);
631286 chunk ^= splatChar;
631287 chunk = (((chunk | x80) - x01) | chunk) & x80;
631288 matches <<= chunkSize;
631289 matches |= ((chunk >> 7) * extractMagic) >> shiftAmount;
631290 i -= chunkSize;
631291 } while (i >= 0);
631292 }
631293 matches = ~matches;
631294 if (rowEntries == 16) {
631295 return ZSTD_rotateRight_U16((U16)matches, headGrouped);
631296 } else if (rowEntries == 32) {

◆ ZSTD_RowFindBestMatch()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_RowFindBestMatch ( ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iLimit,
size_t * offsetPtr,
const U32 mls,
const ZSTD_dictMode_e dictMode,
const U32 rowLog )
631328{
631329 U32* const hashTable = ms->hashTable;
631330 BYTE* const tagTable = ms->tagTable;
631331 U32* const hashCache = ms->hashCache;
631332 const U32 hashLog = ms->rowHashLog;
631333 const ZSTD_compressionParameters* const cParams = &ms->cParams;
631334 const BYTE* const base = ms->window.base;
631335 const BYTE* const dictBase = ms->window.dictBase;
631336 const U32 dictLimit = ms->window.dictLimit;
631337 const BYTE* const prefixStart = base + dictLimit;
631338 const BYTE* const dictEnd = dictBase + dictLimit;
631339 const U32 curr = (U32)(ip-base);
631340 const U32 maxDistance = 1U << cParams->windowLog;
631341 const U32 lowestValid = ms->window.lowLimit;
631342 const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
631343 const U32 isDictionary = (ms->loadedDictEnd != 0);
631344 const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
631345 const U32 rowEntries = (1U << rowLog);
631346 const U32 rowMask = rowEntries - 1;
631347 const U32 cappedSearchLog = MIN(cParams->searchLog, rowLog); /* nb of searches is capped at nb entries per row */
631348 const U32 groupWidth = ZSTD_row_matchMaskGroupWidth(rowEntries);
631349 const U64 hashSalt = ms->hashSalt;
631350 U32 nbAttempts = 1U << cappedSearchLog;
631351 size_t ml=4-1;
631352 U32 hash;
631353
631354 /* DMS/DDS variables that may be referenced laster */
631355 const ZSTD_matchState_t* const dms = ms->dictMatchState;
631356
631357 /* Initialize the following variables to satisfy static analyzer */
631358 size_t ddsIdx = 0;
631359 U32 ddsExtraAttempts = 0; /* cctx hash tables are limited in searches, but allow extra searches into DDS */
631360 U32 dmsTag = 0;
631361 U32* dmsRow = NULL;
631362 BYTE* dmsTagRow = NULL;
631363
631364 if (dictMode == ZSTD_dedicatedDictSearch) {
631365 const U32 ddsHashLog = dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
631366 { /* Prefetch DDS hashtable entry */
631367 ddsIdx = ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG;
631368 PREFETCH_L1(&dms->hashTable[ddsIdx]);
631369 }
631370 ddsExtraAttempts = cParams->searchLog > rowLog ? 1U << (cParams->searchLog - rowLog) : 0;
631371 }
631372
631373 if (dictMode == ZSTD_dictMatchState) {
631374 /* Prefetch DMS rows */
631375 U32* const dmsHashTable = dms->hashTable;
631376 BYTE* const dmsTagTable = dms->tagTable;
631377 U32 const dmsHash = (U32)ZSTD_hashPtr(ip, dms->rowHashLog + ZSTD_ROW_HASH_TAG_BITS, mls);
631378 U32 const dmsRelRow = (dmsHash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
631379 dmsTag = dmsHash & ZSTD_ROW_HASH_TAG_MASK;
631380 dmsTagRow = (BYTE*)(dmsTagTable + dmsRelRow);
631381 dmsRow = dmsHashTable + dmsRelRow;
631382 ZSTD_row_prefetch(dmsHashTable, dmsTagTable, dmsRelRow, rowLog);
631383 }
631384
631385 /* Update the hashTable and tagTable up to (but not including) ip */
631386 if (!ms->lazySkipping) {
631387 ZSTD_row_update_internal(ms, ip, mls, rowLog, rowMask, 1 /* useCache */);
631388 hash = ZSTD_row_nextCachedHash(hashCache, hashTable, tagTable, base, curr, hashLog, rowLog, mls, hashSalt);
631389 } else {
631390 /* Stop inserting every position when in the lazy skipping mode.
631391 * The hash cache is also not kept up to date in this mode.
631392 */
631393 hash = (U32)ZSTD_hashPtrSalted(ip, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);
631394 ms->nextToUpdate = curr;
631395 }
631396 ms->hashSaltEntropy += hash; /* collect salt entropy */
631397
631398 { /* Get the hash for ip, compute the appropriate row */
631399 U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
631400 U32 const tag = hash & ZSTD_ROW_HASH_TAG_MASK;
631401 U32* const row = hashTable + relRow;
631402 BYTE* tagRow = (BYTE*)(tagTable + relRow);
631403 U32 const headGrouped = (*tagRow & rowMask) * groupWidth;
631404 U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
631405 size_t numMatches = 0;
631406 size_t currMatch = 0;
631407 ZSTD_VecMask matches = ZSTD_row_getMatchMask(tagRow, (BYTE)tag, headGrouped, rowEntries);
631408
631409 /* Cycle through the matches and prefetch */
631410 for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
631411 U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
631412 U32 const matchIndex = row[matchPos];
631413 if(matchPos == 0) continue;
631414 assert(numMatches < rowEntries);
631415 if (matchIndex < lowLimit)
631416 break;
631417 if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
631418 PREFETCH_L1(base + matchIndex);
631419 } else {
631420 PREFETCH_L1(dictBase + matchIndex);
631421 }
631422 matchBuffer[numMatches++] = matchIndex;
631423 --nbAttempts;
631424 }
631425
631426 /* Speed opt: insert current byte into hashtable too. This allows us to avoid one iteration of the loop
631427 in ZSTD_row_update_internal() at the next search. */
631428 {
631429 U32 const pos = ZSTD_row_nextIndex(tagRow, rowMask);
631430 tagRow[pos] = (BYTE)tag;
631431 row[pos] = ms->nextToUpdate++;
631432 }
631433
631434 /* Return the longest match */
631435 for (; currMatch < numMatches; ++currMatch) {
631436 U32 const matchIndex = matchBuffer[currMatch];
631437 size_t currentMl=0;
631438 assert(matchIndex < curr);
631439 assert(matchIndex >= lowLimit);
631440
631441 if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
631442 const BYTE* const match = base + matchIndex;
631443 assert(matchIndex >= dictLimit); /* ensures this is true if dictMode != ZSTD_extDict */
631444 /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
631445 if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3)) /* potentially better */
631446 currentMl = ZSTD_count(ip, match, iLimit);
631447 } else {
631448 const BYTE* const match = dictBase + matchIndex;
631449 assert(match+4 <= dictEnd);
631450 if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
631451 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
631452 }
631453
631454 /* Save best solution */
631455 if (currentMl > ml) {
631456 ml = currentMl;
631457 *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
631458 if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
631459 }
631460 }
631461 }
631462
631463 assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
631464 if (dictMode == ZSTD_dedicatedDictSearch) {
631465 ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts + ddsExtraAttempts, dms,
631466 ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
631467 } else if (dictMode == ZSTD_dictMatchState) {
631468 /* TODO: Measure and potentially add prefetching to DMS */
631469 const U32 dmsLowestIndex = dms->window.dictLimit;
631470 const BYTE* const dmsBase = dms->window.base;
631471 const BYTE* const dmsEnd = dms->window.nextSrc;
631472 const U32 dmsSize = (U32)(dmsEnd - dmsBase);
631473 const U32 dmsIndexDelta = dictLimit - dmsSize;
631474
631475 { U32 const headGrouped = (*dmsTagRow & rowMask) * groupWidth;
631476 U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
631477 size_t numMatches = 0;
631478 size_t currMatch = 0;
631479 ZSTD_VecMask matches = ZSTD_row_getMatchMask(dmsTagRow, (BYTE)dmsTag, headGrouped, rowEntries);
631480
631481 for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
631482 U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
631483 U32 const matchIndex = dmsRow[matchPos];
631484 if(matchPos == 0) continue;
631485 if (matchIndex < dmsLowestIndex)
631486 break;
631487 PREFETCH_L1(dmsBase + matchIndex);
631488 matchBuffer[numMatches++] = matchIndex;
631489 --nbAttempts;
631490 }
631491
631492 /* Return the longest match */
631493 for (; currMatch < numMatches; ++currMatch) {
631494 U32 const matchIndex = matchBuffer[currMatch];
631495 size_t currentMl=0;
631496 assert(matchIndex >= dmsLowestIndex);
631497 assert(matchIndex < curr);
631498
631499 { const BYTE* const match = dmsBase + matchIndex;
631500 assert(match+4 <= dmsEnd);
631501 if (MEM_read32(match) == MEM_read32(ip))
631502 currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
631503 }
631504
631505 if (currentMl > ml) {
631506 ml = currentMl;
631507 assert(curr > matchIndex + dmsIndexDelta);
631508 *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));

◆ ZSTD_searchMax()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::ZSTD_searchMax ( ZSTD_matchState_t * ms,
const BYTE * ip,
const BYTE * iend,
size_t * offsetPtr,
U32 const mls,
U32 const rowLog,
searchMethod_e const searchMethod,
ZSTD_dictMode_e const dictMode )

Searches for the longest match at ip. Dispatches to the correct implementation function based on the (searchMethod, dictMode, mls, rowLog). We use switch statements here instead of using an indirect function call through a function pointer because after Spectre and Meltdown mitigations, indirect function calls can be very costly, especially in the kernel.

NOTE: dictMode and searchMethod should be templated, so those switch statements should be optimized out. Only the mls & rowLog switches should be left.

Parameters
msThe match state.
ipThe position to search at.
iendThe end of the input data.
[out]offsetPtrStores the match offset into this pointer.
mlsThe minimum search length, in the range [4, 6].
rowLogThe row log (if applicable), in the range [4, 6].
searchMethodThe search method to use (templated).
dictModeThe dictMode (templated).
Returns
The length of the longest match found, or < mls if no match is found. If a match is found its offset is stored in offsetPtr.
631677{
631678 if (dictMode == ZSTD_noDict) {
631679 ZSTD_SWITCH_SEARCH_METHOD(noDict)
631680 } else if (dictMode == ZSTD_extDict) {
631681 ZSTD_SWITCH_SEARCH_METHOD(extDict)
631682 } else if (dictMode == ZSTD_dictMatchState) {
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_compressBlock_lazy_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_lazy_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize,
const searchMethod_e searchMethod,
const U32 depth,
ZSTD_dictMode_e const dictMode )
631703{
631704 const BYTE* const istart = (const BYTE*)src;
631705 const BYTE* ip = istart;
631706 const BYTE* anchor = istart;
631707 const BYTE* const iend = istart + srcSize;
631708 const BYTE* const ilimit = (searchMethod == search_rowHash) ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
631709 const BYTE* const base = ms->window.base;
631710 const U32 prefixLowestIndex = ms->window.dictLimit;
631711 const BYTE* const prefixLowest = base + prefixLowestIndex;
631712 const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
631713 const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
631714
631715 U32 offset_1 = rep[0], offset_2 = rep[1];
631716 U32 offsetSaved1 = 0, offsetSaved2 = 0;
631717
631718 const int isDMS = dictMode == ZSTD_dictMatchState;
631719 const int isDDS = dictMode == ZSTD_dedicatedDictSearch;
631720 const int isDxS = isDMS || isDDS;
631721 const ZSTD_matchState_t* const dms = ms->dictMatchState;
631722 const U32 dictLowestIndex = isDxS ? dms->window.dictLimit : 0;
631723 const BYTE* const dictBase = isDxS ? dms->window.base : NULL;
631724 const BYTE* const dictLowest = isDxS ? dictBase + dictLowestIndex : NULL;
631725 const BYTE* const dictEnd = isDxS ? dms->window.nextSrc : NULL;
631726 const U32 dictIndexDelta = isDxS ?
631727 prefixLowestIndex - (U32)(dictEnd - dictBase) :
631728 0;
631729 const U32 dictAndPrefixLength = (U32)((ip - prefixLowest) + (dictEnd - dictLowest));
631730
631731 DEBUGLOG(5, "ZSTD_compressBlock_lazy_generic (dictMode=%u) (searchFunc=%u)", (U32)dictMode, (U32)searchMethod);
631732 ip += (dictAndPrefixLength == 0);
631733 if (dictMode == ZSTD_noDict) {
631734 U32 const curr = (U32)(ip - base);
631735 U32 const windowLow = ZSTD_getLowestPrefixIndex(ms, curr, ms->cParams.windowLog);
631736 U32 const maxRep = curr - windowLow;
631737 if (offset_2 > maxRep) offsetSaved2 = offset_2, offset_2 = 0;
631738 if (offset_1 > maxRep) offsetSaved1 = offset_1, offset_1 = 0;
631739 }
631740 if (isDxS) {
631741 /* dictMatchState repCode checks don't currently handle repCode == 0
631742 * disabling. */
631743 assert(offset_1 <= dictAndPrefixLength);
631744 assert(offset_2 <= dictAndPrefixLength);
631745 }
631746
631747 /* Reset the lazy skipping state */
631748 ms->lazySkipping = 0;
631749
631750 if (searchMethod == search_rowHash) {
631751 ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
631752 }
631753
631754 /* Match Loop */
631755#if defined(__GNUC__) && defined(__x86_64__)
631756 /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
631757 * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
631758 */
631759 __asm__(".p2align 5");
631760#endif
631761 while (ip < ilimit) {
631762 size_t matchLength=0;
631763 size_t offBase = REPCODE1_TO_OFFBASE;
631764 const BYTE* start=ip+1;
631765 DEBUGLOG(7, "search baseline (depth 0)");
631766
631767 /* check repCode */
631768 if (isDxS) {
631769 const U32 repIndex = (U32)(ip - base) + 1 - offset_1;
631770 const BYTE* repMatch = ((dictMode == ZSTD_dictMatchState || dictMode == ZSTD_dedicatedDictSearch)
631771 && repIndex < prefixLowestIndex) ?
631772 dictBase + (repIndex - dictIndexDelta) :
631773 base + repIndex;
631774 if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
631775 && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
631776 const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
631777 matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
631778 if (depth==0) goto _storeSequence;
631779 }
631780 }
631781 if ( dictMode == ZSTD_noDict
631782 && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
631783 matchLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
631784 if (depth==0) goto _storeSequence;
631785 }
631786
631787 /* first search (depth 0) */
631788 { size_t offbaseFound = 999999999;
631789 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &offbaseFound, mls, rowLog, searchMethod, dictMode);
631790 if (ml2 > matchLength)
631791 matchLength = ml2, start = ip, offBase = offbaseFound;
631792 }
631793
631794 if (matchLength < 4) {
631795 size_t const step = ((size_t)(ip-anchor) >> kSearchStrength) + 1; /* jump faster over incompressible sections */;
631796 ip += step;
631797 /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
631798 * In this mode we stop inserting every position into our tables, and only insert
631799 * positions that we search, which is one in step positions.
631800 * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
631801 * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
631802 * triggered once we've gone 2KB without finding any matches.
631803 */
631804 ms->lazySkipping = step > kLazySkippingStep;
631805 continue;
631806 }
631807
631808 /* let's try to find a better solution */
631809 if (depth>=1)
631810 while (ip<ilimit) {
631811 DEBUGLOG(7, "search depth 1");
631812 ip ++;
631813 if ( (dictMode == ZSTD_noDict)
631814 && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
631815 size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
631816 int const gain2 = (int)(mlRep * 3);
631817 int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
631818 if ((mlRep >= 4) && (gain2 > gain1))
631819 matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
631820 }
631821 if (isDxS) {
631822 const U32 repIndex = (U32)(ip - base) - offset_1;
631823 const BYTE* repMatch = repIndex < prefixLowestIndex ?
631824 dictBase + (repIndex - dictIndexDelta) :
631825 base + repIndex;
631826 if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
631827 && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
631828 const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
631829 size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
631830 int const gain2 = (int)(mlRep * 3);
631831 int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
631832 if ((mlRep >= 4) && (gain2 > gain1))
631833 matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
631834 }
631835 }
631836 { size_t ofbCandidate=999999999;
631837 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
631838 int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
631839 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
631840 if ((ml2 >= 4) && (gain2 > gain1)) {
631841 matchLength = ml2, offBase = ofbCandidate, start = ip;
631842 continue; /* search a better one */
631843 } }
631844
631845 /* let's find an even better one */
631846 if ((depth==2) && (ip<ilimit)) {
631847 DEBUGLOG(7, "search depth 2");
631848 ip ++;
631849 if ( (dictMode == ZSTD_noDict)
631850 && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
631851 size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
631852 int const gain2 = (int)(mlRep * 4);
631853 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
631854 if ((mlRep >= 4) && (gain2 > gain1))
631855 matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
631856 }
631857 if (isDxS) {
631858 const U32 repIndex = (U32)(ip - base) - offset_1;
631859 const BYTE* repMatch = repIndex < prefixLowestIndex ?
631860 dictBase + (repIndex - dictIndexDelta) :
631861 base + repIndex;
631862 if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
631863 && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
631864 const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
631865 size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
631866 int const gain2 = (int)(mlRep * 4);
631867 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
631868 if ((mlRep >= 4) && (gain2 > gain1))
631869 matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
631870 }
631871 }
631872 { size_t ofbCandidate=999999999;
631873 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
631874 int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
631875 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
631876 if ((ml2 >= 4) && (gain2 > gain1)) {
631877 matchLength = ml2, offBase = ofbCandidate, start = ip;
631878 continue;
631879 } } }
631880 break; /* nothing found : store previous solution */
631881 }
631882
631883 /* NOTE:
631884 * Pay attention that `start[-value]` can lead to strange undefined behavior
631885 * notably if `value` is unsigned, resulting in a large positive `-value`.
631886 */
631887 /* catch up */
631888 if (OFFBASE_IS_OFFSET(offBase)) {
631889 if (dictMode == ZSTD_noDict) {
631890 while ( ((start > anchor) & (start - OFFBASE_TO_OFFSET(offBase) > prefixLowest))
631891 && (start[-1] == (start-OFFBASE_TO_OFFSET(offBase))[-1]) ) /* only search for offset within prefix */
631892 { start--; matchLength++; }
631893 }
631894 if (isDxS) {
631895 U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
631896 const BYTE* match = (matchIndex < prefixLowestIndex) ? dictBase + matchIndex - dictIndexDelta : base + matchIndex;
631897 const BYTE* const mStart = (matchIndex < prefixLowestIndex) ? dictLowest : prefixLowest;
631898 while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
631899 }
631900 offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
631901 }
631902 /* store sequence */
631903_storeSequence:
631904 { size_t const litLength = (size_t)(start - anchor);
631905 ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
631906 anchor = ip = start + matchLength;
631907 }
631908 if (ms->lazySkipping) {
631909 /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
631910 if (searchMethod == search_rowHash) {
631911 ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
631912 }
631913 ms->lazySkipping = 0;
631914 }
631915
631916 /* check immediate repcode */
631917 if (isDxS) {
631918 while (ip <= ilimit) {
631919 U32 const current2 = (U32)(ip-base);
631920 U32 const repIndex = current2 - offset_2;
631921 const BYTE* repMatch = repIndex < prefixLowestIndex ?
631922 dictBase - dictIndexDelta + repIndex :
631923 base + repIndex;
631924 if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex) >= 3 /* intentional overflow */)
631925 && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
631926 const BYTE* const repEnd2 = repIndex < prefixLowestIndex ? dictEnd : iend;
631927 matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd2, prefixLowest) + 4;
631928 offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap offset_2 <=> offset_1 */
631929 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
631930 ip += matchLength;
631931 anchor = ip;
631932 continue;
631933 }
631934 break;
631935 }
631936 }
631937
631938 if (dictMode == ZSTD_noDict) {
631939 while ( ((ip <= ilimit) & (offset_2>0))
631940 && (MEM_read32(ip) == MEM_read32(ip - offset_2)) ) {
631941 /* store sequence */
631942 matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
631943 offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap repcodes */
631944 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
631945 ip += matchLength;
631946 anchor = ip;
631947 continue; /* faster when present ... (?) */
631948 } } }
631949
631950 /* If offset_1 started invalid (offsetSaved1 != 0) and became valid (offset_1 != 0),
631951 * rotate saved offsets. See comment in ZSTD_compressBlock_fast_noDict for more context. */
631952 offsetSaved2 = ((offsetSaved1 != 0) && (offset_1 != 0)) ? offsetSaved1 : offsetSaved2;
631953
FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax(ZSTD_matchState_t *ms, const BYTE *ip, const BYTE *iend, size_t *offsetPtr, U32 const mls, U32 const rowLog, searchMethod_e const searchMethod, ZSTD_dictMode_e const dictMode)
Definition duckdb.cpp:631661

◆ ZSTD_compressBlock_lazy_extDict_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_lazy_extDict_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize,
const searchMethod_e searchMethod,
const U32 depth )
632123{
632124 const BYTE* const istart = (const BYTE*)src;
632125 const BYTE* ip = istart;
632126 const BYTE* anchor = istart;
632127 const BYTE* const iend = istart + srcSize;
632128 const BYTE* const ilimit = searchMethod == search_rowHash ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
632129 const BYTE* const base = ms->window.base;
632130 const U32 dictLimit = ms->window.dictLimit;
632131 const BYTE* const prefixStart = base + dictLimit;
632132 const BYTE* const dictBase = ms->window.dictBase;
632133 const BYTE* const dictEnd = dictBase + dictLimit;
632134 const BYTE* const dictStart = dictBase + ms->window.lowLimit;
632135 const U32 windowLog = ms->cParams.windowLog;
632136 const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
632137 const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
632138
632139 U32 offset_1 = rep[0], offset_2 = rep[1];
632140
632141 DEBUGLOG(5, "ZSTD_compressBlock_lazy_extDict_generic (searchFunc=%u)", (U32)searchMethod);
632142
632143 /* Reset the lazy skipping state */
632144 ms->lazySkipping = 0;
632145
632146 /* init */
632147 ip += (ip == prefixStart);
632148 if (searchMethod == search_rowHash) {
632149 ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
632150 }
632151
632152 /* Match Loop */
632153#if defined(__GNUC__) && defined(__x86_64__)
632154 /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
632155 * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
632156 */
632157 __asm__(".p2align 5");
632158#endif
632159 while (ip < ilimit) {
632160 size_t matchLength=0;
632161 size_t offBase = REPCODE1_TO_OFFBASE;
632162 const BYTE* start=ip+1;
632163 U32 curr = (U32)(ip-base);
632164
632165 /* check repCode */
632166 { const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr+1, windowLog);
632167 const U32 repIndex = (U32)(curr+1 - offset_1);
632168 const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
632169 const BYTE* const repMatch = repBase + repIndex;
632170 if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
632171 & (offset_1 <= curr+1 - windowLow) ) /* note: we are searching at curr+1 */
632172 if (MEM_read32(ip+1) == MEM_read32(repMatch)) {
632173 /* repcode detected we should take it */
632174 const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
632175 matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repEnd, prefixStart) + 4;
632176 if (depth==0) goto _storeSequence;
632177 } }
632178
632179 /* first search (depth 0) */
632180 { size_t ofbCandidate = 999999999;
632181 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
632182 if (ml2 > matchLength)
632183 matchLength = ml2, start = ip, offBase = ofbCandidate;
632184 }
632185
632186 if (matchLength < 4) {
632187 size_t const step = ((size_t)(ip-anchor) >> kSearchStrength);
632188 ip += step + 1; /* jump faster over incompressible sections */
632189 /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
632190 * In this mode we stop inserting every position into our tables, and only insert
632191 * positions that we search, which is one in step positions.
632192 * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
632193 * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
632194 * triggered once we've gone 2KB without finding any matches.
632195 */
632196 ms->lazySkipping = step > kLazySkippingStep;
632197 continue;
632198 }
632199
632200 /* let's try to find a better solution */
632201 if (depth>=1)
632202 while (ip<ilimit) {
632203 ip ++;
632204 curr++;
632205 /* check repCode */
632206 if (offBase) {
632207 const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
632208 const U32 repIndex = (U32)(curr - offset_1);
632209 const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
632210 const BYTE* const repMatch = repBase + repIndex;
632211 if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
632212 & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
632213 if (MEM_read32(ip) == MEM_read32(repMatch)) {
632214 /* repcode detected */
632215 const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
632216 size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
632217 int const gain2 = (int)(repLength * 3);
632218 int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
632219 if ((repLength >= 4) && (gain2 > gain1))
632220 matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
632221 } }
632222
632223 /* search match, depth 1 */
632224 { size_t ofbCandidate = 999999999;
632225 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
632226 int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
632227 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
632228 if ((ml2 >= 4) && (gain2 > gain1)) {
632229 matchLength = ml2, offBase = ofbCandidate, start = ip;
632230 continue; /* search a better one */
632231 } }
632232
632233 /* let's find an even better one */
632234 if ((depth==2) && (ip<ilimit)) {
632235 ip ++;
632236 curr++;
632237 /* check repCode */
632238 if (offBase) {
632239 const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
632240 const U32 repIndex = (U32)(curr - offset_1);
632241 const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
632242 const BYTE* const repMatch = repBase + repIndex;
632243 if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
632244 & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
632245 if (MEM_read32(ip) == MEM_read32(repMatch)) {
632246 /* repcode detected */
632247 const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
632248 size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
632249 int const gain2 = (int)(repLength * 4);
632250 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
632251 if ((repLength >= 4) && (gain2 > gain1))
632252 matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
632253 } }
632254
632255 /* search match, depth 2 */
632256 { size_t ofbCandidate = 999999999;
632257 size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
632258 int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
632259 int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
632260 if ((ml2 >= 4) && (gain2 > gain1)) {
632261 matchLength = ml2, offBase = ofbCandidate, start = ip;
632262 continue;
632263 } } }
632264 break; /* nothing found : store previous solution */
632265 }
632266
632267 /* catch up */
632268 if (OFFBASE_IS_OFFSET(offBase)) {
632269 U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
632270 const BYTE* match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex;
632271 const BYTE* const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart;
632272 while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
632273 offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
632274 }
632275
632276 /* store sequence */
632277_storeSequence:
632278 { size_t const litLength = (size_t)(start - anchor);
632279 ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
632280 anchor = ip = start + matchLength;
632281 }
632282 if (ms->lazySkipping) {
632283 /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
632284 if (searchMethod == search_rowHash) {
632285 ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
632286 }
632287 ms->lazySkipping = 0;
632288 }
632289
632290 /* check immediate repcode */
632291 while (ip <= ilimit) {
632292 const U32 repCurrent = (U32)(ip-base);
632293 const U32 windowLow = ZSTD_getLowestMatchIndex(ms, repCurrent, windowLog);
632294 const U32 repIndex = repCurrent - offset_2;
632295 const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
632296 const BYTE* const repMatch = repBase + repIndex;
632297 if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
632298 & (offset_2 <= repCurrent - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
632299 if (MEM_read32(ip) == MEM_read32(repMatch)) {
632300 /* repcode detected we should take it */
632301 const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
632302 matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
632303 offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap offset history */
632304 ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
632305 ip += matchLength;
632306 anchor = ip;
632307 continue; /* faster when present ... (?) */
632308 }
632309 break;
632310 } }
632311
double depth(InputArray R, InputArray t, InputArray X)

◆ ZSTD_ldm_gear_init()

void duckdb_zstd::ZSTD_ldm_gear_init ( ldmRollingHashState_t * state,
ldmParams_t const * params )
static

ZSTD_ldm_gear_init():

Initializes the rolling hash state such that it will honor the settings in params.

632546{
632547 unsigned maxBitsInMask = MIN(params->minMatchLength, 64);
632548 unsigned hashRateLog = params->hashRateLog;
632549
632550 state->rolling = ~(U32)0;
632551
632552 /* The choice of the splitting criterion is subject to two conditions:
632553 * 1. it has to trigger on average every 2^(hashRateLog) bytes;
632554 * 2. ideally, it has to depend on a window of minMatchLength bytes.
632555 *
632556 * In the gear hash algorithm, bit n depends on the last n bytes;
632557 * so in order to obtain a good quality splitting criterion it is
632558 * preferable to use bits with high weight.
632559 *
632560 * To match condition 1 we use a mask with hashRateLog bits set
632561 * and, because of the previous remark, we make sure these bits
632562 * have the highest possible weight while still respecting
632563 * condition 2.
632564 */

◆ ZSTD_ldm_gear_reset()

void duckdb_zstd::ZSTD_ldm_gear_reset ( ldmRollingHashState_t * state,
BYTE const * data,
size_t minMatchLength )
static

ZSTD_ldm_gear_reset() Feeds [data, data + minMatchLength) into the hash without registering any splits. This effectively resets the hash state. This is used when skipping over data, either at the beginning of a block, or skipping sections.

632580{
632581 U64 hash = state->rolling;
632582 size_t n = 0;
632583
632584#define GEAR_ITER_ONCE() do { \
632585 hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
632586 n += 1; \
632587 } while (0)
632588 while (n + 3 < minMatchLength) {
632589 GEAR_ITER_ONCE();
632590 GEAR_ITER_ONCE();
632591 GEAR_ITER_ONCE();

◆ ZSTD_ldm_gear_feed()

size_t duckdb_zstd::ZSTD_ldm_gear_feed ( ldmRollingHashState_t * state,
BYTE const * data,
size_t size,
size_t * splits,
unsigned * numSplits )
static

ZSTD_ldm_gear_feed():

Registers in the splits array all the split points found in the first size bytes following the data pointer. This function terminates when either all the data has been processed or LDM_BATCH_SIZE splits are present in the splits array.

Precondition: The splits array must not be full. Returns: The number of bytes processed.

632607 : The splits array must not be full.
632608 * Returns: The number of bytes processed. */
632609static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state,
632610 BYTE const* data, size_t size,
632611 size_t* splits, unsigned* numSplits)
632612{
632613 size_t n;
632614 U64 hash, mask;
632615
632616 hash = state->rolling;
632617 mask = state->stopMask;
632618 n = 0;
632619
632620#define GEAR_ITER_ONCE() do { \
632621 hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
632622 n += 1; \
632623 if (UNLIKELY((hash & mask) == 0)) { \
632624 splits[*numSplits] = n; \
632625 *numSplits += 1; \
632626 if (*numSplits == LDM_BATCH_SIZE) \
632627 goto done; \
632628 } \
632629 } while (0)
632630
632631 while (n + 3 < size) {
632632 GEAR_ITER_ONCE();
632633 GEAR_ITER_ONCE();
632634 GEAR_ITER_ONCE();
632635 GEAR_ITER_ONCE();
632636 }
632637 while (n < size) {
632638 GEAR_ITER_ONCE();
632639 }
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_ldm_getBucket()

ldmEntry_t * duckdb_zstd::ZSTD_ldm_getBucket ( ldmState_t * ldmState,
size_t hash,
ldmParams_t const ldmParams )
static

ZSTD_ldm_getBucket() : Returns a pointer to the start of the bucket associated with hash.

632679{
632680 return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
632681}
632682
Here is the call graph for this function:

◆ ZSTD_ldm_insertEntry()

void duckdb_zstd::ZSTD_ldm_insertEntry ( ldmState_t * ldmState,
size_t const hash,
const ldmEntry_t entry,
ldmParams_t const ldmParams )
static

ZSTD_ldm_insertEntry() : Insert the entry with corresponding hash into the hash table

632687{
632688 return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
632689}
632690
632693static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
632694 size_t const hash, const ldmEntry_t entry,
632695 ldmParams_t const ldmParams)
632696{
static void ZSTD_ldm_insertEntry(ldmState_t *ldmState, size_t const hash, const ldmEntry_t entry, ldmParams_t const ldmParams)
Definition duckdb.cpp:632686

◆ ZSTD_ldm_countBackwardsMatch()

size_t duckdb_zstd::ZSTD_ldm_countBackwardsMatch ( const BYTE * pIn,
const BYTE * pAnchor,
const BYTE * pMatch,
const BYTE * pMatchBase )
static

ZSTD_ldm_countBackwardsMatch() : Returns the number of bytes that match backwards before pIn and pMatch.

We count only bytes where pMatch >= pBase and pIn >= pAnchor.

632712{
632713 size_t matchLength = 0;

◆ ZSTD_ldm_countBackwardsMatch_2segments()

size_t duckdb_zstd::ZSTD_ldm_countBackwardsMatch_2segments ( const BYTE * pIn,
const BYTE * pAnchor,
const BYTE * pMatch,
const BYTE * pMatchBase,
const BYTE * pExtDictStart,
const BYTE * pExtDictEnd )
static

ZSTD_ldm_countBackwardsMatch_2segments() : Returns the number of bytes that match backwards from pMatch, even with the backwards match spanning 2 different segments.

On reaching pMatchBase, start counting from mEnd

632731{
632732 size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
632733 if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
632734 /* If backwards match is entirely in the extDict or prefix, immediately return */
static size_t ZSTD_ldm_countBackwardsMatch(const BYTE *pIn, const BYTE *pAnchor, const BYTE *pMatch, const BYTE *pMatchBase)
Definition duckdb.cpp:632702

◆ ZSTD_ldm_fillFastTables()

size_t duckdb_zstd::ZSTD_ldm_fillFastTables ( ZSTD_matchState_t * ms,
void const * end )
static

ZSTD_ldm_fillFastTables() :

Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies. This is similar to ZSTD_loadDictionaryContent.

The tables for the other strategies are filled within their block compressors.

632752{
632753 const BYTE* const iend = (const BYTE*)end;
632754
632755 switch(ms->cParams.strategy)
632756 {
632757 case ZSTD_fast:
632758 ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
632759 break;
632760
632761 case ZSTD_dfast:
632762#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
632763 ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
632764#else
632765 assert(0); /* shouldn't be called: cparams should've been adjusted. */
632766#endif
632767 break;
632768
632769 case ZSTD_greedy:
632770 case ZSTD_lazy:
632771 case ZSTD_lazy2:
632772 case ZSTD_btlazy2:
632773 case ZSTD_btopt:
632774 case ZSTD_btultra:
632775 case ZSTD_btultra2:
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_ldm_limitTableUpdate()

void duckdb_zstd::ZSTD_ldm_limitTableUpdate ( ZSTD_matchState_t * ms,
const BYTE * anchor )
static

ZSTD_ldm_limitTableUpdate() :

Sets cctx->nextToUpdate to a position corresponding closer to anchor if it is far way (after a long match, only update tables a limited amount).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_ldm_generateSequences_internal()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_ldm_generateSequences_internal ( ldmState_t * ldmState,
rawSeqStore_t * rawSeqStore,
ldmParams_t const * params,
void const * src,
size_t srcSize )
static
632843{
632844 /* LDM parameters */
632845 int const extDict = ZSTD_window_hasExtDict(ldmState->window);
632846 U32 const minMatchLength = params->minMatchLength;
632847 U32 const entsPerBucket = 1U << params->bucketSizeLog;
632848 U32 const hBits = params->hashLog - params->bucketSizeLog;
632849 /* Prefix and extDict parameters */
632850 U32 const dictLimit = ldmState->window.dictLimit;
632851 U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
632852 BYTE const* const base = ldmState->window.base;
632853 BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
632854 BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
632855 BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
632856 BYTE const* const lowPrefixPtr = base + dictLimit;
632857 /* Input bounds */
632858 BYTE const* const istart = (BYTE const*)src;
632859 BYTE const* const iend = istart + srcSize;
632860 BYTE const* const ilimit = iend - HASH_READ_SIZE;
632861 /* Input positions */
632862 BYTE const* anchor = istart;
632863 BYTE const* ip = istart;
632864 /* Rolling hash state */
632865 ldmRollingHashState_t hashState;
632866 /* Arrays for staged-processing */
632867 size_t* const splits = ldmState->splitIndices;
632868 ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
632869 unsigned numSplits;
632870
632871 if (srcSize < minMatchLength)
632872 return iend - anchor;
632873
632874 /* Initialize the rolling hash state with the first minMatchLength bytes */
632875 ZSTD_ldm_gear_init(&hashState, params);
632876 ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
632877 ip += minMatchLength;
632878
632879 while (ip < ilimit) {
632880 size_t hashed;
632881 unsigned n;
632882
632883 numSplits = 0;
632884 hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
632885 splits, &numSplits);
632886
632887 for (n = 0; n < numSplits; n++) {
632888 BYTE const* const split = ip + splits[n] - minMatchLength;
632889 U64 const xxhash = XXH64(split, minMatchLength, 0);
632890 U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
632891
632892 candidates[n].split = split;
632893 candidates[n].hash = hash;
632894 candidates[n].checksum = (U32)(xxhash >> 32);
632895 candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, *params);
632896 PREFETCH_L1(candidates[n].bucket);
632897 }
632898
632899 for (n = 0; n < numSplits; n++) {
632900 size_t forwardMatchLength = 0, backwardMatchLength = 0,
632901 bestMatchLength = 0, mLength;
632902 U32 offset;
632903 BYTE const* const split = candidates[n].split;
632904 U32 const checksum = candidates[n].checksum;
632905 U32 const hash = candidates[n].hash;
632906 ldmEntry_t* const bucket = candidates[n].bucket;
632907 ldmEntry_t const* cur;
632908 ldmEntry_t const* bestEntry = NULL;
632909 ldmEntry_t newEntry;
632910
632911 newEntry.offset = (U32)(split - base);
632912 newEntry.checksum = checksum;
632913
632914 /* If a split point would generate a sequence overlapping with
632915 * the previous one, we merely register it in the hash table and
632916 * move on */
632917 if (split < anchor) {
632918 ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
632919 continue;
632920 }
632921
632922 for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
632923 size_t curForwardMatchLength, curBackwardMatchLength,
632924 curTotalMatchLength;
632925 if (cur->checksum != checksum || cur->offset <= lowestIndex) {
632926 continue;
632927 }
632928 if (extDict) {
632929 BYTE const* const curMatchBase =
632930 cur->offset < dictLimit ? dictBase : base;
632931 BYTE const* const pMatch = curMatchBase + cur->offset;
632932 BYTE const* const matchEnd =
632933 cur->offset < dictLimit ? dictEnd : iend;
632934 BYTE const* const lowMatchPtr =
632935 cur->offset < dictLimit ? dictStart : lowPrefixPtr;
632936 curForwardMatchLength =
632937 ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
632938 if (curForwardMatchLength < minMatchLength) {
632939 continue;
632940 }
632941 curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
632942 split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
632943 } else { /* !extDict */
632944 BYTE const* const pMatch = base + cur->offset;
632945 curForwardMatchLength = ZSTD_count(split, pMatch, iend);
632946 if (curForwardMatchLength < minMatchLength) {
632947 continue;
632948 }
632949 curBackwardMatchLength =
632950 ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
632951 }
632952 curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
632953
632954 if (curTotalMatchLength > bestMatchLength) {
632955 bestMatchLength = curTotalMatchLength;
632956 forwardMatchLength = curForwardMatchLength;
632957 backwardMatchLength = curBackwardMatchLength;
632958 bestEntry = cur;
632959 }
632960 }
632961
632962 /* No match found -- insert an entry into the hash table
632963 * and process the next candidate match */
632964 if (bestEntry == NULL) {
632965 ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
632966 continue;
632967 }
632968
632969 /* Match found */
632970 offset = (U32)(split - base) - bestEntry->offset;
632971 mLength = forwardMatchLength + backwardMatchLength;
632972 {
632973 rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
632974
632975 /* Out of sequence storage */
632976 if (rawSeqStore->size == rawSeqStore->capacity)
632977 return ERROR(dstSize_tooSmall);
632978 seq->litLength = (U32)(split - backwardMatchLength - anchor);
632979 seq->matchLength = (U32)mLength;
632980 seq->offset = offset;
632981 rawSeqStore->size++;
632982 }
632983
632984 /* Insert the current entry into the hash table --- it must be
632985 * done after the previous block to avoid clobbering bestEntry */
632986 ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
632987
632988 anchor = split + forwardMatchLength;
632989
632990 /* If we find a match that ends after the data that we've hashed
632991 * then we have a repeating, overlapping, pattern. E.g. all zeros.
632992 * If one repetition of the pattern matches our `stopMask` then all
632993 * repetitions will. We don't need to insert them all into out table,
632994 * only the first one. So skip over overlapping matches.
632995 * This is a major speed boost (20x) for compressing a single byte
632996 * repeated, when that byte ends up in the table.
632997 */
632998 if (anchor > ip + hashed) {
632999 ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
633000 /* Continue the outer loop at anchor (ip + hashed == anchor). */
633001 ip = anchor - hashed;
633002 break;
633003 }
static ldmEntry_t * ZSTD_ldm_getBucket(ldmState_t *ldmState, size_t hash, ldmParams_t const ldmParams)
Definition duckdb.cpp:632678
MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
Definition duckdb.cpp:618469
static size_t ZSTD_ldm_countBackwardsMatch_2segments(const BYTE *pIn, const BYTE *pAnchor, const BYTE *pMatch, const BYTE *pMatchBase, const BYTE *pExtDictStart, const BYTE *pExtDictEnd)
Definition duckdb.cpp:632720
static void ZSTD_ldm_gear_reset(ldmRollingHashState_t *state, BYTE const *data, size_t minMatchLength)
Definition duckdb.cpp:632571
Definition duckdb.cpp:617787

◆ ZSTD_ldm_reduceTable()

void duckdb_zstd::ZSTD_ldm_reduceTable ( ldmEntry_t *const table,
U32 const size,
U32 const reducerValue )
static

ZSTD_ldm_reduceTable() : reduce table indexes by reducerValue

◆ maybeSplitSequence()

rawSeq duckdb_zstd::maybeSplitSequence ( rawSeqStore_t * rawSeqStore,
U32 const remaining,
U32 const minMatch )
static

If the sequence length is longer than remaining then the sequence is split between this block and the next.

Returns the current sequence to handle, or if the rest of the block should be literals, it returns a sequence with offset == 0.

633140{
633141 rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
633142 assert(sequence.offset > 0);
633143 /* Likely: No partial sequence */
633144 if (remaining >= sequence.litLength + sequence.matchLength) {
633145 rawSeqStore->pos++;
633146 return sequence;
633147 }
633148 /* Cut the sequence short (offset == 0 ==> rest is literals). */
633149 if (remaining <= sequence.litLength) {
633150 sequence.offset = 0;
633151 } else if (remaining < sequence.litLength + sequence.matchLength) {
633152 sequence.matchLength = remaining - sequence.litLength;
633153 if (sequence.matchLength < minMatch) {
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_bitWeight()

MEM_STATIC U32 duckdb_zstd::ZSTD_bitWeight ( U32 stat)
633296 : ZSTD_bitWeight(stat))
633297#endif

◆ ZSTD_fracWeight()

MEM_STATIC U32 duckdb_zstd::ZSTD_fracWeight ( U32 rawStat)
633302{
633303 return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);
633304}
633305
633306/* ZSTD_fracWeight() :
633307 * provide fractional-bit "cost" of a stat,
633308 * using linear interpolation approximation */
633309MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)
633310{
633311 U32 const stat = rawStat + 1;
633312 U32 const hb = ZSTD_highbit32(stat);
633313 U32 const BWeight = hb * BITCOST_MULTIPLIER;
633314 /* Fweight was meant for "Fractional weight"

◆ ZSTD_compressedLiterals()

int duckdb_zstd::ZSTD_compressedLiterals ( optState_t const *const optPtr)
static
633328{
633329 return (double)price / (BITCOST_MULTIPLIER*8);

◆ ZSTD_setBasePrices()

void duckdb_zstd::ZSTD_setBasePrices ( optState_t * optPtr,
int optLevel )
static
633334{
633335 return optPtr->literalCompressionMode != ZSTD_ps_disable;
633336}
633337
633338static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)

◆ sum_u32()

U32 duckdb_zstd::sum_u32 ( const unsigned table[],
size_t nbElts )
static
633349{

◆ ZSTD_downscaleStats()

U32 duckdb_zstd::ZSTD_downscaleStats ( unsigned * table,
U32 lastEltIndex,
U32 shift,
base_directive_e base1 )
static
633358 { base_0possible=0, base_1guaranteed=1 } base_directive_e;
633359
633360static U32
633361ZSTD_downscaleStats(unsigned* table, U32 lastEltIndex, U32 shift, base_directive_e base1)
633362{
633363 U32 s, sum=0;
633364 DEBUGLOG(5, "ZSTD_downscaleStats (nbElts=%u, shift=%u)",
633365 (unsigned)lastEltIndex+1, (unsigned)shift );
633366 assert(shift < 30);
633367 for (s=0; s<lastEltIndex+1; s++) {
Scalar sum(InputArray src)

◆ ZSTD_scaleStats()

U32 duckdb_zstd::ZSTD_scaleStats ( unsigned * table,
U32 lastEltIndex,
U32 logTarget )
static
633380{

◆ ZSTD_rescaleFreqs()

void duckdb_zstd::ZSTD_rescaleFreqs ( optState_t *const optPtr,
const BYTE *const src,
size_t const srcSize,
int const optLevel )
static
633390 : init statistics
633391 * take hints from dictionary if there is one
633392 * and init from zero if there is none,
633393 * using src for literals stats, and baseline stats for sequence symbols
633394 * otherwise downscale existing stats, to be used as seed for next block.
633395 */
633396static void
633397ZSTD_rescaleFreqs(optState_t* const optPtr,
633398 const BYTE* const src, size_t const srcSize,
633399 int const optLevel)
633400{
633401 int const compressedLiterals = ZSTD_compressedLiterals(optPtr);
633402 DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);
633403 optPtr->priceType = zop_dynamic;
633404
633405 if (optPtr->litLengthSum == 0) { /* no literals stats collected -> first block assumed -> init */
633406
633407 /* heuristic: use pre-defined stats for too small inputs */
633408 if (srcSize <= ZSTD_PREDEF_THRESHOLD) {
633409 DEBUGLOG(5, "srcSize <= %i : use predefined stats", ZSTD_PREDEF_THRESHOLD);
633410 optPtr->priceType = zop_predef;
633411 }
633412
633413 assert(optPtr->symbolCosts != NULL);
633414 if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {
633415
633416 /* huffman stats covering the full value set : table presumed generated by dictionary */
633417 optPtr->priceType = zop_dynamic;
633418
633419 if (compressedLiterals) {
633420 /* generate literals statistics from huffman table */
633421 unsigned lit;
633422 assert(optPtr->litFreq != NULL);
633423 optPtr->litSum = 0;
633424 for (lit=0; lit<=MaxLit; lit++) {
633425 U32 const scaleLog = 11; /* scale to 2K */
633426 U32 const bitCost = HUF_getNbBitsFromCTable(optPtr->symbolCosts->huf.CTable, lit);
633427 assert(bitCost <= scaleLog);
633428 optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
633429 optPtr->litSum += optPtr->litFreq[lit];
633430 } }
633431
633432 { unsigned ll;
633433 FSE_CState_t llstate;
633434 FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);
633435 optPtr->litLengthSum = 0;
633436 for (ll=0; ll<=MaxLL; ll++) {
633437 U32 const scaleLog = 10; /* scale to 1K */
633438 U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);
633439 assert(bitCost < scaleLog);
633440 optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
633441 optPtr->litLengthSum += optPtr->litLengthFreq[ll];
633442 } }
633443
633444 { unsigned ml;
633445 FSE_CState_t mlstate;
633446 FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);
633447 optPtr->matchLengthSum = 0;
633448 for (ml=0; ml<=MaxML; ml++) {
633449 U32 const scaleLog = 10;
633450 U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);
633451 assert(bitCost < scaleLog);
633452 optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
633453 optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];
633454 } }
633455
633456 { unsigned of;
633457 FSE_CState_t ofstate;
633458 FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);
633459 optPtr->offCodeSum = 0;
633460 for (of=0; of<=MaxOff; of++) {
633461 U32 const scaleLog = 10;
633462 U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);
633463 assert(bitCost < scaleLog);
633464 optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
633465 optPtr->offCodeSum += optPtr->offCodeFreq[of];
633466 } }
633467
633468 } else { /* first block, no dictionary */
633469
633470 assert(optPtr->litFreq != NULL);
633471 if (compressedLiterals) {
633472 /* base initial cost of literals on direct frequency within src */
633473 unsigned lit = MaxLit;
633474 HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */
633475 optPtr->litSum = ZSTD_downscaleStats(optPtr->litFreq, MaxLit, 8, base_0possible);
633476 }
633477
633478 { unsigned const baseLLfreqs[MaxLL+1] = {
633479 4, 2, 1, 1, 1, 1, 1, 1,
633480 1, 1, 1, 1, 1, 1, 1, 1,
633481 1, 1, 1, 1, 1, 1, 1, 1,
633482 1, 1, 1, 1, 1, 1, 1, 1,
633483 1, 1, 1, 1
633484 };
633485 ZSTD_memcpy(optPtr->litLengthFreq, baseLLfreqs, sizeof(baseLLfreqs));
633486 optPtr->litLengthSum = sum_u32(baseLLfreqs, MaxLL+1);
633487 }
633488
633489 { unsigned ml;
633490 for (ml=0; ml<=MaxML; ml++)
633491 optPtr->matchLengthFreq[ml] = 1;
633492 }
633493 optPtr->matchLengthSum = MaxML+1;
633494
633495 { unsigned const baseOFCfreqs[MaxOff+1] = {
633496 6, 2, 1, 1, 2, 3, 4, 4,
633497 4, 3, 2, 1, 1, 1, 1, 1,
633498 1, 1, 1, 1, 1, 1, 1, 1,
633499 1, 1, 1, 1, 1, 1, 1, 1
633500 };
633501 ZSTD_memcpy(optPtr->offCodeFreq, baseOFCfreqs, sizeof(baseOFCfreqs));
633502 optPtr->offCodeSum = sum_u32(baseOFCfreqs, MaxOff+1);
633503 }
633504
633505 }
633506
633507 } else { /* new block : scale down accumulated statistics */
633508
633509 if (compressedLiterals)
633510 optPtr->litSum = ZSTD_scaleStats(optPtr->litFreq, MaxLit, 12);
static softfloat zero()
none
U32 HUF_getNbBitsFromCTable(const HUF_CElt *symbolTable, U32 symbolValue)
Definition duckdb.cpp:615613
Definition duckdb.cpp:617686

◆ ZSTD_rawLiteralsCost()

U32 duckdb_zstd::ZSTD_rawLiteralsCost ( const BYTE *const literals,
U32 const litLength,
const optState_t *const optPtr,
int optLevel )
static
633525{
633526 DEBUGLOG(8, "ZSTD_rawLiteralsCost (%u literals)", litLength);
633527 if (litLength == 0) return 0;
633528
633529 if (!ZSTD_compressedLiterals(optPtr))
633530 return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */
633531
633532 if (optPtr->priceType == zop_predef)
633533 return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */
633534
633535 /* dynamic statistics */
633536 { U32 price = optPtr->litSumBasePrice * litLength;
633537 U32 const litPriceMax = optPtr->litSumBasePrice - BITCOST_MULTIPLIER;
633538 U32 u;
633539 assert(optPtr->litSumBasePrice >= BITCOST_MULTIPLIER);
633540 for (u=0; u < litLength; u++) {

◆ ZSTD_litLengthPrice()

U32 duckdb_zstd::ZSTD_litLengthPrice ( U32 const litLength,
const optState_t *const optPtr,
int optLevel )
static
633552{
633553 assert(litLength <= ZSTD_BLOCKSIZE_MAX);
633554 if (optPtr->priceType == zop_predef)
633555 return WEIGHT(litLength, optLevel);
633556
633557 /* ZSTD_LLcode() can't compute litLength price for sizes >= ZSTD_BLOCKSIZE_MAX
633558 * because it isn't representable in the zstd format.
633559 * So instead just pretend it would cost 1 bit more than ZSTD_BLOCKSIZE_MAX - 1.
633560 * In such a case, the block would be all literals.
633561 */
633562 if (litLength == ZSTD_BLOCKSIZE_MAX)
633563 return BITCOST_MULTIPLIER + ZSTD_litLengthPrice(ZSTD_BLOCKSIZE_MAX - 1, optPtr, optLevel);
633564

◆ ZSTD_getMatchPrice()

FORCE_INLINE_TEMPLATE U32 duckdb_zstd::ZSTD_getMatchPrice ( U32 const offBase,
U32 const matchLength,
const optState_t *const optPtr,
int const optLevel )
633584{
633585 U32 price;
633586 U32 const offCode = ZSTD_highbit32(offBase);
633587 U32 const mlBase = matchLength - MINMATCH;
633588 assert(matchLength >= MINMATCH);
633589
633590 if (optPtr->priceType == zop_predef) /* fixed scheme, does not use statistics */
633591 return WEIGHT(mlBase, optLevel)
633592 + ((16 + offCode) * BITCOST_MULTIPLIER); /* emulated offset cost */
633593
633594 /* dynamic statistics */
633595 price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));
633596 if ((optLevel<2) /*static*/ && offCode >= 20)
633597 price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */
633598
633599 /* match Length */
633600 { U32 const mlCode = ZSTD_MLcode(mlBase);
633601 price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));

◆ ZSTD_updateStats()

void duckdb_zstd::ZSTD_updateStats ( optState_t *const optPtr,
U32 litLength,
const BYTE * literals,
U32 offBase,
U32 matchLength )
static
633606 :%u) = %u", matchLength, price);
633607 return price;
633608}
633609
633610/* ZSTD_updateStats() :
633611 * assumption : literals + litLength <= iend */
633612static void ZSTD_updateStats(optState_t* const optPtr,
633613 U32 litLength, const BYTE* literals,
633614 U32 offBase, U32 matchLength)
633615{
633616 /* literals */
633617 if (ZSTD_compressedLiterals(optPtr)) {
633618 U32 u;
633619 for (u=0; u < litLength; u++)
633620 optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;
633621 optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;
633622 }
633623
633624 /* literal Length */
633625 { U32 const llCode = ZSTD_LLcode(litLength);
633626 optPtr->litLengthFreq[llCode]++;
633627 optPtr->litLengthSum++;
633628 }
633629
633630 /* offset code : follows storeSeq() numeric representation */
633631 { U32 const offCode = ZSTD_highbit32(offBase);
633632 assert(offCode <= MaxOff);
633633 optPtr->offCodeFreq[offCode]++;
633634 optPtr->offCodeSum++;
633635 }
633636

◆ ZSTD_readMINMATCH()

MEM_STATIC U32 duckdb_zstd::ZSTD_readMINMATCH ( const void * memPtr,
U32 length )
633650{
633651 switch (length)
633652 {
633653 default :

◆ ZSTD_insertAndFindFirstIndexHash3()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_insertAndFindFirstIndexHash3 ( const ZSTD_matchState_t * ms,
U32 * nextToUpdate3,
const BYTE *const ip )
static
633670{
633671 U32* const hashTable3 = ms->hashTable3;
633672 U32 const hashLog3 = ms->hashLog3;
633673 const BYTE* const base = ms->window.base;
633674 U32 idx = *nextToUpdate3;
633675 U32 const target = (U32)(ip - base);
633676 size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);
633677 assert(hashLog3 > 0);
633678
633679 while(idx < target) {

◆ ZSTD_insertBt1()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_insertBt1 ( const ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iend,
U32 const target,
U32 const mls,
const int extDict )
static

ZSTD_insertBt1() : add one or multiple positions to tree.

Parameters
ipassumed <= iend-8 .
targetThe target of ZSTD_updateTree_internal() - we are filling to this position
Returns
: nb of positions added
633703{
633704 const ZSTD_compressionParameters* const cParams = &ms->cParams;
633705 U32* const hashTable = ms->hashTable;
633706 U32 const hashLog = cParams->hashLog;
633707 size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
633708 U32* const bt = ms->chainTable;
633709 U32 const btLog = cParams->chainLog - 1;
633710 U32 const btMask = (1 << btLog) - 1;
633711 U32 matchIndex = hashTable[h];
633712 size_t commonLengthSmaller=0, commonLengthLarger=0;
633713 const BYTE* const base = ms->window.base;
633714 const BYTE* const dictBase = ms->window.dictBase;
633715 const U32 dictLimit = ms->window.dictLimit;
633716 const BYTE* const dictEnd = dictBase + dictLimit;
633717 const BYTE* const prefixStart = base + dictLimit;
633718 const BYTE* match;
633719 const U32 curr = (U32)(ip-base);
633720 const U32 btLow = btMask >= curr ? 0 : curr - btMask;
633721 U32* smallerPtr = bt + 2*(curr&btMask);
633722 U32* largerPtr = smallerPtr + 1;
633723 U32 dummy32; /* to be nullified at the end */
633724 /* windowLow is based on target because
633725 * we only need positions that will be in the window at the end of the tree update.
633726 */
633727 U32 const windowLow = ZSTD_getLowestMatchIndex(ms, target, cParams->windowLog);
633728 U32 matchEndIdx = curr+8+1;
633729 size_t bestLength = 8;
633730 U32 nbCompares = 1U << cParams->searchLog;
633731#ifdef ZSTD_C_PREDICT
633732 U32 predictedSmall = *(bt + 2*((curr-1)&btMask) + 0);
633733 U32 predictedLarge = *(bt + 2*((curr-1)&btMask) + 1);
633734 predictedSmall += (predictedSmall>0);
633735 predictedLarge += (predictedLarge>0);
633736#endif /* ZSTD_C_PREDICT */
633737
633738 DEBUGLOG(8, "ZSTD_insertBt1 (%u)", curr);
633739
633740 assert(curr <= target);
633741 assert(ip <= iend-8); /* required for h calculation */
633742 hashTable[h] = curr; /* Update Hash Table */
633743
633744 assert(windowLow > 0);
633745 for (; nbCompares && (matchIndex >= windowLow); --nbCompares) {
633746 U32* const nextPtr = bt + 2*(matchIndex & btMask);
633747 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
633748 assert(matchIndex < curr);
633749
633750#ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */
633751 const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */
633752 if (matchIndex == predictedSmall) {
633753 /* no need to check length, result known */
633754 *smallerPtr = matchIndex;
633755 if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
633756 smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
633757 matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
633758 predictedSmall = predictPtr[1] + (predictPtr[1]>0);
633759 continue;
633760 }
633761 if (matchIndex == predictedLarge) {
633762 *largerPtr = matchIndex;
633763 if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
633764 largerPtr = nextPtr;
633765 matchIndex = nextPtr[0];
633766 predictedLarge = predictPtr[0] + (predictPtr[0]>0);
633767 continue;
633768 }
633769#endif
633770
633771 if (!extDict || (matchIndex+matchLength >= dictLimit)) {
633772 assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */
633773 match = base + matchIndex;
633774 matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
633775 } else {
633776 match = dictBase + matchIndex;
633777 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
633778 if (matchIndex+matchLength >= dictLimit)
633779 match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
633780 }
633781
633782 if (matchLength > bestLength) {
633783 bestLength = matchLength;
633784 if (matchLength > matchEndIdx - matchIndex)
633785 matchEndIdx = matchIndex + (U32)matchLength;
633786 }
633787
633788 if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
633789 break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
633790 }
633791
633792 if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
633793 /* match is smaller than current */
633794 *smallerPtr = matchIndex; /* update smaller idx */
633795 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
633796 if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
633797 smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
633798 matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
633799 } else {
633800 /* match is larger than current */
633801 *largerPtr = matchIndex;
633802 commonLengthLarger = matchLength;
633803 if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
633804 largerPtr = nextPtr;
633805 matchIndex = nextPtr[0];
633806 } }
633807
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_updateTree_internal()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_updateTree_internal ( ZSTD_matchState_t * ms,
const BYTE *const ip,
const BYTE *const iend,
const U32 mls,
const ZSTD_dictMode_e dictMode )
633822{
633823 const BYTE* const base = ms->window.base;
633824 U32 const target = (U32)(ip - base);
633825 U32 idx = ms->nextToUpdate;
633826 DEBUGLOG(7, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",
633827 idx, target, dictMode);
633828
633829 while(idx < target) {
633830 U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, target, mls, dictMode == ZSTD_extDict);
static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertBt1(const ZSTD_matchState_t *ms, const BYTE *const ip, const BYTE *const iend, U32 const target, U32 const mls, const int extDict)
Definition duckdb.cpp:633691

◆ ZSTD_insertBtAndGetAllMatches()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_insertBtAndGetAllMatches ( ZSTD_match_t * matches,
ZSTD_matchState_t * ms,
U32 * nextToUpdate3,
const BYTE *const ip,
const BYTE *const iLimit,
const ZSTD_dictMode_e dictMode,
const U32 rep[ZSTD_REP_NUM],
const U32 ll0,
const U32 lengthToBeat,
const U32 mls )
633839 {
633840 ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
633841}
633842
633845U32
633846ZSTD_insertBtAndGetAllMatches (
633847 ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */
633848 ZSTD_matchState_t* ms,
633849 U32* nextToUpdate3,
633850 const BYTE* const ip, const BYTE* const iLimit,
633851 const ZSTD_dictMode_e dictMode,
633852 const U32 rep[ZSTD_REP_NUM],
633853 const U32 ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */
633854 const U32 lengthToBeat,
633855 const U32 mls /* template */)
633856{
633857 const ZSTD_compressionParameters* const cParams = &ms->cParams;
633858 U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
633859 const BYTE* const base = ms->window.base;
633860 U32 const curr = (U32)(ip-base);
633861 U32 const hashLog = cParams->hashLog;
633862 U32 const minMatch = (mls==3) ? 3 : 4;
633863 U32* const hashTable = ms->hashTable;
633864 size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
633865 U32 matchIndex = hashTable[h];
633866 U32* const bt = ms->chainTable;
633867 U32 const btLog = cParams->chainLog - 1;
633868 U32 const btMask= (1U << btLog) - 1;
633869 size_t commonLengthSmaller=0, commonLengthLarger=0;
633870 const BYTE* const dictBase = ms->window.dictBase;
633871 U32 const dictLimit = ms->window.dictLimit;
633872 const BYTE* const dictEnd = dictBase + dictLimit;
633873 const BYTE* const prefixStart = base + dictLimit;
633874 U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;
633875 U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
633876 U32 const matchLow = windowLow ? windowLow : 1;
633877 U32* smallerPtr = bt + 2*(curr&btMask);
633878 U32* largerPtr = bt + 2*(curr&btMask) + 1;
633879 U32 matchEndIdx = curr+8+1; /* farthest referenced position of any match => detects repetitive patterns */
633880 U32 dummy32; /* to be nullified at the end */
633881 U32 mnum = 0;
633882 U32 nbCompares = 1U << cParams->searchLog;
633883
633884 const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;
633885 const ZSTD_compressionParameters* const dmsCParams =
633886 dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;
633887 const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;
633888 const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;
633889 U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;
633890 U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;
633891 U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;
633892 U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;
633893 U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;
633894 U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;
633895 U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;
633896
633897 size_t bestLength = lengthToBeat-1;
633898 DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", curr);
633899
633900 /* check repCode */
633901 assert(ll0 <= 1); /* necessarily 1 or 0 */
633902 { U32 const lastR = ZSTD_REP_NUM + ll0;
633903 U32 repCode;
633904 for (repCode = ll0; repCode < lastR; repCode++) {
633905 U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
633906 U32 const repIndex = curr - repOffset;
633907 U32 repLen = 0;
633908 assert(curr >= dictLimit);
633909 if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < curr-dictLimit) { /* equivalent to `curr > repIndex >= dictLimit` */
633910 /* We must validate the repcode offset because when we're using a dictionary the
633911 * valid offset range shrinks when the dictionary goes out of bounds.
633912 */
633913 if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {
633914 repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;
633915 }
633916 } else { /* repIndex < dictLimit || repIndex >= curr */
633917 const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?
633918 dmsBase + repIndex - dmsIndexDelta :
633919 dictBase + repIndex;
633920 assert(curr >= windowLow);
633921 if ( dictMode == ZSTD_extDict
633922 && ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow) /* equivalent to `curr > repIndex >= windowLow` */
633923 & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)
633924 && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
633925 repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;
633926 }
633927 if (dictMode == ZSTD_dictMatchState
633928 && ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `curr > repIndex >= dmsLowLimit` */
633929 & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */
633930 && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
633931 repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;
633932 } }
633933 /* save longer solution */
633934 if (repLen > bestLength) {
633935 DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",
633936 repCode, ll0, repOffset, repLen);
633937 bestLength = repLen;
633938 matches[mnum].off = REPCODE_TO_OFFBASE(repCode - ll0 + 1); /* expect value between 1 and 3 */
633939 matches[mnum].len = (U32)repLen;
633940 mnum++;
633941 if ( (repLen > sufficient_len)
633942 | (ip+repLen == iLimit) ) { /* best possible */
633943 return mnum;
633944 } } } }
633945
633946 /* HC3 match finder */
633947 if ((mls == 3) /*static*/ && (bestLength < mls)) {
633948 U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);
633949 if ((matchIndex3 >= matchLow)
633950 & (curr - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {
633951 size_t mlen;
633952 if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {
633953 const BYTE* const match = base + matchIndex3;
633954 mlen = ZSTD_count(ip, match, iLimit);
633955 } else {
633956 const BYTE* const match = dictBase + matchIndex3;
633957 mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);
633958 }
633959
633960 /* save best solution */
633961 if (mlen >= mls /* == 3 > bestLength */) {
633962 DEBUGLOG(8, "found small match with hlog3, of length %u",
633963 (U32)mlen);
633964 bestLength = mlen;
633965 assert(curr > matchIndex3);
633966 assert(mnum==0); /* no prior solution */
633967 matches[0].off = OFFSET_TO_OFFBASE(curr - matchIndex3);
633968 matches[0].len = (U32)mlen;
633969 mnum = 1;
633970 if ( (mlen > sufficient_len) |
633971 (ip+mlen == iLimit) ) { /* best possible length */
633972 ms->nextToUpdate = curr+1; /* skip insertion */
633973 return 1;
633974 } } }
633975 /* no dictMatchState lookup: dicts don't have a populated HC3 table */
633976 } /* if (mls == 3) */
633977
633978 hashTable[h] = curr; /* Update Hash Table */
633979
633980 for (; nbCompares && (matchIndex >= matchLow); --nbCompares) {
633981 U32* const nextPtr = bt + 2*(matchIndex & btMask);
633982 const BYTE* match;
633983 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
633984 assert(curr > matchIndex);
633985
633986 if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {
633987 assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */
633988 match = base + matchIndex;
633989 if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */
633990 matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);
633991 } else {
633992 match = dictBase + matchIndex;
633993 assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */
633994 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);
633995 if (matchIndex+matchLength >= dictLimit)
633996 match = base + matchIndex; /* prepare for match[matchLength] read */
633997 }
633998
633999 if (matchLength > bestLength) {
634000 DEBUGLOG(8, "found match of length %u at distance %u (offBase=%u)",
634001 (U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));
634002 assert(matchEndIdx > matchIndex);
634003 if (matchLength > matchEndIdx - matchIndex)
634004 matchEndIdx = matchIndex + (U32)matchLength;
634005 bestLength = matchLength;
634006 matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);
634007 matches[mnum].len = (U32)matchLength;
634008 mnum++;
634009 if ( (matchLength > ZSTD_OPT_NUM)
634010 | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
634011 if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */
634012 break; /* drop, to preserve bt consistency (miss a little bit of compression) */
634013 } }
634014
634015 if (match[matchLength] < ip[matchLength]) {
634016 /* match smaller than current */
634017 *smallerPtr = matchIndex; /* update smaller idx */
634018 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
634019 if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
634020 smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */
634021 matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */
634022 } else {
634023 *largerPtr = matchIndex;
634024 commonLengthLarger = matchLength;
634025 if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
634026 largerPtr = nextPtr;
634027 matchIndex = nextPtr[0];
634028 } }
634029
634030 *smallerPtr = *largerPtr = 0;
634031
634032 assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
634033 if (dictMode == ZSTD_dictMatchState && nbCompares) {
634034 size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);
634035 U32 dictMatchIndex = dms->hashTable[dmsH];
634036 const U32* const dmsBt = dms->chainTable;
634037 commonLengthSmaller = commonLengthLarger = 0;
634038 for (; nbCompares && (dictMatchIndex > dmsLowLimit); --nbCompares) {
634039 const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);
634040 size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
634041 const BYTE* match = dmsBase + dictMatchIndex;
634042 matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);
634043 if (dictMatchIndex+matchLength >= dmsHighLimit)
634044 match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */
634045
634046 if (matchLength > bestLength) {
634047 matchIndex = dictMatchIndex + dmsIndexDelta;
634048 DEBUGLOG(8, "found dms match of length %u at distance %u (offBase=%u)",
634049 (U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));
634050 if (matchLength > matchEndIdx - matchIndex)
634051 matchEndIdx = matchIndex + (U32)matchLength;
634052 bestLength = matchLength;
634053 matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);
634054 matches[mnum].len = (U32)matchLength;
634055 mnum++;
634056 if ( (matchLength > ZSTD_OPT_NUM)
634057 | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
634058 break; /* drop, to guarantee consistency (miss a little bit of compression) */
634059 } }
634060
634061 if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */
634062 if (match[matchLength] < ip[matchLength]) {
634063 commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
634064 dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
634065 } else {
634066 /* match is larger than current */
634067 commonLengthLarger = matchLength;

◆ ZSTD_btGetAllMatches_internal()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 duckdb_zstd::ZSTD_btGetAllMatches_internal ( ZSTD_match_t * matches,
ZSTD_matchState_t * ms,
U32 * nextToUpdate3,
const BYTE * ip,
const BYTE *const iHighLimit,
const U32 rep[ZSTD_REP_NUM],
U32 const ll0,
U32 const lengthToBeat,
const ZSTD_dictMode_e dictMode,
const U32 mls )
634099{

◆ ZSTD_selectBtGetAllMatches()

ZSTD_getAllMatchesFn duckdb_zstd::ZSTD_selectBtGetAllMatches ( ZSTD_matchState_t const * ms,
ZSTD_dictMode_e const dictMode )
static
634146{
634147 ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = {
634148 ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict),
634149 ZSTD_BT_GET_ALL_MATCHES_ARRAY(extDict),

◆ ZSTD_optLdm_skipRawSeqStoreBytes()

void duckdb_zstd::ZSTD_optLdm_skipRawSeqStoreBytes ( rawSeqStore_t * rawSeqStore,
size_t nbBytes )
static
634175{
634176 U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
634177 while (currPos && rawSeqStore->pos < rawSeqStore->size) {
634178 rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
634179 if (currPos >= currSeq.litLength + currSeq.matchLength) {
634180 currPos -= currSeq.litLength + currSeq.matchLength;
634181 rawSeqStore->pos++;
634182 } else {
634183 rawSeqStore->posInSequence = currPos;

◆ ZSTD_opt_getNextMatchAndUpdateSeqStore()

void duckdb_zstd::ZSTD_opt_getNextMatchAndUpdateSeqStore ( ZSTD_optLdm_t * optLdm,
U32 currPosInBlock,
U32 blockBytesRemaining )
static
634199{
634200 rawSeq currSeq;
634201 U32 currBlockEndPos;
634202 U32 literalsBytesRemaining;
634203 U32 matchBytesRemaining;
634204
634205 /* Setting match end position to MAX to ensure we never use an LDM during this block */
634206 if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
634207 optLdm->startPosInBlock = UINT_MAX;
634208 optLdm->endPosInBlock = UINT_MAX;
634209 return;
634210 }
634211 /* Calculate appropriate bytes left in matchLength and litLength
634212 * after adjusting based on ldmSeqStore->posInSequence */
634213 currSeq = optLdm->seqStore.seq[optLdm->seqStore.pos];
634214 assert(optLdm->seqStore.posInSequence <= currSeq.litLength + currSeq.matchLength);
634215 currBlockEndPos = currPosInBlock + blockBytesRemaining;
634216 literalsBytesRemaining = (optLdm->seqStore.posInSequence < currSeq.litLength) ?
634217 currSeq.litLength - (U32)optLdm->seqStore.posInSequence :
634218 0;
634219 matchBytesRemaining = (literalsBytesRemaining == 0) ?
634220 currSeq.matchLength - ((U32)optLdm->seqStore.posInSequence - currSeq.litLength) :
634221 currSeq.matchLength;
634222
634223 /* If there are more literal bytes than bytes remaining in block, no ldm is possible */
634224 if (literalsBytesRemaining >= blockBytesRemaining) {
634225 optLdm->startPosInBlock = UINT_MAX;
634226 optLdm->endPosInBlock = UINT_MAX;
634227 ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, blockBytesRemaining);
634228 return;
634229 }
634230
634231 /* Matches may be < MINMATCH by this process. In that case, we will reject them
634232 when we are deciding whether or not to add the ldm */
634233 optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining;
634234 optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining;
634235 optLdm->offset = currSeq.offset;
634236
634237 if (optLdm->endPosInBlock > currBlockEndPos) {
634238 /* Match ends after the block ends, we can't use the whole match */

◆ ZSTD_optLdm_maybeAddMatch()

void duckdb_zstd::ZSTD_optLdm_maybeAddMatch ( ZSTD_match_t * matches,
U32 * nbMatches,
const ZSTD_optLdm_t * optLdm,
U32 currPosInBlock )
static
634254{
634255 U32 const posDiff = currPosInBlock - optLdm->startPosInBlock;
634256 /* Note: ZSTD_match_t actually contains offBase and matchLength (before subtracting MINMATCH) */
634257 U32 const candidateMatchLength = optLdm->endPosInBlock - optLdm->startPosInBlock - posDiff;
634258
634259 /* Ensure that current block position is not outside of the match */
634260 if (currPosInBlock < optLdm->startPosInBlock
634261 || currPosInBlock >= optLdm->endPosInBlock
634262 || candidateMatchLength < MINMATCH) {
634263 return;
634264 }
634265
634266 if (*nbMatches == 0 || ((candidateMatchLength > matches[*nbMatches-1].len) && *nbMatches < ZSTD_OPT_NUM)) {
634267 U32 const candidateOffBase = OFFSET_TO_OFFBASE(optLdm->offset);

◆ ZSTD_optLdm_processMatchCandidate()

void duckdb_zstd::ZSTD_optLdm_processMatchCandidate ( ZSTD_optLdm_t * optLdm,
ZSTD_match_t * matches,
U32 * nbMatches,
U32 currPosInBlock,
U32 remainingBytes )
static
634283{
634284 if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
634285 return;
634286 }
634287
634288 if (currPosInBlock >= optLdm->endPosInBlock) {
634289 if (currPosInBlock > optLdm->endPosInBlock) {
634290 /* The position at which ZSTD_optLdm_processMatchCandidate() is called is not necessarily
634291 * at the end of a match from the ldm seq store, and will often be some bytes
634292 * over beyond matchEndPosInBlock. As such, we need to correct for these "overshoots"
634293 */

◆ ZSTD_compressBlock_opt_generic()

FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_compressBlock_opt_generic ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize,
const int optLevel,
const ZSTD_dictMode_e dictMode )
634337{
634338 optState_t* const optStatePtr = &ms->opt;
634339 const BYTE* const istart = (const BYTE*)src;
634340 const BYTE* ip = istart;
634341 const BYTE* anchor = istart;
634342 const BYTE* const iend = istart + srcSize;
634343 const BYTE* const ilimit = iend - 8;
634344 const BYTE* const base = ms->window.base;
634345 const BYTE* const prefixStart = base + ms->window.dictLimit;
634346 const ZSTD_compressionParameters* const cParams = &ms->cParams;
634347
634348 ZSTD_getAllMatchesFn getAllMatches = ZSTD_selectBtGetAllMatches(ms, dictMode);
634349
634350 U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
634351 U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;
634352 U32 nextToUpdate3 = ms->nextToUpdate;
634353
634354 ZSTD_optimal_t* const opt = optStatePtr->priceTable;
634355 ZSTD_match_t* const matches = optStatePtr->matchTable;
634356 ZSTD_optimal_t lastStretch;
634357 ZSTD_optLdm_t optLdm;
634358
634359 ZSTD_memset(&lastStretch, 0, sizeof(ZSTD_optimal_t));
634360
634361 optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;
634362 optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;
634363 ZSTD_opt_getNextMatchAndUpdateSeqStore(&optLdm, (U32)(ip-istart), (U32)(iend-ip));
634364
634365 /* init */
634366 DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",
634367 (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);
634368 assert(optLevel <= 2);
634369 ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);
634370 ip += (ip==prefixStart);
634371
634372 /* Match Loop */
634373 while (ip < ilimit) {
634374 U32 cur, last_pos = 0;
634375
634376 /* find first match */
634377 { U32 const litlen = (U32)(ip - anchor);
634378 U32 const ll0 = !litlen;
634379 U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);
634380 ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
634381 (U32)(ip-istart), (U32)(iend-ip));
634382 if (!nbMatches) {
634383 DEBUGLOG(8, "no match found at cPos %u", (unsigned)(ip-istart));
634384 ip++;
634385 continue;
634386 }
634387
634388 /* Match found: let's store this solution, and eventually find more candidates.
634389 * During this forward pass, @opt is used to store stretches,
634390 * defined as "a match followed by N literals".
634391 * Note how this is different from a Sequence, which is "N literals followed by a match".
634392 * Storing stretches allows us to store different match predecessors
634393 * for each literal position part of a literals run. */
634394
634395 /* initialize opt[0] */
634396 opt[0].mlen = 0; /* there are only literals so far */
634397 opt[0].litlen = litlen;
634398 /* No need to include the actual price of the literals before the first match
634399 * because it is static for the duration of the forward pass, and is included
634400 * in every subsequent price. But, we include the literal length because
634401 * the cost variation of litlen depends on the value of litlen.
634402 */
634403 opt[0].price = LL_PRICE(litlen);
634404 ZSTD_STATIC_ASSERT(sizeof(opt[0].rep[0]) == sizeof(rep[0]));
634405 ZSTD_memcpy(&opt[0].rep, rep, sizeof(opt[0].rep));
634406
634407 /* large match -> immediate encoding */
634408 { U32 const maxML = matches[nbMatches-1].len;
634409 U32 const maxOffBase = matches[nbMatches-1].off;
634410 DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffBase=%u at cPos=%u => start new series",
634411 nbMatches, maxML, maxOffBase, (U32)(ip-prefixStart));
634412
634413 if (maxML > sufficient_len) {
634414 lastStretch.litlen = 0;
634415 lastStretch.mlen = maxML;
634416 lastStretch.off = maxOffBase;
634417 DEBUGLOG(6, "large match (%u>%u) => immediate encoding",
634418 maxML, sufficient_len);
634419 cur = 0;
634420 last_pos = maxML;
634421 goto _shortestPath;
634422 } }
634423
634424 /* set prices for first matches starting position == 0 */
634425 assert(opt[0].price >= 0);
634426 { U32 pos;
634427 U32 matchNb;
634428 for (pos = 1; pos < minMatch; pos++) {
634429 opt[pos].price = ZSTD_MAX_PRICE;
634430 opt[pos].mlen = 0;
634431 opt[pos].litlen = litlen + pos;
634432 }
634433 for (matchNb = 0; matchNb < nbMatches; matchNb++) {
634434 U32 const offBase = matches[matchNb].off;
634435 U32 const end = matches[matchNb].len;
634436 for ( ; pos <= end ; pos++ ) {
634437 int const matchPrice = (int)ZSTD_getMatchPrice(offBase, pos, optStatePtr, optLevel);
634438 int const sequencePrice = opt[0].price + matchPrice;
634439 DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
634440 pos, ZSTD_fCost(sequencePrice));
634441 opt[pos].mlen = pos;
634442 opt[pos].off = offBase;
634443 opt[pos].litlen = 0; /* end of match */
634444 opt[pos].price = sequencePrice + LL_PRICE(0);
634445 }
634446 }
634447 last_pos = pos-1;
634448 opt[pos].price = ZSTD_MAX_PRICE;
634449 }
634450 }
634451
634452 /* check further positions */
634453 for (cur = 1; cur <= last_pos; cur++) {
634454 const BYTE* const inr = ip + cur;
634455 assert(cur <= ZSTD_OPT_NUM);
634456 DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur);
634457
634458 /* Fix current position with one literal if cheaper */
634459 { U32 const litlen = opt[cur-1].litlen + 1;
634460 int const price = opt[cur-1].price
634461 + LIT_PRICE(ip+cur-1)
634462 + LL_INCPRICE(litlen);
634463 assert(price < 1000000000); /* overflow check */
634464 if (price <= opt[cur].price) {
634465 ZSTD_optimal_t const prevMatch = opt[cur];
634466 DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
634467 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
634468 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
634469 opt[cur] = opt[cur-1];
634470 opt[cur].litlen = litlen;
634471 opt[cur].price = price;
634472 if ( (optLevel >= 1) /* additional check only for higher modes */
634473 && (prevMatch.litlen == 0) /* replace a match */
634474 && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
634475 && LIKELY(ip + cur < iend)
634476 ) {
634477 /* check next position, in case it would be cheaper */
634478 int with1literal = prevMatch.price + LIT_PRICE(ip+cur) + LL_INCPRICE(1);
634479 int withMoreLiterals = price + LIT_PRICE(ip+cur) + LL_INCPRICE(litlen+1);
634480 DEBUGLOG(7, "then at next rPos %u : match+1lit %.2f vs %ulits %.2f",
634481 cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
634482 if ( (with1literal < withMoreLiterals)
634483 && (with1literal < opt[cur+1].price) ) {
634484 /* update offset history - before it disappears */
634485 U32 const prev = cur - prevMatch.mlen;
634486 repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, prevMatch.off, opt[prev].litlen==0);
634487 assert(cur >= prevMatch.mlen);
634488 DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !",
634489 ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals),
634490 newReps.rep[0], newReps.rep[1], newReps.rep[2] );
634491 opt[cur+1] = prevMatch; /* mlen & offbase */
634492 ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(repcodes_t));
634493 opt[cur+1].litlen = 1;
634494 opt[cur+1].price = with1literal;
634495 if (last_pos < cur+1) last_pos = cur+1;
634496 }
634497 }
634498 } else {
634499 DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f)",
634500 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price));
634501 }
634502 }
634503
634504 /* Offset history is not updated during match comparison.
634505 * Do it here, now that the match is selected and confirmed.
634506 */
634507 ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));
634508 assert(cur >= opt[cur].mlen);
634509 if (opt[cur].litlen == 0) {
634510 /* just finished a match => alter offset history */
634511 U32 const prev = cur - opt[cur].mlen;
634512 repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
634513 ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));
634514 }
634515
634516 /* last match must start at a minimum distance of 8 from oend */
634517 if (inr > ilimit) continue;
634518
634519 if (cur == last_pos) break;
634520
634521 if ( (optLevel==0) /*static_test*/
634522 && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
634523 DEBUGLOG(7, "skip current position : next rPos(%u) price is cheaper", cur+1);
634524 continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
634525 }
634526
634527 assert(opt[cur].price >= 0);
634528 { U32 const ll0 = (opt[cur].litlen == 0);
634529 int const previousPrice = opt[cur].price;
634530 int const basePrice = previousPrice + LL_PRICE(0);
634531 U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);
634532 U32 matchNb;
634533
634534 ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
634535 (U32)(inr-istart), (U32)(iend-inr));
634536
634537 if (!nbMatches) {
634538 DEBUGLOG(7, "rPos:%u : no match found", cur);
634539 continue;
634540 }
634541
634542 { U32 const longestML = matches[nbMatches-1].len;
634543 DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of longest ML=%u",
634544 inr-istart, cur, nbMatches, longestML);
634545
634546 if ( (longestML > sufficient_len)
634547 || (cur + longestML >= ZSTD_OPT_NUM)
634548 || (ip + cur + longestML >= iend) ) {
634549 lastStretch.mlen = longestML;
634550 lastStretch.off = matches[nbMatches-1].off;
634551 lastStretch.litlen = 0;
634552 last_pos = cur + longestML;
634553 goto _shortestPath;
634554 } }
634555
634556 /* set prices using matches found at position == cur */
634557 for (matchNb = 0; matchNb < nbMatches; matchNb++) {
634558 U32 const offset = matches[matchNb].off;
634559 U32 const lastML = matches[matchNb].len;
634560 U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;
634561 U32 mlen;
634562
634563 DEBUGLOG(7, "testing match %u => offBase=%4u, mlen=%2u, llen=%2u",
634564 matchNb, matches[matchNb].off, lastML, opt[cur].litlen);
634565
634566 for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */
634567 U32 const pos = cur + mlen;
634568 int const price = basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
634569
634570 if ((pos > last_pos) || (price < opt[pos].price)) {
634571 DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
634572 pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
634573 while (last_pos < pos) {
634574 /* fill empty positions, for future comparisons */
634575 last_pos++;
634576 opt[last_pos].price = ZSTD_MAX_PRICE;
634577 opt[last_pos].litlen = !0; /* just needs to be != 0, to mean "not an end of match" */
634578 }
634579 opt[pos].mlen = mlen;
634580 opt[pos].off = offset;
634581 opt[pos].litlen = 0;
634582 opt[pos].price = price;
634583 } else {
634584 DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
634585 pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
634586 if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
634587 }
634588 } } }
634589 opt[last_pos+1].price = ZSTD_MAX_PRICE;
634590 } /* for (cur = 1; cur <= last_pos; cur++) */
634591
634592 lastStretch = opt[last_pos];
634593 assert(cur >= lastStretch.mlen);
634594 cur = last_pos - lastStretch.mlen;
634595
634596_shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */
634597 assert(opt[0].mlen == 0);
634598 assert(last_pos >= lastStretch.mlen);
634599 assert(cur == last_pos - lastStretch.mlen);
634600
634601 if (lastStretch.mlen==0) {
634602 /* no solution : all matches have been converted into literals */
634603 assert(lastStretch.litlen == (ip - anchor) + last_pos);
634604 ip += last_pos;
634605 continue;
634606 }
634607 assert(lastStretch.off > 0);
634608
634609 /* Update offset history */
634610 if (lastStretch.litlen == 0) {
634611 /* finishing on a match : update offset history */
634612 repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastStretch.off, opt[cur].litlen==0);
634613 ZSTD_memcpy(rep, &reps, sizeof(repcodes_t));
634614 } else {
634615 ZSTD_memcpy(rep, lastStretch.rep, sizeof(repcodes_t));
634616 assert(cur >= lastStretch.litlen);
634617 cur -= lastStretch.litlen;
634618 }
634619
634620 /* Let's write the shortest path solution.
634621 * It is stored in @opt in reverse order,
634622 * starting from @storeEnd (==cur+2),
634623 * effectively partially @opt overwriting.
634624 * Content is changed too:
634625 * - So far, @opt stored stretches, aka a match followed by literals
634626 * - Now, it will store sequences, aka literals followed by a match
634627 */
634628 { U32 const storeEnd = cur + 2;
634629 U32 storeStart = storeEnd;
634630 U32 stretchPos = cur;
634631
634632 DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
634633 last_pos, cur); (void)last_pos;
634634 assert(storeEnd < ZSTD_OPT_SIZE);
634635 DEBUGLOG(6, "last stretch copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
634636 storeEnd, lastStretch.litlen, lastStretch.mlen, lastStretch.off);
634637 if (lastStretch.litlen > 0) {
634638 /* last "sequence" is unfinished: just a bunch of literals */
634639 opt[storeEnd].litlen = lastStretch.litlen;
634640 opt[storeEnd].mlen = 0;
634641 storeStart = storeEnd-1;
634642 opt[storeStart] = lastStretch;
634643 } {
634644 opt[storeEnd] = lastStretch; /* note: litlen will be fixed */
634645 storeStart = storeEnd;
634646 }
634647 while (1) {
634648 ZSTD_optimal_t nextStretch = opt[stretchPos];
634649 opt[storeStart].litlen = nextStretch.litlen;
634650 DEBUGLOG(6, "selected sequence (llen=%u,mlen=%u,ofc=%u)",
634651 opt[storeStart].litlen, opt[storeStart].mlen, opt[storeStart].off);
634652 if (nextStretch.mlen == 0) {
634653 /* reaching beginning of segment */
634654 break;
634655 }
634656 storeStart--;
634657 opt[storeStart] = nextStretch; /* note: litlen will be fixed */
634658 assert(nextStretch.litlen + nextStretch.mlen <= stretchPos);
634659 stretchPos -= nextStretch.litlen + nextStretch.mlen;
634660 }
634661
634662 /* save sequences */
634663 DEBUGLOG(6, "sending selected sequences into seqStore");
634664 { U32 storePos;
634665 for (storePos=storeStart; storePos <= storeEnd; storePos++) {
634666 U32 const llen = opt[storePos].litlen;
634667 U32 const mlen = opt[storePos].mlen;
634668 U32 const offBase = opt[storePos].off;
634669 U32 const advance = llen + mlen;
634670 DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",
634671 anchor - istart, (unsigned)llen, (unsigned)mlen);
634672
634673 if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */
634674 assert(storePos == storeEnd); /* must be last sequence */
634675 ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */
634676 continue; /* will finish */
634677 }
634678
634679 assert(anchor + llen <= iend);
634680 ZSTD_updateStats(optStatePtr, llen, anchor, offBase, mlen);
634681 ZSTD_storeSeq(seqStore, llen, anchor, iend, offBase, mlen);
634682 anchor += advance;
634683 ip = anchor;
634684 } }
634685 DEBUGLOG(7, "new offset history : %u, %u, %u", rep[0], rep[1], rep[2]);
634686
634687 /* update all costs */
Definition duckdb.cpp:634156

◆ ZSTD_compressBlock_opt0()

size_t duckdb_zstd::ZSTD_compressBlock_opt0 ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize,
const ZSTD_dictMode_e dictMode )
static

◆ ZSTD_compressBlock_opt2()

size_t duckdb_zstd::ZSTD_compressBlock_opt2 ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize,
const ZSTD_dictMode_e dictMode )
static
634701{
634702 return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode);
634703}
634704#endif
634705

◆ ZSTD_initStats_ultra()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_initStats_ultra ( ZSTD_matchState_t * ms,
seqStore_t * seqStore,
U32 rep[ZSTD_REP_NUM],
const void * src,
size_t srcSize )
static
634740{
634741 U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */
634742 ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));
634743
634744 DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);
634745 assert(ms->opt.litLengthSum == 0); /* first block */
634746 assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */
634747 assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */
634748 assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */
634749
634750 ZSTD_compressBlock_opt2(ms, seqStore, tmpRep, src, srcSize, ZSTD_noDict); /* generate stats into ms->opt*/
634751
634752 /* invalidate first scan from history, only keep entropy stats */

◆ ZSTDMT_freeBufferPool()

void duckdb_zstd::ZSTDMT_freeBufferPool ( ZSTDMT_bufferPool * bufPool)
static
634951{
634952 DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
634953 if (!bufPool) return; /* compatibility with free on NULL */
634954 if (bufPool->buffers) {
634955 unsigned u;
634956 for (u=0; u<bufPool->totalBuffers; u++) {
634957 DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->buffers[u].start);

◆ ZSTDMT_createBufferPool()

ZSTDMT_bufferPool * duckdb_zstd::ZSTDMT_createBufferPool ( unsigned maxNbBuffers,
ZSTD_customMem cMem )
static
634967{
634968 ZSTDMT_bufferPool* const bufPool =
634969 (ZSTDMT_bufferPool*)ZSTD_customCalloc(sizeof(ZSTDMT_bufferPool), cMem);
634970 if (bufPool==NULL) return NULL;
634971 if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
634972 ZSTD_customFree(bufPool, cMem);
634973 return NULL;
634974 }
634975 bufPool->buffers = (buffer_t*)ZSTD_customCalloc(maxNbBuffers * sizeof(buffer_t), cMem);
634976 if (bufPool->buffers==NULL) {
634977 ZSTDMT_freeBufferPool(bufPool);
634978 return NULL;

◆ ZSTDMT_sizeof_bufferPool()

size_t duckdb_zstd::ZSTDMT_sizeof_bufferPool ( ZSTDMT_bufferPool * bufPool)
static
634989{
634990 size_t const poolSize = sizeof(*bufPool);
634991 size_t const arraySize = bufPool->totalBuffers * sizeof(buffer_t);
634992 unsigned u;
634993 size_t totalBufferSize = 0;

◆ ZSTDMT_setBufferSize()

void duckdb_zstd::ZSTDMT_setBufferSize ( ZSTDMT_bufferPool *const bufPool,
size_t const bSize )
static

◆ ZSTDMT_expandBufferPool()

ZSTDMT_bufferPool * duckdb_zstd::ZSTDMT_expandBufferPool ( ZSTDMT_bufferPool * srcBufPool,
unsigned maxNbBuffers )
static
635009 : bSize = %u", (U32)bSize);
635010 bufPool->bufferSize = bSize;
635011 ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
635012}
635013
635014
635015static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, unsigned maxNbBuffers)
635016{
635017 if (srcBufPool==NULL) return NULL;
635018 if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */
635019 return srcBufPool;
635020 /* need a larger buffer pool */
635021 { ZSTD_customMem const cMem = srcBufPool->cMem;
635022 size_t const bSize = srcBufPool->bufferSize; /* forward parameters */
635023 ZSTDMT_bufferPool* newBufPool;

◆ ZSTDMT_getBuffer()

buffer_t duckdb_zstd::ZSTDMT_getBuffer ( ZSTDMT_bufferPool * bufPool)
static

ZSTDMT_getBuffer() : assumption : bufPool must be valid

Returns
: a buffer, with start pointer and size note: allocation may fail, in this case, start==NULL and size==0
635037{
635038 size_t const bSize = bufPool->bufferSize;
635039 DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);
635040 ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
635041 if (bufPool->nbBuffers) { /* try to use an existing buffer */
635042 buffer_t const buf = bufPool->buffers[--(bufPool->nbBuffers)];
635043 size_t const availBufferSize = buf.capacity;
635044 bufPool->buffers[bufPool->nbBuffers] = g_nullBuffer;
635045 if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {
635046 /* large enough, but not too much */
635047 DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",
635048 bufPool->nbBuffers, (U32)buf.capacity);
635049 ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
635050 return buf;
635051 }
635052 /* size conditions not respected : scratch this buffer, create new one */
635053 DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");
635054 ZSTD_customFree(buf.start, bufPool->cMem);
635055 }
635056 ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
635057 /* create new buffer */
635058 DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");
635059 { buffer_t buffer;
635060 void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);
635061 buffer.start = start; /* note : start can be NULL if malloc fails ! */
635062 buffer.capacity = (start==NULL) ? 0 : bSize;
635063 if (start==NULL) {

◆ ZSTDMT_releaseBuffer()

void duckdb_zstd::ZSTDMT_releaseBuffer ( ZSTDMT_bufferPool * bufPool,
buffer_t buf )
static
635092 : buffer allocation failure !!");
635093 }
635094 return buffer;
635095}
635096#endif
635097
635098/* store buffer for later re-use, up to pool capacity */
635099static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
635100{
635101 DEBUGLOG(5, "ZSTDMT_releaseBuffer");
635102 if (buf.start == NULL) return; /* compatible with release on NULL */
635103 ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
635104 if (bufPool->nbBuffers < bufPool->totalBuffers) {
635105 bufPool->buffers[bufPool->nbBuffers++] = buf; /* stored for later use */
635106 DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",
635107 (U32)buf.capacity, (U32)(bufPool->nbBuffers-1));
635108 ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);

◆ ZSTDMT_sizeof_seqPool()

size_t duckdb_zstd::ZSTDMT_sizeof_seqPool ( ZSTDMT_seqPool * seqPool)
static

◆ bufferToSeq()

rawSeqStore_t duckdb_zstd::bufferToSeq ( buffer_t buffer)
static
635133{
635134 return ZSTDMT_sizeof_bufferPool(seqPool);
635135}
635136

◆ seqToBuffer()

buffer_t duckdb_zstd::seqToBuffer ( rawSeqStore_t seq)
static
635138{
635139 rawSeqStore_t seq = kNullRawSeqStore;
635140 seq.seq = (rawSeq*)buffer.start;
635141 seq.capacity = buffer.capacity / sizeof(rawSeq);
635142 return seq;
635143}
635144

◆ ZSTDMT_getSeq()

rawSeqStore_t duckdb_zstd::ZSTDMT_getSeq ( ZSTDMT_seqPool * seqPool)
static
635146{
635147 buffer_t buffer;
635148 buffer.start = seq.seq;
635149 buffer.capacity = seq.capacity * sizeof(rawSeq);
635150 return buffer;
635151}
635152

◆ ZSTDMT_releaseSeq()

void duckdb_zstd::ZSTDMT_releaseSeq ( ZSTDMT_seqPool * seqPool,
rawSeqStore_t seq )
static
635163{
635164 return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));

◆ ZSTDMT_setNbSeq()

void duckdb_zstd::ZSTDMT_setNbSeq ( ZSTDMT_seqPool *const seqPool,
size_t const nbSeq )
static
635169{

◆ ZSTDMT_createSeqPool()

ZSTDMT_seqPool * duckdb_zstd::ZSTDMT_createSeqPool ( unsigned nbWorkers,
ZSTD_customMem cMem )
static
635174{
635175 ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));
635176}
635177

◆ ZSTDMT_freeSeqPool()

void duckdb_zstd::ZSTDMT_freeSeqPool ( ZSTDMT_seqPool * seqPool)
static
635179{
635180 ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(SEQ_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);
635181 if (seqPool == NULL) return NULL;
635182 ZSTDMT_setNbSeq(seqPool, 0);

◆ ZSTDMT_expandSeqPool()

ZSTDMT_seqPool * duckdb_zstd::ZSTDMT_expandSeqPool ( ZSTDMT_seqPool * pool,
U32 nbWorkers )
static
635187{

◆ ZSTDMT_freeCCtxPool()

void duckdb_zstd::ZSTDMT_freeCCtxPool ( ZSTDMT_CCtxPool * pool)
static
635210{
635211 if (!pool) return;
635212 ZSTD_pthread_mutex_destroy(&pool->poolMutex);
635213 if (pool->cctxs) {

◆ ZSTDMT_createCCtxPool()

ZSTDMT_CCtxPool * duckdb_zstd::ZSTDMT_createCCtxPool ( int nbWorkers,
ZSTD_customMem cMem )
static
635226{
635227 ZSTDMT_CCtxPool* const cctxPool =
635228 (ZSTDMT_CCtxPool*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtxPool), cMem);
635229 assert(nbWorkers > 0);
635230 if (!cctxPool) return NULL;
635231 if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
635232 ZSTD_customFree(cctxPool, cMem);
635233 return NULL;
635234 }
635235 cctxPool->totalCCtx = nbWorkers;
635236 cctxPool->cctxs = (ZSTD_CCtx**)ZSTD_customCalloc(nbWorkers * sizeof(ZSTD_CCtx*), cMem);
635237 if (!cctxPool->cctxs) {
635238 ZSTDMT_freeCCtxPool(cctxPool);
635239 return NULL;
635240 }
Definition duckdb.cpp:635193

◆ ZSTDMT_expandCCtxPool()

ZSTDMT_CCtxPool * duckdb_zstd::ZSTDMT_expandCCtxPool ( ZSTDMT_CCtxPool * srcPool,
int nbWorkers )
static
635243 { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
635244 cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
635245 DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
635246 return cctxPool;
635247}
635248
635249static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,
635250 int nbWorkers)
635251{
635252 if (srcPool==NULL) return NULL;

◆ ZSTDMT_sizeof_CCtxPool()

size_t duckdb_zstd::ZSTDMT_sizeof_CCtxPool ( ZSTDMT_CCtxPool * cctxPool)
static
635255 { ZSTD_customMem const cMem = srcPool->cMem;
635256 ZSTDMT_freeCCtxPool(srcPool);
635257 return ZSTDMT_createCCtxPool(nbWorkers, cMem);
635258 }
635259}
635260
635261/* only works during initialization phase, not during compression */
635262static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
635263{
635264 ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
635265 { unsigned const nbWorkers = cctxPool->totalCCtx;
635266 size_t const poolSize = sizeof(*cctxPool);
635267 size_t const arraySize = cctxPool->totalCCtx * sizeof(ZSTD_CCtx*);
635268 size_t totalCCtxSize = 0;
635269 unsigned u;
635270 for (u=0; u<nbWorkers; u++) {

◆ ZSTDMT_getCCtx()

ZSTD_CCtx * duckdb_zstd::ZSTDMT_getCCtx ( ZSTDMT_CCtxPool * cctxPool)
static
635280{
635281 DEBUGLOG(5, "ZSTDMT_getCCtx");
635282 ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
635283 if (cctxPool->availCCtx) {
635284 cctxPool->availCCtx--;
635285 { ZSTD_CCtx* const cctx = cctxPool->cctxs[cctxPool->availCCtx];

◆ ZSTDMT_releaseCCtx()

void duckdb_zstd::ZSTDMT_releaseCCtx ( ZSTDMT_CCtxPool * pool,
ZSTD_CCtx * cctx )
static
635295{
635296 if (cctx==NULL) return; /* compatibility with release on NULL */
635297 ZSTD_pthread_mutex_lock(&pool->poolMutex);
635298 if (pool->availCCtx < pool->totalCCtx)
635299 pool->cctxs[pool->availCCtx++] = cctx;

◆ ZSTDMT_serialState_reset()

int duckdb_zstd::ZSTDMT_serialState_reset ( serialState_t * serialState,
ZSTDMT_seqPool * seqPool,
ZSTD_CCtx_params params,
size_t jobSize,
const void * dict,
size_t const dictSize,
ZSTD_dictContentType_e dictContentType )
static
635338{
635339 /* Adjust parameters */
635340 if (params.ldmParams.enableLdm == ZSTD_ps_enable) {
635341 DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);
635342 ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
635343 assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
635344 assert(params.ldmParams.hashRateLog < 32);
635345 } else {
635346 ZSTD_memset(&params.ldmParams, 0, sizeof(params.ldmParams));
635347 }
635348 serialState->nextJobID = 0;
635349 if (params.fParams.checksumFlag)
635350 XXH64_reset(&serialState->xxhState, 0);
635351 if (params.ldmParams.enableLdm == ZSTD_ps_enable) {
635352 ZSTD_customMem cMem = params.customMem;
635353 unsigned const hashLog = params.ldmParams.hashLog;
635354 size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);
635355 unsigned const bucketLog =
635356 params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;
635357 unsigned const prevBucketLog =
635358 serialState->params.ldmParams.hashLog -
635359 serialState->params.ldmParams.bucketSizeLog;
635360 size_t const numBuckets = (size_t)1 << bucketLog;
635361 /* Size the seq pool tables */
635362 ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));
635363 /* Reset the window */
635364 ZSTD_window_init(&serialState->ldmState.window);
635365 /* Resize tables and output space if necessary. */
635366 if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {
635367 ZSTD_customFree(serialState->ldmState.hashTable, cMem);
635368 serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_customMalloc(hashSize, cMem);
635369 }
635370 if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {
635371 ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);
635372 serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_customMalloc(numBuckets, cMem);
635373 }
635374 if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)
635375 return 1;
635376 /* Zero the tables */
635377 ZSTD_memset(serialState->ldmState.hashTable, 0, hashSize);
635378 ZSTD_memset(serialState->ldmState.bucketOffsets, 0, numBuckets);
635379
635380 /* Update window state and fill hash table with dict */
635381 serialState->ldmState.loadedDictEnd = 0;
635382 if (dictSize > 0) {
635383 if (dictContentType == ZSTD_dct_rawContent) {
635384 BYTE const* const dictEnd = (const BYTE*)dict + dictSize;
635385 ZSTD_window_update(&serialState->ldmState.window, dict, dictSize, /* forceNonContiguous */ 0);
635386 ZSTD_ldm_fillHashTable(&serialState->ldmState, (const BYTE*)dict, dictEnd, &params.ldmParams);
635387 serialState->ldmState.loadedDictEnd = params.forceWindow ? 0 : (U32)(dictEnd - serialState->ldmState.window.base);
635388 } else {
635389 /* don't even load anything */
635390 }
635391 }
635392
635393 /* Initialize serialState's copy of ldmWindow. */

◆ ZSTDMT_serialState_init()

int duckdb_zstd::ZSTDMT_serialState_init ( serialState_t * serialState)
static
635403{
635404 int initError = 0;

◆ ZSTDMT_serialState_free()

void duckdb_zstd::ZSTDMT_serialState_free ( serialState_t * serialState)
static
635414{
635415 ZSTD_customMem cMem = serialState->params.customMem;

◆ ZSTDMT_serialState_update()

void duckdb_zstd::ZSTDMT_serialState_update ( serialState_t * serialState,
ZSTD_CCtx * jobCCtx,
rawSeqStore_t seqStore,
range_t src,
unsigned jobID )
static
635427{
635428 /* Wait for our turn */
635429 ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
635430 while (serialState->nextJobID < jobID) {
635431 DEBUGLOG(5, "wait for serialState->cond");
635432 ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);
635433 }
635434 /* A future job may error and skip our job */
635435 if (serialState->nextJobID == jobID) {
635436 /* It is now our turn, do any processing necessary */
635437 if (serialState->params.ldmParams.enableLdm == ZSTD_ps_enable) {
635438 size_t error;
635439 assert(seqStore.seq != NULL && seqStore.pos == 0 &&
635440 seqStore.size == 0 && seqStore.capacity > 0);
635441 assert(src.size <= serialState->params.jobSize);
635442 ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0);
635444 &serialState->ldmState, &seqStore,
635445 &serialState->params.ldmParams, src.start, src.size);
635446 /* We provide a large enough buffer to never fail. */
635447 assert(!ZSTD_isError(error)); (void)error;
635448 /* Update ldmWindow to match the ldmState.window and signal the main
635449 * thread if it is waiting for a buffer.
635450 */
635451 ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
635452 serialState->ldmWindow = serialState->ldmState.window;
635453 ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
635454 ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
635455 }
635456 if (serialState->params.fParams.checksumFlag && src.size > 0)
635457 XXH64_update(&serialState->xxhState, src.start, src.size);
635458 }
635459 /* Now it is the next jobs turn */
635460 serialState->nextJobID++;
635461 ZSTD_pthread_cond_broadcast(&serialState->cond);

◆ ZSTDMT_serialState_ensureFinished()

void duckdb_zstd::ZSTDMT_serialState_ensureFinished ( serialState_t * serialState,
unsigned jobID,
size_t cSize )
static
635464 {
635465 ZSTD_referenceExternalSequences(jobCCtx, seqStore.seq, seqStore.size);
635466 assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable);
635467 }
635468}
635469
635470static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,
635471 unsigned jobID, size_t cSize)
635472{
635473 ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
635474 if (serialState->nextJobID <= jobID) {
635475 assert(ZSTD_isError(cSize)); (void)cSize;
635476 DEBUGLOG(5, "Skipping past job %u because of error", jobID);
635477 serialState->nextJobID = jobID + 1;
635478 ZSTD_pthread_cond_broadcast(&serialState->cond);
635479
635480 ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
Definition duckdb.cpp:635308

◆ ZSTDMT_compressionJob()

void duckdb_zstd::ZSTDMT_compressionJob ( void * jobDescription)
static
635528{
635529 ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
635530 ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */
635531 ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);
635532 rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);
635533 buffer_t dstBuff = job->dstBuff;
635534 size_t lastCBlockSize = 0;
635535
635536 /* resources */
635537 if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));
635538 if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */
635539 dstBuff = ZSTDMT_getBuffer(job->bufPool);
635540 if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));
635541 job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */
635542 }
635543 if (jobParams.ldmParams.enableLdm == ZSTD_ps_enable && rawSeqStore.seq == NULL)
635544 JOB_ERROR(ERROR(memory_allocation));
635545
635546 /* Don't compute the checksum for chunks, since we compute it externally,
635547 * but write it in the header.
635548 */
635549 if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;
635550 /* Don't run LDM for the chunks, since we handle it externally */
635551 jobParams.ldmParams.enableLdm = ZSTD_ps_disable;
635552 /* Correct nbWorkers to 0. */
635553 jobParams.nbWorkers = 0;
635554
635555
635556 /* init */
635557 if (job->cdict) {
635558 size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize);
635559 assert(job->firstJob); /* only allowed for first job */
635560 if (ZSTD_isError(initError)) JOB_ERROR(initError);
635561 } else { /* srcStart points at reloaded section */
635562 U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;
635563 { size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);
635564 if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);
635565 }
635566 if (!job->firstJob) {
635567 size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0);
635568 if (ZSTD_isError(err)) JOB_ERROR(err);
635569 }
635570 { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,
635571 job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */
635572 ZSTD_dtlm_fast,
635573 NULL, /*cdict*/
635574 &jobParams, pledgedSrcSize);
635575 if (ZSTD_isError(initError)) JOB_ERROR(initError);
635576 } }
635577
635578 /* Perform serial step as early as possible, but after CCtx initialization */
635579 ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);
635580
635581 if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */
635582 size_t const hSize = ZSTD_compressContinue_public(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);
635583 if (ZSTD_isError(hSize)) JOB_ERROR(hSize);
635584 DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);
635585 ZSTD_invalidateRepCodes(cctx);
635586 }
635587
635588 /* compress */
635589 { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;
635590 int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);
635591 const BYTE* ip = (const BYTE*) job->src.start;
635592 BYTE* const ostart = (BYTE*)dstBuff.start;
635593 BYTE* op = ostart;
635594 BYTE* oend = op + dstBuff.capacity;
635595 int chunkNb;
635596 if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */
635597 DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);
635598 assert(job->cSize == 0);
635599 for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {
635600 size_t const cSize = ZSTD_compressContinue_public(cctx, op, oend-op, ip, chunkSize);
635601 if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
635602 ip += chunkSize;
635603 op += cSize; assert(op < oend);
635604 /* stats */
635605 ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
635606 job->cSize += cSize;
635607 job->consumed = chunkSize * chunkNb;
635608 DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",
635609 (U32)cSize, (U32)job->cSize);
635610 ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */
635611 ZSTD_pthread_mutex_unlock(&job->job_mutex);
635612 }
635613 /* last block */
635614 assert(chunkSize > 0);
635615 assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */
635616 if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {
635617 size_t const lastBlockSize1 = job->src.size & (chunkSize-1);
635618 size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;
635619 size_t const cSize = (job->lastJob) ?
635620 ZSTD_compressEnd_public(cctx, op, oend-op, ip, lastBlockSize) :
635621 ZSTD_compressContinue_public(cctx, op, oend-op, ip, lastBlockSize);
635622 if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
635623 lastCBlockSize = cSize;
635624 } }
635625 if (!job->firstJob) {
635626 /* Double check that we don't have an ext-dict, because then our
635627 * repcode invalidation doesn't work.
635628 */
635629 assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
635630 }
635631 ZSTD_CCtx_trace(cctx, 0);
635632
635633_endJob:
635634 ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);
635635 if (job->prefix.size > 0)
635636 DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);
635637 DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);
635638 /* release resources */
635639 ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);
635640 ZSTDMT_releaseCCtx(job->cctxPool, cctx);
635641 /* report */
static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool *bufPool)
Definition duckdb.cpp:635029

◆ ZSTDMT_freeJobsTable()

void duckdb_zstd::ZSTDMT_freeJobsTable ( ZSTDMT_jobDescription * jobTable,
U32 nbJobs,
ZSTD_customMem cMem )
static
635719 : 1;
635720};
635721
635722static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
635723{
635724 U32 jobNb;

◆ ZSTDMT_createJobsTable()

ZSTDMT_jobDescription * duckdb_zstd::ZSTDMT_createJobsTable ( U32 * nbJobsPtr,
ZSTD_customMem cMem )
static
635737{
635738 U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
635739 U32 const nbJobs = 1 << nbJobsLog2;
635740 U32 jobNb;
635741 ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
635742 ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
635743 int initError = 0;
635744 if (jobTable==NULL) return NULL;
635745 *nbJobsPtr = nbJobs;
635746 for (jobNb=0; jobNb<nbJobs; jobNb++) {
635747 initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
635748 initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);

◆ ZSTDMT_expandJobsTable()

size_t duckdb_zstd::ZSTDMT_expandJobsTable ( ZSTDMT_CCtx * mtctx,
U32 nbWorkers )
static
635750 {
635751 ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
635752 return NULL;
635753 }
635754 return jobTable;
635755}
635756
635757static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
635758 U32 nbJobs = nbWorkers + 2;
635759 if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */
635760 ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
635761 mtctx->jobIDMask = 0;

◆ ZSTDMT_CCtxParam_setNbWorkers()

size_t duckdb_zstd::ZSTDMT_CCtxParam_setNbWorkers ( ZSTD_CCtx_params * params,
unsigned nbWorkers )
static

◆ ZSTDMT_createCCtx_advanced_internal()

MEM_STATIC ZSTDMT_CCtx * duckdb_zstd::ZSTDMT_createCCtx_advanced_internal ( unsigned nbWorkers,
ZSTD_customMem cMem,
ZSTD_threadPool * pool )
635774{
635775 return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);
635776}
635777
635778MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
635779{
635780 ZSTDMT_CCtx* mtctx;
635781 U32 nbJobs = nbWorkers + 2;
635782 int initError;
635783 DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
635784
635785 if (nbWorkers < 1) return NULL;
635786 nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
635787 if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
635788 /* invalid custom allocator */
635789 return NULL;
635790
635791 mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);
635792 if (!mtctx) return NULL;
635793 ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
635794 mtctx->cMem = cMem;
635795 mtctx->allJobsCompleted = 1;
635796 if (pool != NULL) {
635797 mtctx->factory = pool;
635798 mtctx->providedFactory = 1;
635799 }
635800 else {
635801 mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
635802 mtctx->providedFactory = 0;
635803 }
635804 mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
635805 assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */
635806 mtctx->jobIDMask = nbJobs - 1;
635807 mtctx->bufPool = ZSTDMT_createBufferPool(BUF_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);
635808 mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
635809 mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
635810 initError = ZSTDMT_serialState_init(&mtctx->serial);
635811 mtctx->roundBuff = kNullRoundBuff;
struct POOL_ctx_s ZSTD_threadPool
Definition duckdb.cpp:408953

◆ ZSTDMT_releaseAllJobResources()

void duckdb_zstd::ZSTDMT_releaseAllJobResources ( ZSTDMT_CCtx * mtctx)
static
635836{
635837 unsigned jobID;
635838 DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
635839 for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
635840 /* Copy the mutex/cond out */
635841 ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;
635842 ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;
635843
635844 DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
635845 ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
635846
635847 /* Clear the job description, but keep the mutex/cond */
635848 ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));

◆ ZSTDMT_waitForAllJobsCompleted()

void duckdb_zstd::ZSTDMT_waitForAllJobsCompleted ( ZSTDMT_CCtx * mtctx)
static
635858{
635859 DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
635860 while (mtctx->doneJobID < mtctx->nextJobID) {
635861 unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
635862 ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
635863 while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {

◆ ZSTDMT_resize()

size_t duckdb_zstd::ZSTDMT_resize ( ZSTDMT_CCtx * mtctx,
unsigned nbWorkers )
static
635907{
635908 if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
635909 FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");
635910 mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, BUF_POOL_MAX_NB_BUFFERS(nbWorkers));
635911 if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
int POOL_resize(POOL_ctx *ctx, size_t numThreads)
Definition duckdb.cpp:611955

◆ ZSTDMT_computeTargetJobLog()

unsigned duckdb_zstd::ZSTDMT_computeTargetJobLog ( const ZSTD_CCtx_params * params)
static
636013{
636014 unsigned jobLog;
636015 if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
636016 /* In Long Range Mode, the windowLog is typically oversized.
636017 * In which case, it's preferable to determine the jobSize

◆ ZSTDMT_overlapLog_default()

int duckdb_zstd::ZSTDMT_overlapLog_default ( ZSTD_strategy strat)
static
636020 {
636021 jobLog = MAX(20, params->cParams.windowLog + 2);
636022 }
636023 return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);
636024}
636025
636026static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
636027{
636028 switch(strat)
636029 {
636030 case ZSTD_btultra2:
636031 return 9;
636032 case ZSTD_btultra:
636033 case ZSTD_btopt:
636034 return 8;
636035 case ZSTD_btlazy2:
636036 case ZSTD_lazy2:
636037 return 7;
636038 case ZSTD_lazy:

◆ ZSTDMT_overlapLog()

int duckdb_zstd::ZSTDMT_overlapLog ( int ovlog,
ZSTD_strategy strat )
static
636040 :
636041 case ZSTD_fast:
636042 default:;
636043 }
636044 return 6;
636045}

◆ ZSTDMT_computeOverlapSize()

size_t duckdb_zstd::ZSTDMT_computeOverlapSize ( const ZSTD_CCtx_params * params)
static
636048{
636049 assert(0 <= ovlog && ovlog <= 9);
636050 if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
636051 return ovlog;
636052}
636053
636054static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)
636055{
636056 int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);
636057 int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);
636058 assert(0 <= overlapRLog && overlapRLog <= 8);
636059 if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
636060 /* In Long Range Mode, the windowLog is typically oversized.
636061 * In which case, it's preferable to determine the jobSize
636062 * based on chainLog instead.
636063 * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
636064 ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)

◆ ZSTDMT_writeLastEmptyBlock()

void duckdb_zstd::ZSTDMT_writeLastEmptyBlock ( ZSTDMT_jobDescription * job)
static
636194{
636195 assert(job->lastJob == 1);
636196 assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */
636197 assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */
636198 assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
636199 job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
636200 if (job->dstBuff.start == NULL) {
636201 job->cSize = ERROR(memory_allocation);
636202 return;

◆ ZSTDMT_createCompressionJob()

size_t duckdb_zstd::ZSTDMT_createCompressionJob ( ZSTDMT_CCtx * mtctx,
size_t srcSize,
ZSTD_EndDirective endOp )
static
636212{
636213 unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
636214 int const endFrame = (endOp == ZSTD_e_end);
636215
636216 if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
636217 DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
636218 assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
636219 return 0;
636220 }
636221
636222 if (!mtctx->jobReady) {
636223 BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
636224 DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
636225 mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
636226 mtctx->jobs[jobID].src.start = src;
636227 mtctx->jobs[jobID].src.size = srcSize;
636228 assert(mtctx->inBuff.filled >= srcSize);
636229 mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
636230 mtctx->jobs[jobID].consumed = 0;
636231 mtctx->jobs[jobID].cSize = 0;
636232 mtctx->jobs[jobID].params = mtctx->params;
636233 mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
636234 mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
636235 mtctx->jobs[jobID].dstBuff = g_nullBuffer;
636236 mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
636237 mtctx->jobs[jobID].bufPool = mtctx->bufPool;
636238 mtctx->jobs[jobID].seqPool = mtctx->seqPool;
636239 mtctx->jobs[jobID].serial = &mtctx->serial;
636240 mtctx->jobs[jobID].jobID = mtctx->nextJobID;
636241 mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
636242 mtctx->jobs[jobID].lastJob = endFrame;
636243 mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
636244 mtctx->jobs[jobID].dstFlushed = 0;
636245
636246 /* Update the round buffer pos and clear the input buffer to be reset */
636247 mtctx->roundBuff.pos += srcSize;
636248 mtctx->inBuff.buffer = g_nullBuffer;
636249 mtctx->inBuff.filled = 0;
636250 /* Set the prefix */
636251 if (!endFrame) {
636252 size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
636253 mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
636254 mtctx->inBuff.prefix.size = newPrefixSize;
636255 } else { /* endFrame==1 => no need for another input buffer */
636256 mtctx->inBuff.prefix = kNullRange;
636257 mtctx->frameEnded = endFrame;
636258 if (mtctx->nextJobID == 0) {
636259 /* single job exception : checksum is already calculated directly within worker thread */
636260 mtctx->params.fParams.checksumFlag = 0;
636261 } }
636262
636263 if ( (srcSize == 0)
636264 && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
636265 DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
636266 assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */
636267 ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
636268 mtctx->nextJobID++;
636269 return 0;
636270 }
636271 }
636272
636273 DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",
636274 mtctx->nextJobID,
636275 (U32)mtctx->jobs[jobID].src.size,
636276 mtctx->jobs[jobID].lastJob,
636277 mtctx->nextJobID,
636278 jobID);
636279 if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
636280 mtctx->nextJobID++;
int POOL_tryAdd(POOL_ctx *ctx, POOL_function function, void *opaque)
Definition duckdb.cpp:612010

◆ ZSTDMT_flushProduced()

size_t duckdb_zstd::ZSTDMT_flushProduced ( ZSTDMT_CCtx * mtctx,
ZSTD_outBuffer * output,
unsigned blockToFlush,
ZSTD_EndDirective end )
static

ZSTDMT_flushProduced() : flush whatever data has been produced but not yet flushed in current job. move to next job if current one is fully flushed. output : pos will be updated with amount of data flushed . blockToFlush : if >0, the function will block and wait if there is no data available to flush .

Returns
: amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code
636297{
636298 unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
636299 DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
636300 blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
636301 assert(output->size >= output->pos);
636302
636303 ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
636304 if ( blockToFlush
636305 && (mtctx->doneJobID < mtctx->nextJobID) ) {
636306 assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
636307 while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */
636308 if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
636309 DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
636310 mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
636311 break;
636312 }
636313 DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
636314 mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
636315 ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */
636316 } }
636317
636318 /* try to flush something */
636319 { size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */
636320 size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */
636321 size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */
636322 ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
636323 if (ZSTD_isError(cSize)) {
636324 DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
636325 mtctx->doneJobID, ZSTD_getErrorName(cSize));
636326 ZSTDMT_waitForAllJobsCompleted(mtctx);
636327 ZSTDMT_releaseAllJobResources(mtctx);
636328 return cSize;
636329 }
636330 /* add frame checksum if necessary (can only happen once) */
636331 assert(srcConsumed <= srcSize);
636332 if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */
636333 && mtctx->jobs[wJobID].frameChecksumNeeded ) {
636334 U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
636335 DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
636336 MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
636337 cSize += 4;
636338 mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */
636339 mtctx->jobs[wJobID].frameChecksumNeeded = 0;
636340 }
636341
636342 if (cSize > 0) { /* compression is ongoing or completed */
636343 size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
636344 DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
636345 (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
636346 assert(mtctx->doneJobID < mtctx->nextJobID);
636347 assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
636348 assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
636349 if (toFlush > 0) {
636350 ZSTD_memcpy((char*)output->dst + output->pos,
636351 (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
636352 toFlush);
636353 }
636354 output->pos += toFlush;
636355 mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */
636356
636357 if ( (srcConsumed == srcSize) /* job is completed */
636358 && (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */
636359 DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
636360 mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
636361 ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
636362 DEBUGLOG(5, "dstBuffer released");
636363 mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
636364 mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */
636365 mtctx->consumed += srcSize;
636366 mtctx->produced += cSize;
636367 mtctx->doneJobID++;
636368 } }
636369
636370 /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
636371 if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
636372 if (srcSize > srcConsumed) return 1; /* current job not completely compressed */
636373 }
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTDMT_getInputDataInUse()

range_t duckdb_zstd::ZSTDMT_getInputDataInUse ( ZSTDMT_CCtx * mtctx)
static

Returns the range of data used by the earliest job that is not yet complete. If the data of the first job is broken up into two segments, we cover both sections.

636388{
636389 unsigned const firstJobID = mtctx->doneJobID;
636390 unsigned const lastJobID = mtctx->nextJobID;
636391 unsigned jobID;
636392
636393 for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
636394 unsigned const wJobID = jobID & mtctx->jobIDMask;
636395 size_t consumed;
636396
636397 ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
636398 consumed = mtctx->jobs[wJobID].consumed;
636399 ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
636400
636401 if (consumed < mtctx->jobs[wJobID].src.size) {
636402 range_t range = mtctx->jobs[wJobID].prefix;
636403 if (range.size == 0) {
636404 /* Empty prefix */
636405 range = mtctx->jobs[wJobID].src;
636406 }
Definition duckdb.cpp:635303

◆ ZSTDMT_isOverlapped()

int duckdb_zstd::ZSTDMT_isOverlapped ( buffer_t buffer,
range_t range )
static

Returns non-zero iff buffer and range overlap.

636419{
636420 BYTE const* const bufferStart = (BYTE const*)buffer.start;
636421 BYTE const* const rangeStart = (BYTE const*)range.start;
636422
636423 if (rangeStart == NULL || bufferStart == NULL)
636424 return 0;
636425
636426 {
636427 BYTE const* const bufferEnd = bufferStart + buffer.capacity;
636428 BYTE const* const rangeEnd = rangeStart + range.size;
636429

◆ ZSTDMT_doesOverlapWindow()

int duckdb_zstd::ZSTDMT_doesOverlapWindow ( buffer_t buffer,
ZSTD_window_t window )
static
636439{
636440 range_t extDict;
636441 range_t prefix;
636442
636443 DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
636444 extDict.start = window.dictBase + window.lowLimit;
636445 extDict.size = window.dictLimit - window.lowLimit;
636446
636447 prefix.start = window.base + window.dictLimit;
636448 prefix.size = window.nextSrc - (window.base + window.dictLimit);
636449 DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
636450 (size_t)extDict.start,
636451 (size_t)extDict.start + extDict.size);

◆ ZSTDMT_waitForLdmComplete()

void duckdb_zstd::ZSTDMT_waitForLdmComplete ( ZSTDMT_CCtx * mtctx,
buffer_t buffer )
static
636461{
636462 if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) {
636463 ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
636464 DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
636465 DEBUGLOG(5, "source [0x%zx, 0x%zx)",
636466 (size_t)buffer.start,
636467 (size_t)buffer.start + buffer.capacity);
636468 ZSTD_PTHREAD_MUTEX_LOCK(mutex);
636469 while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {

◆ ZSTDMT_tryGetInputRange()

int duckdb_zstd::ZSTDMT_tryGetInputRange ( ZSTDMT_CCtx * mtctx)
static

Attempts to set the inBuff to the next section to fill. If any part of the new section is still in use we give up. Returns non-zero if the buffer is filled.

636484{
636485 range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
636486 size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
636487 size_t const target = mtctx->targetSectionSize;
636488 buffer_t buffer;
636489
636490 DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
636491 assert(mtctx->inBuff.buffer.start == NULL);
636492 assert(mtctx->roundBuff.capacity >= target);
636493
636494 if (spaceLeft < target) {
636495 /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
636496 * Simply copy the prefix to the beginning in that case.
636497 */
636498 BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
636499 size_t const prefixSize = mtctx->inBuff.prefix.size;
636500
636501 buffer.start = start;
636502 buffer.capacity = prefixSize;
636503 if (ZSTDMT_isOverlapped(buffer, inUse)) {
636504 DEBUGLOG(5, "Waiting for buffer...");
636505 return 0;
636506 }
636507 ZSTDMT_waitForLdmComplete(mtctx, buffer);
636508 ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);
636509 mtctx->inBuff.prefix.start = start;
636510 mtctx->roundBuff.pos = prefixSize;
636511 }
636512 buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
636513 buffer.capacity = target;
636514
636515 if (ZSTDMT_isOverlapped(buffer, inUse)) {
636516 DEBUGLOG(5, "Waiting for buffer...");
636517 return 0;
636518 }
636519 assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
636520
636521 ZSTDMT_waitForLdmComplete(mtctx, buffer);
636522
636523 DEBUGLOG(5, "Using prefix range [%zx, %zx)",
636524 (size_t)mtctx->inBuff.prefix.start,
636525 (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
636526 DEBUGLOG(5, "Using source range [%zx, %zx)",
636527 (size_t)buffer.start,
636528 (size_t)buffer.start + buffer.capacity);
static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
Definition duckdb.cpp:636411
static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx *mtctx)
Definition duckdb.cpp:636380

◆ findSynchronizationPoint()

syncPoint_t duckdb_zstd::findSynchronizationPoint ( ZSTDMT_CCtx const * mtctx,
ZSTD_inBuffer const input )
static

Searches through the input for a synchronization point. If one is found, we will instruct the caller to flush, and return the number of bytes to load. Otherwise, we will load as many bytes as possible and instruct the caller to continue as normal.

636550{
636551 BYTE const* const istart = (BYTE const*)input.src + input.pos;
636552 U64 const primePower = mtctx->rsync.primePower;
636553 U64 const hitMask = mtctx->rsync.hitMask;
636554
636555 syncPoint_t syncPoint;
636556 U64 hash;
636557 BYTE const* prev;
636558 size_t pos;
636559
636560 syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
636561 syncPoint.flush = 0;
636562 if (!mtctx->params.rsyncable)
636563 /* Rsync is disabled. */
636564 return syncPoint;
636565 if (mtctx->inBuff.filled + input.size - input.pos < RSYNC_MIN_BLOCK_SIZE)
636566 /* We don't emit synchronization points if it would produce too small blocks.
636567 * We don't have enough input to find a synchronization point, so don't look.
636568 */
636569 return syncPoint;
636570 if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
636571 /* Not enough to compute the hash.
636572 * We will miss any synchronization points in this RSYNC_LENGTH byte
636573 * window. However, since it depends only in the internal buffers, if the
636574 * state is already synchronized, we will remain synchronized.
636575 * Additionally, the probability that we miss a synchronization point is
636576 * low: RSYNC_LENGTH / targetSectionSize.
636577 */
636578 return syncPoint;
636579 /* Initialize the loop variables. */
636580 if (mtctx->inBuff.filled < RSYNC_MIN_BLOCK_SIZE) {
636581 /* We don't need to scan the first RSYNC_MIN_BLOCK_SIZE positions
636582 * because they can't possibly be a sync point. So we can start
636583 * part way through the input buffer.
636584 */
636585 pos = RSYNC_MIN_BLOCK_SIZE - mtctx->inBuff.filled;
636586 if (pos >= RSYNC_LENGTH) {
636587 prev = istart + pos - RSYNC_LENGTH;
636588 hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
636589 } else {
636590 assert(mtctx->inBuff.filled >= RSYNC_LENGTH);
636591 prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
636592 hash = ZSTD_rollingHash_compute(prev + pos, (RSYNC_LENGTH - pos));
636593 hash = ZSTD_rollingHash_append(hash, istart, pos);
636594 }
636595 } else {
636596 /* We have enough bytes buffered to initialize the hash,
636597 * and have processed enough bytes to find a sync point.
636598 * Start scanning at the beginning of the input.
636599 */
636600 assert(mtctx->inBuff.filled >= RSYNC_MIN_BLOCK_SIZE);
636601 assert(RSYNC_MIN_BLOCK_SIZE >= RSYNC_LENGTH);
636602 pos = 0;
636603 prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
636604 hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
636605 if ((hash & hitMask) == hitMask) {
636606 /* We're already at a sync point so don't load any more until
636607 * we're able to flush this sync point.
636608 * This likely happened because the job table was full so we
636609 * couldn't add our job.
636610 */
636611 syncPoint.toLoad = 0;
636612 syncPoint.flush = 1;
636613 return syncPoint;
636614 }
636615 }
636616 /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
636617 * through the input. If we hit a synchronization point, then cut the
636618 * job off, and tell the compressor to flush the job. Otherwise, load
636619 * all the bytes and continue as normal.
636620 * If we go too long without a synchronization point (targetSectionSize)
636621 * then a block will be emitted anyways, but this is okay, since if we
636622 * are already synchronized we will remain synchronized.
636623 */
636624 assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);
636625 for (; pos < syncPoint.toLoad; ++pos) {
636626 BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
636627 /* This assert is very expensive, and Debian compiles with asserts enabled.
636628 * So disable it for now. We can get similar coverage by checking it at the
636629 * beginning & end of the loop.
636630 * assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);
636631 */
636632 hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
636633 assert(mtctx->inBuff.filled + pos >= RSYNC_MIN_BLOCK_SIZE);
636634 if ((hash & hitMask) == hitMask) {
636635 syncPoint.toLoad = pos + 1;
636636 syncPoint.flush = 1;
static U64 ZSTD_rollingHash_append(U64 hash, void const *buf, size_t size)
Definition duckdb.cpp:618393
MEM_STATIC U64 ZSTD_rollingHash_compute(void const *buf, size_t size)
Definition duckdb.cpp:618407
MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
Definition duckdb.cpp:618424
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_getDTableDesc()

DTableDesc duckdb_zstd::HUF_getDTableDesc ( const HUF_DTable * table)
static
636879 { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc;

◆ HUF_initFastDStream()

size_t duckdb_zstd::HUF_initFastDStream ( BYTE const * ip)
static
636882{
636883 DTableDesc dtd;
636884 ZSTD_memcpy(&dtd, table, sizeof(dtd));
636885 return dtd;
636886}
636887
636888static size_t HUF_initFastDStream(BYTE const* ip) {

◆ HUF_DecompressFastArgs_init()

size_t duckdb_zstd::HUF_DecompressFastArgs_init ( HUF_DecompressFastArgs * args,
void * dst,
size_t dstSize,
void const * src,
size_t srcSize,
const HUF_DTable * DTable )
static

Initializes args for the fast decoding loop.

Returns
1 on success 0 if the fallback implementation should be used. Or an error code on failure.
636930{
636931 void const* dt = DTable + 1;
636932 U32 const dtLog = HUF_getDTableDesc(DTable).tableLog;
636933
636934 const BYTE* const istart = (const BYTE*)src;
636935
636936 BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
636937
636938 /* The fast decoding loop assumes 64-bit little-endian.
636939 * This condition is false on x32.
636940 */
636941 if (!MEM_isLittleEndian() || MEM_32bits())
636942 return 0;
636943
636944 /* Avoid nullptr addition */
636945 if (dstSize == 0)
636946 return 0;
636947 assert(dst != NULL);
636948
636949 /* strict minimum : jump table + 1 byte per stream */
636950 if (srcSize < 10)
636951 return ERROR(corruption_detected);
636952
636953 /* Must have at least 8 bytes per stream because we don't handle initializing smaller bit containers.
636954 * If table log is not correct at this point, fallback to the old decoder.
636955 * On small inputs we don't have enough data to trigger the fast loop, so use the old decoder.
636956 */
636957 if (dtLog != HUF_DECODER_FAST_TABLELOG)
636958 return 0;
636959
636960 /* Read the jump table. */
636961 {
636962 size_t const length1 = MEM_readLE16(istart);
636963 size_t const length2 = MEM_readLE16(istart+2);
636964 size_t const length3 = MEM_readLE16(istart+4);
636965 size_t const length4 = srcSize - (length1 + length2 + length3 + 6);
636966 args->iend[0] = istart + 6; /* jumpTable */
636967 args->iend[1] = args->iend[0] + length1;
636968 args->iend[2] = args->iend[1] + length2;
636969 args->iend[3] = args->iend[2] + length3;
636970
636971 /* HUF_initFastDStream() requires this, and this small of an input
636972 * won't benefit from the ASM loop anyways.
636973 */
636974 if (length1 < 8 || length2 < 8 || length3 < 8 || length4 < 8)
636975 return 0;
636976 if (length4 > srcSize) return ERROR(corruption_detected); /* overflow */
636977 }
636978 /* ip[] contains the position that is currently loaded into bits[]. */
636979 args->ip[0] = args->iend[1] - sizeof(U64);
636980 args->ip[1] = args->iend[2] - sizeof(U64);
636981 args->ip[2] = args->iend[3] - sizeof(U64);
636982 args->ip[3] = (BYTE const*)src + srcSize - sizeof(U64);
636983
636984 /* op[] contains the output pointers. */
636985 args->op[0] = (BYTE*)dst;
636986 args->op[1] = args->op[0] + (dstSize+3)/4;
636987 args->op[2] = args->op[1] + (dstSize+3)/4;
636988 args->op[3] = args->op[2] + (dstSize+3)/4;
636989
636990 /* No point to call the ASM loop for tiny outputs. */
636991 if (args->op[3] >= oend)
636992 return 0;
636993
636994 /* bits[] is the bit container.
636995 * It is read from the MSB down to the LSB.
636996 * It is shifted left as it is read, and zeros are
636997 * shifted in. After the lowest valid bit a 1 is
636998 * set, so that CountTrailingZeros(bits[]) can be used
636999 * to count how many bits we've consumed.
637000 */
637001 args->bits[0] = HUF_initFastDStream(args->ip[0]);
637002 args->bits[1] = HUF_initFastDStream(args->ip[1]);
637003 args->bits[2] = HUF_initFastDStream(args->ip[2]);
637004 args->bits[3] = HUF_initFastDStream(args->ip[3]);
637005
637006 /* The decoders must be sure to never read beyond ilowest.
637007 * This is lower than iend[0], but allowing decoders to read
637008 * down to ilowest can allow an extra iteration or two in the
637009 * fast loop.
637010 */
MEM_STATIC unsigned char * ZSTD_maybeNullPtrAdd(unsigned char *ptr, ptrdiff_t add)
Definition duckdb.cpp:608335
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_initRemainingDStream()

size_t duckdb_zstd::HUF_initRemainingDStream ( BIT_DStream_t * bit,
HUF_DecompressFastArgs const * args,
int stream,
BYTE * segmentEnd )
static
637020{
637021 /* Validate that we haven't overwritten. */
637022 if (args->op[stream] > segmentEnd)
637023 return ERROR(corruption_detected);
637024 /* Validate that we haven't read beyond iend[].
637025 * Note that ip[] may be < iend[] because the MSB is
637026 * the next bit to read, and we may have consumed 100%
637027 * of the stream, so down to iend[i] - 8 is valid.
637028 */
637029 if (args->ip[stream] < args->iend[stream] - 8)
637030 return ERROR(corruption_detected);
637031
637032 /* Construct the BIT_DStream_t. */
637033 assert(sizeof(size_t) == 8);
637034 bit->bitContainer = MEM_readLEST(args->ip[stream]);

◆ HUF_DEltX1_set4()

U64 duckdb_zstd::HUF_DEltX1_set4 ( BYTE symbol,
BYTE nbBits )
static

Packs 4 HUF_DEltX1 structs into a U64. This is used to lay down 4 entries at a time.

637067 { BYTE nbBits; BYTE byte; } HUF_DEltX1; /* single-symbol decoding */
637068
637073static U64 HUF_DEltX1_set4(BYTE symbol, BYTE nbBits) {
637074 U64 D4;
637075 if (MEM_isLittleEndian()) {
637076 D4 = (U64)((symbol << 8) + nbBits);

◆ HUF_rescaleStats()

U32 duckdb_zstd::HUF_rescaleStats ( BYTE * huffWeight,
U32 * rankVal,
U32 nbSymbols,
U32 tableLog,
U32 targetTableLog )
static

Increase the tableLog to targetTableLog and rescales the stats. If tableLog > targetTableLog this is a no-op.

Returns
New tableLog
637091{
637092 if (tableLog > targetTableLog)
637093 return tableLog;
637094 if (tableLog < targetTableLog) {
637095 U32 const scale = targetTableLog - tableLog;
637096 U32 s;
637097 /* Increase the weight for all non-zero probability symbols by scale. */
637098 for (s = 0; s < nbSymbols; ++s) {
637099 huffWeight[s] += (BYTE)((huffWeight[s] == 0) ? 0 : scale);
637100 }
637101 /* Update rankVal to reflect the new weights.
637102 * All weights except 0 get moved to weight + scale.
637103 * Weights [1, scale] are empty.
637104 */
637105 for (s = targetTableLog; s > scale; --s) {
637106 rankVal[s] = rankVal[s - scale];

◆ HUF_decodeSymbolX1()

FORCE_INLINE_TEMPLATE BYTE duckdb_zstd::HUF_decodeSymbolX1 ( BIT_DStream_t * Dstream,
const HUF_DEltX1 * dt,
const U32 dtLog )

◆ HUF_decodeStreamX1()

HINT_INLINE size_t duckdb_zstd::HUF_decodeStreamX1 ( BYTE * p,
BIT_DStream_t *const bitDPtr,
BYTE *const pEnd,
const HUF_DEltX1 *const dt,
const U32 dtLog )
637278 { \
637279 if (MEM_64bits()) \
637280 HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr); \
637281 } while (0)
637282
637283HINT_INLINE size_t
637284HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog)
637285{
637286 BYTE* const pStart = p;
637287
637288 /* up to 4 symbols at a time */
637289 if ((pEnd - p) > 3) {
637290 while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) {
637291 HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
637292 HUF_DECODE_SYMBOLX1_1(p, bitDPtr);
637293 HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
637294 HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
637295 }
637296 } else {
637297 BIT_reloadDStream(bitDPtr);
637298 }
637299
637300 /* [0-3] symbols remaining */
637301 if (MEM_32bits())
637302 while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd))
637303 HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
#define HINT_INLINE
Definition duckdb.cpp:608056

◆ HUF_decompress1X1_usingDTable_internal_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_decompress1X1_usingDTable_internal_body ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable )
637317{
637318 BYTE* op = (BYTE*)dst;
637319 BYTE* const oend = ZSTD_maybeNullPtrAdd(op, dstSize);
637320 const void* dtPtr = DTable + 1;
637321 const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
637322 BIT_DStream_t bitD;
637323 DTableDesc const dtd = HUF_getDTableDesc(DTable);
637324 U32 const dtLog = dtd.tableLog;
637325
637326 CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );

◆ HUF_decompress4X1_usingDTable_internal_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_decompress4X1_usingDTable_internal_body ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable )
637344{
637345 /* Check */
637346 if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
637347 if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */
637348
637349 { const BYTE* const istart = (const BYTE*) cSrc;
637350 BYTE* const ostart = (BYTE*) dst;
637351 BYTE* const oend = ostart + dstSize;
637352 BYTE* const olimit = oend - 3;
637353 const void* const dtPtr = DTable + 1;
637354 const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
637355
637356 /* Init */
637357 BIT_DStream_t bitD1;
637358 BIT_DStream_t bitD2;
637359 BIT_DStream_t bitD3;
637360 BIT_DStream_t bitD4;
637361 size_t const length1 = MEM_readLE16(istart);
637362 size_t const length2 = MEM_readLE16(istart+2);
637363 size_t const length3 = MEM_readLE16(istart+4);
637364 size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
637365 const BYTE* const istart1 = istart + 6; /* jumpTable */
637366 const BYTE* const istart2 = istart1 + length1;
637367 const BYTE* const istart3 = istart2 + length2;
637368 const BYTE* const istart4 = istart3 + length3;
637369 const size_t segmentSize = (dstSize+3) / 4;
637370 BYTE* const opStart2 = ostart + segmentSize;
637371 BYTE* const opStart3 = opStart2 + segmentSize;
637372 BYTE* const opStart4 = opStart3 + segmentSize;
637373 BYTE* op1 = ostart;
637374 BYTE* op2 = opStart2;
637375 BYTE* op3 = opStart3;
637376 BYTE* op4 = opStart4;
637377 DTableDesc const dtd = HUF_getDTableDesc(DTable);
637378 U32 const dtLog = dtd.tableLog;
637379 U32 endSignal = 1;
637380
637381 if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
637382 if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */
637383 assert(dstSize >= 6); /* validated above */
637384 CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
637385 CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
637386 CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
637387 CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
637388
637389 /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */
637390 if ((size_t)(oend - op4) >= sizeof(size_t)) {
637391 for ( ; (endSignal) & (op4 < olimit) ; ) {
637392 HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
637393 HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
637394 HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
637395 HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
637396 HUF_DECODE_SYMBOLX1_1(op1, &bitD1);
637397 HUF_DECODE_SYMBOLX1_1(op2, &bitD2);
637398 HUF_DECODE_SYMBOLX1_1(op3, &bitD3);
637399 HUF_DECODE_SYMBOLX1_1(op4, &bitD4);
637400 HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
637401 HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
637402 HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
637403 HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
637404 HUF_DECODE_SYMBOLX1_0(op1, &bitD1);
637405 HUF_DECODE_SYMBOLX1_0(op2, &bitD2);
637406 HUF_DECODE_SYMBOLX1_0(op3, &bitD3);
637407 HUF_DECODE_SYMBOLX1_0(op4, &bitD4);
637408 endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
637409 endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
637410 endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
637411 endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
637412 }
637413 }
637414
637415 /* check corruption */
637416 /* note : should not be necessary : op# advance in lock step, and we control op4.
637417 * but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */
637418 if (op1 > opStart2) return ERROR(corruption_detected);
637419 if (op2 > opStart3) return ERROR(corruption_detected);
637420 if (op3 > opStart4) return ERROR(corruption_detected);
637421 /* note : op4 supposed already verified within main loop */
637422
637423 /* finish bitStreams one by one */
637424 HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog);
637425 HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog);
637426 HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog);
637427 HUF_decodeStreamX1(op4, &bitD4, oend, dt, dtLog);
637428
637429 /* check */
MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t *bitD)
Definition duckdb.cpp:609899

◆ HUF_decompress4X1_usingDTable_internal_default()

size_t duckdb_zstd::HUF_decompress4X1_usingDTable_internal_default ( void * dst,
size_t dstSize,
void const * cSrc,
size_t cSrcSize,
HUF_DTable const * DTable )
static
637441 {
637442 return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
637443}

◆ HUF_decompress4X1_usingDTable_internal_fast_c_loop()

HUF_FAST_BMI2_ATTRS void duckdb_zstd::HUF_decompress4X1_usingDTable_internal_fast_c_loop ( HUF_DecompressFastArgs * args)
static
637448 {
637449 return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
637450}
637451
637452static HUF_FAST_BMI2_ATTRS
637453void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args)
637454{
637455 U64 bits[4];
637456 BYTE const* ip[4];
637457 BYTE* op[4];
637458 U16 const* const dtable = (U16 const*)args->dt;
637459 BYTE* const oend = args->oend;
637460 BYTE const* const ilowest = args->ilowest;
637461
637462 /* Copy the arguments to local variables */
637463 ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
637464 ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip));
637465 ZSTD_memcpy(&op, &args->op, sizeof(op));
637466
637467 assert(MEM_isLittleEndian());
637468 assert(!MEM_32bits());
637469
637470 for (;;) {
637471 BYTE* olimit;
637472 int stream;
637473
637474 /* Assert loop preconditions */
637475#ifndef NDEBUG
637476 for (stream = 0; stream < 4; ++stream) {
637477 assert(op[stream] <= (stream == 3 ? oend : op[stream + 1]));
637478 assert(ip[stream] >= ilowest);
637479 }
637480#endif
637481 /* Compute olimit */
637482 {
637483 /* Each iteration produces 5 output symbols per stream */
637484 size_t const oiters = (size_t)(oend - op[3]) / 5;
637485 /* Each iteration consumes up to 11 bits * 5 = 55 bits < 7 bytes
637486 * per stream.
637487 */
637488 size_t const iiters = (size_t)(ip[0] - ilowest) / 7;
637489 /* We can safely run iters iterations before running bounds checks */
637490 size_t const iters = MIN(oiters, iiters);
637491 size_t const symbols = iters * 5;
637492
637493 /* We can simply check that op[3] < olimit, instead of checking all
637494 * of our bounds, since we can't hit the other bounds until we've run
637495 * iters iterations, which only happens when op[3] == olimit.
637496 */
637497 olimit = op[3] + symbols;
637498
637499 /* Exit fast decoding loop once we reach the end. */
637500 if (op[3] == olimit)
637501 break;
637502
637503 /* Exit the decoding loop if any input pointer has crossed the
637504 * previous one. This indicates corruption, and a precondition
637505 * to our loop is that ip[i] >= ip[0].
637506 */
637507 for (stream = 1; stream < 4; ++stream) {
637508 if (ip[stream] < ip[stream - 1])
637509 goto _out;
637510 }
637511 }
637512
637513#ifndef NDEBUG
637514 for (stream = 1; stream < 4; ++stream) {
637515 assert(ip[stream] >= ip[stream - 1]);
637516 }
637517#endif
637518
637519#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol) \
637520 do { \
637521 int const index = (int)(bits[(_stream)] >> 53); \
637522 int const entry = (int)dtable[index]; \
637523 bits[(_stream)] <<= (entry & 0x3F); \
637524 op[(_stream)][(_symbol)] = (BYTE)((entry >> 8) & 0xFF); \
637525 } while (0)
637526
637527#define HUF_4X1_RELOAD_STREAM(_stream) \
637528 do { \
637529 int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
637530 int const nbBits = ctz & 7; \
637531 int const nbBytes = ctz >> 3; \
637532 op[(_stream)] += 5; \
637533 ip[(_stream)] -= nbBytes; \
637534 bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \
637535 bits[(_stream)] <<= nbBits; \
637536 } while (0)
637537
637538 /* Manually unroll the loop because compilers don't consistently
637539 * unroll the inner loops, which destroys performance.
637540 */
637541 do {
637542 /* Decode 5 symbols in each of the 4 streams */
637543 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0);
637544 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1);
637545 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2);
637546 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3);
637547 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 4);
637548
637549 /* Reload each of the 4 the bitstreams */
637550 HUF_4X_FOR_EACH_STREAM(HUF_4X1_RELOAD_STREAM);
637551 } while (op[3] < olimit);
637552
637553#undef HUF_4X1_DECODE_SYMBOL
637554#undef HUF_4X1_RELOAD_STREAM
637555 }
637556

◆ HUF_decompress4X1_usingDTable_internal_fast()

HUF_FAST_BMI2_ATTRS size_t duckdb_zstd::HUF_decompress4X1_usingDTable_internal_fast ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable,
HUF_DecompressFastLoopFn loopFn )
static
Returns
dstSize on success (>= 6) 0 if the fallback implementation should be used An error if an error occurred
637577{
637578 void const* dt = DTable + 1;
637579 BYTE const* const ilowest = (BYTE const*)cSrc;
637580 BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
637582 { size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
637583 FORWARD_IF_ERROR(ret, "Failed to init fast loop args");
637584 if (ret == 0)
637585 return 0;
637586 }
637587
637588 assert(args.ip[0] >= args.ilowest);
637589 loopFn(&args);
637590
637591 /* Our loop guarantees that ip[] >= ilowest and that we haven't
637592 * overwritten any op[].
637593 */
637594 assert(args.ip[0] >= ilowest);
637595 assert(args.ip[0] >= ilowest);
637596 assert(args.ip[1] >= ilowest);
637597 assert(args.ip[2] >= ilowest);
637598 assert(args.ip[3] >= ilowest);
637599 assert(args.op[3] <= oend);
637600
637601 assert(ilowest == args.ilowest);
637602 assert(ilowest + 6 == args.iend[0]);
637603 (void)ilowest;
637604
637605 /* finish bit streams one by one. */
637606 { size_t const segmentSize = (dstSize+3) / 4;
637607 BYTE* segmentEnd = (BYTE*)dst;
637608 int i;
637609 for (i = 0; i < 4; ++i) {
637610 BIT_DStream_t bit;
637611 if (segmentSize <= (size_t)(oend - segmentEnd))
637612 segmentEnd += segmentSize;
637613 else
637614 segmentEnd = oend;
637615 FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption");
637616 /* Decompress and validate that we've produced exactly the expected length. */
637617 args.op[i] += HUF_decodeStreamX1(args.op[i], &bit, segmentEnd, (HUF_DEltX1 const*)dt, HUF_DECODER_FAST_TABLELOG);
637618 if (args.op[i] != segmentEnd) return ERROR(corruption_detected);
static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs *args, void *dst, size_t dstSize, void const *src, size_t srcSize, const HUF_DTable *DTable)
Definition duckdb.cpp:636922
Definition duckdb.cpp:636904
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_decompress4X1_usingDTable_internal()

size_t duckdb_zstd::HUF_decompress4X1_usingDTable_internal ( void * dst,
size_t dstSize,
void const * cSrc,
size_t cSrcSize,
HUF_DTable const * DTable,
int flags )
static
637631{
637632 HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X1_usingDTable_internal_default;
637633 HUF_DecompressFastLoopFn loopFn = HUF_decompress4X1_usingDTable_internal_fast_c_loop;
637634
637635#if DYNAMIC_BMI2
637636 if (flags & HUF_flags_bmi2) {
637637 fallbackFn = HUF_decompress4X1_usingDTable_internal_bmi2;
637638 } else {
637639 return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
637640 }
637641#endif

◆ HUF_decompress4X1_DCtx_wksp()

size_t duckdb_zstd::HUF_decompress4X1_DCtx_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )
static
637653{
637654 const BYTE* ip = (const BYTE*) cSrc;
637655

◆ HUF_buildDEltX2U32()

U32 duckdb_zstd::HUF_buildDEltX2U32 ( U32 symbol,
U32 nbBits,
U32 baseSeq,
int level )
static

Constructs a HUF_DEltX2 in a U32.

637674 { BYTE symbol; } sortedSymbol_t;
637675typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1];
637676typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX];
637677
637681static U32 HUF_buildDEltX2U32(U32 symbol, U32 nbBits, U32 baseSeq, int level)
637682{
637683 U32 seq;
637684 DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, sequence) == 0);
637685 DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, nbBits) == 2);
637686 DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, length) == 3);
637687 DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U32));
637688 if (MEM_isLittleEndian()) {
static U32 HUF_buildDEltX2U32(U32 symbol, U32 nbBits, U32 baseSeq, int level)
Definition duckdb.cpp:637674

◆ HUF_buildDEltX2()

HUF_DEltX2 duckdb_zstd::HUF_buildDEltX2 ( U32 symbol,
U32 nbBits,
U32 baseSeq,
int level )
static

Constructs a HUF_DEltX2.

Here is the caller graph for this function:

◆ HUF_buildDEltX2U64()

U64 duckdb_zstd::HUF_buildDEltX2U64 ( U32 symbol,
U32 nbBits,
U16 baseSeq,
int level )
static

Constructs 2 HUF_DEltX2s and packs them into a U64.

Here is the caller graph for this function:

◆ HUF_fillDTableX2ForWeight()

void duckdb_zstd::HUF_fillDTableX2ForWeight ( HUF_DEltX2 * DTableRank,
sortedSymbol_t const * begin,
sortedSymbol_t const * end,
U32 nbBits,
U32 tableLog,
U16 baseSeq,
int const level )
static

Fills the DTable rank with all the symbols from [begin, end) that are each nbBits long.

Parameters
DTableRankThe start of the rank in the DTable.
beginThe first symbol to fill (inclusive).
endThe last symbol to fill (exclusive).
nbBitsEach symbol is nbBits long.
tableLogThe table log.
baseSeqIf level == 1 { 0 } else { the first level symbol }
levelThe level in the table. Must be 1 or 2.
637727 { 0 } else { the first level symbol }
637728 * @param level The level in the table. Must be 1 or 2.
637729 */
637730static void HUF_fillDTableX2ForWeight(
637731 HUF_DEltX2* DTableRank,
637732 sortedSymbol_t const* begin, sortedSymbol_t const* end,
637733 U32 nbBits, U32 tableLog,
637734 U16 baseSeq, int const level)
637735{
637736 U32 const length = 1U << ((tableLog - nbBits) & 0x1F /* quiet static-analyzer */);
637737 const sortedSymbol_t* ptr;
637738 assert(level >= 1 && level <= 2);
637739 switch (length) {
637740 case 1:
637741 for (ptr = begin; ptr != end; ++ptr) {
637742 HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level);
637743 *DTableRank++ = DElt;
637744 }
637745 break;
637746 case 2:
637747 for (ptr = begin; ptr != end; ++ptr) {
637748 HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level);
637749 DTableRank[0] = DElt;
637750 DTableRank[1] = DElt;
637751 DTableRank += 2;
637752 }
637753 break;
637754 case 4:
637755 for (ptr = begin; ptr != end; ++ptr) {
637756 U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
637757 ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
637758 ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
637759 DTableRank += 4;
637760 }
637761 break;
637762 case 8:
637763 for (ptr = begin; ptr != end; ++ptr) {
637764 U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
637765 ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
637766 ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
637767 ZSTD_memcpy(DTableRank + 4, &DEltX2, sizeof(DEltX2));
637768 ZSTD_memcpy(DTableRank + 6, &DEltX2, sizeof(DEltX2));
637769 DTableRank += 8;
637770 }
637771 break;
637772 default:
637773 for (ptr = begin; ptr != end; ++ptr) {
637774 U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
637775 HUF_DEltX2* const DTableRankEnd = DTableRank + length;
637776 for (; DTableRank != DTableRankEnd; DTableRank += 8) {
637777 ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
637778 ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
static HUF_DEltX2 HUF_buildDEltX2(U32 symbol, U32 nbBits, U32 baseSeq, int level)
Definition duckdb.cpp:637693
static U64 HUF_buildDEltX2U64(U32 symbol, U32 nbBits, U16 baseSeq, int level)
Definition duckdb.cpp:637705
static void HUF_fillDTableX2ForWeight(HUF_DEltX2 *DTableRank, sortedSymbol_t const *begin, sortedSymbol_t const *end, U32 nbBits, U32 tableLog, U16 baseSeq, int const level)
Definition duckdb.cpp:637723
Definition duckdb.cpp:637667
Here is the call graph for this function:
Here is the caller graph for this function:

◆ HUF_fillDTableX2Level2()

void duckdb_zstd::HUF_fillDTableX2Level2 ( HUF_DEltX2 * DTable,
U32 targetLog,
const U32 consumedBits,
const U32 * rankVal,
const int minWeight,
const int maxWeight1,
const sortedSymbol_t * sortedSymbols,
U32 const * rankStart,
U32 nbBitsBaseline,
U16 baseSeq )
static
637793{
637794 /* Fill skipped values (all positions up to rankVal[minWeight]).
637795 * These are positions only get a single symbol because the combined weight
637796 * is too large.
637797 */
637798 if (minWeight>1) {
637799 U32 const length = 1U << ((targetLog - consumedBits) & 0x1F /* quiet static-analyzer */);
637800 U64 const DEltX2 = HUF_buildDEltX2U64(baseSeq, consumedBits, /* baseSeq */ 0, /* level */ 1);
637801 int const skipSize = rankVal[minWeight];
637802 assert(length > 1);
637803 assert((U32)skipSize < length);
637804 switch (length) {
637805 case 2:
637806 assert(skipSize == 1);
637807 ZSTD_memcpy(DTable, &DEltX2, sizeof(DEltX2));
637808 break;
637809 case 4:
637810 assert(skipSize <= 4);
637811 ZSTD_memcpy(DTable + 0, &DEltX2, sizeof(DEltX2));
637812 ZSTD_memcpy(DTable + 2, &DEltX2, sizeof(DEltX2));
637813 break;
637814 default:
637815 {
637816 int i;
637817 for (i = 0; i < skipSize; i += 8) {
637818 ZSTD_memcpy(DTable + i + 0, &DEltX2, sizeof(DEltX2));
637819 ZSTD_memcpy(DTable + i + 2, &DEltX2, sizeof(DEltX2));
637820 ZSTD_memcpy(DTable + i + 4, &DEltX2, sizeof(DEltX2));
637821 ZSTD_memcpy(DTable + i + 6, &DEltX2, sizeof(DEltX2));
637822 }
637823 }
637824 }
637825 }
637826
637827 /* Fill each of the second level symbols by weight. */
637828 {
637829 int w;
637830 for (w = minWeight; w < maxWeight1; ++w) {
637831 int const begin = rankStart[w];
637832 int const end = rankStart[w+1];
637833 U32 const nbBits = nbBitsBaseline - w;
637834 U32 const totalBits = nbBits + consumedBits;

◆ HUF_fillDTableX2()

void duckdb_zstd::HUF_fillDTableX2 ( HUF_DEltX2 * DTable,
const U32 targetLog,
const sortedSymbol_t * sortedList,
const U32 * rankStart,
rankValCol_t * rankValOrigin,
const U32 maxWeight,
const U32 nbBitsBaseline )
static
637848{
637849 U32* const rankVal = rankValOrigin[0];
637850 const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
637851 const U32 minBits = nbBitsBaseline - maxWeight;
637852 int w;
637853 int const wEnd = (int)maxWeight + 1;
637854
637855 /* Fill DTable in order of weight. */
637856 for (w = 1; w < wEnd; ++w) {
637857 int const begin = (int)rankStart[w];
637858 int const end = (int)rankStart[w+1];
637859 U32 const nbBits = nbBitsBaseline - w;
637860
637861 if (targetLog-nbBits >= minBits) {
637862 /* Enough room for a second symbol. */
637863 int start = rankVal[w];
637864 U32 const length = 1U << ((targetLog - nbBits) & 0x1F /* quiet static-analyzer */);
637865 int minWeight = nbBits + scaleLog;
637866 int s;
637867 if (minWeight < 1) minWeight = 1;
637868 /* Fill the DTable for every symbol of weight w.
637869 * These symbols get at least 1 second symbol.
637870 */
637871 for (s = begin; s != end; ++s) {
637872 HUF_fillDTableX2Level2(
637873 DTable + start, targetLog, nbBits,
637874 rankValOrigin[nbBits], minWeight, wEnd,
637875 sortedList, rankStart,
637876 nbBitsBaseline, sortedList[s].symbol);
637877 start += length;
637878 }
637879 } else {
637880 /* Only a single symbol. */

◆ HUF_decodeSymbolX2()

FORCE_INLINE_TEMPLATE U32 duckdb_zstd::HUF_decodeSymbolX2 ( void * op,
BIT_DStream_t * DStream,
const HUF_DEltX2 * dt,
const U32 dtLog )

◆ HUF_decodeLastSymbolX2()

FORCE_INLINE_TEMPLATE U32 duckdb_zstd::HUF_decodeLastSymbolX2 ( void * op,
BIT_DStream_t * DStream,
const HUF_DEltX2 * dt,
const U32 dtLog )
637996{
637997 size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
637998 ZSTD_memcpy(op, &dt[val].sequence, 1);
637999 if (dt[val].length==1) {
638000 BIT_skipBits(DStream, dt[val].nbBits);
638001 } else {
638002 if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
638003 BIT_skipBits(DStream, dt[val].nbBits);

◆ HUF_decodeStreamX2()

HINT_INLINE size_t duckdb_zstd::HUF_decodeStreamX2 ( BYTE * p,
BIT_DStream_t * bitDPtr,
BYTE *const pEnd,
const HUF_DEltX2 *const dt,
const U32 dtLog )
638022 { \
638023 if (MEM_64bits()) \
638024 ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); \
638025 } while (0)
638026
638027HINT_INLINE size_t
638028HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd,
638029 const HUF_DEltX2* const dt, const U32 dtLog)
638030{
638031 BYTE* const pStart = p;
638032
638033 /* up to 8 symbols at a time */
638034 if ((size_t)(pEnd - p) >= sizeof(bitDPtr->bitContainer)) {
638035 if (dtLog <= 11 && MEM_64bits()) {
638036 /* up to 10 symbols at a time */
638037 while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-9)) {
638038 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638039 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638040 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638041 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638042 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638043 }
638044 } else {
638045 /* up to 8 symbols at a time */
638046 while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) {
638047 HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
638048 HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
638049 HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
638050 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638051 }
638052 }
638053 } else {
638054 BIT_reloadDStream(bitDPtr);
638055 }
638056
638057 /* closer to end : up to 2 symbols at a time */
638058 if ((size_t)(pEnd - p) >= 2) {
638059 while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2))
638060 HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
638061
638062 while (p <= pEnd-2)
638063 HUF_DECODE_SYMBOLX2_0(p, bitDPtr); /* no need to reload : reached the end of DStream */

◆ HUF_decompress1X2_usingDTable_internal_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_decompress1X2_usingDTable_internal_body ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable )
638077{
638078 BIT_DStream_t bitD;
638079
638080 /* Init */
638081 CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );
638082
638083 /* decode */
638084 { BYTE* const ostart = (BYTE*) dst;
638085 BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, dstSize);
638086 const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */
638087 const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
638088 DTableDesc const dtd = HUF_getDTableDesc(DTable);
638089 HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog);
638090 }

◆ HUF_decompress4X2_usingDTable_internal_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::HUF_decompress4X2_usingDTable_internal_body ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable )
638108{
638109 if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
638110 if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */
638111
638112 { const BYTE* const istart = (const BYTE*) cSrc;
638113 BYTE* const ostart = (BYTE*) dst;
638114 BYTE* const oend = ostart + dstSize;
638115 BYTE* const olimit = oend - (sizeof(size_t)-1);
638116 const void* const dtPtr = DTable+1;
638117 const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
638118
638119 /* Init */
638120 BIT_DStream_t bitD1;
638121 BIT_DStream_t bitD2;
638122 BIT_DStream_t bitD3;
638123 BIT_DStream_t bitD4;
638124 size_t const length1 = MEM_readLE16(istart);
638125 size_t const length2 = MEM_readLE16(istart+2);
638126 size_t const length3 = MEM_readLE16(istart+4);
638127 size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
638128 const BYTE* const istart1 = istart + 6; /* jumpTable */
638129 const BYTE* const istart2 = istart1 + length1;
638130 const BYTE* const istart3 = istart2 + length2;
638131 const BYTE* const istart4 = istart3 + length3;
638132 size_t const segmentSize = (dstSize+3) / 4;
638133 BYTE* const opStart2 = ostart + segmentSize;
638134 BYTE* const opStart3 = opStart2 + segmentSize;
638135 BYTE* const opStart4 = opStart3 + segmentSize;
638136 BYTE* op1 = ostart;
638137 BYTE* op2 = opStart2;
638138 BYTE* op3 = opStart3;
638139 BYTE* op4 = opStart4;
638140 U32 endSignal = 1;
638141 DTableDesc const dtd = HUF_getDTableDesc(DTable);
638142 U32 const dtLog = dtd.tableLog;
638143
638144 if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
638145 if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */
638146 assert(dstSize >= 6 /* validated above */);
638147 CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
638148 CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
638149 CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
638150 CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
638151
638152 /* 16-32 symbols per loop (4-8 symbols per stream) */
638153 if ((size_t)(oend - op4) >= sizeof(size_t)) {
638154 for ( ; (endSignal) & (op4 < olimit); ) {
638155#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
638156 HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
638157 HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
638158 HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
638159 HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
638160 HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
638161 HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
638162 HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
638163 HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
638164 endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
638165 endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
638166 HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
638167 HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
638168 HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
638169 HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
638170 HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
638171 HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
638172 HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
638173 HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
638174 endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
638175 endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
638176#else
638177 HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
638178 HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
638179 HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
638180 HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
638181 HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
638182 HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
638183 HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
638184 HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
638185 HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
638186 HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
638187 HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
638188 HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
638189 HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
638190 HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
638191 HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
638192 HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
638193 endSignal = (U32)LIKELY((U32)
638194 (BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished)
638195 & (BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished)
638196 & (BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished)
638197 & (BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished));
638198#endif
638199 }
638200 }
638201
638202 /* check corruption */
638203 if (op1 > opStart2) return ERROR(corruption_detected);
638204 if (op2 > opStart3) return ERROR(corruption_detected);
638205 if (op3 > opStart4) return ERROR(corruption_detected);
638206 /* note : op4 already verified within main loop */
638207
638208 /* finish bitStreams one by one */
638209 HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
638210 HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
638211 HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
638212 HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
638213
638214 /* check */

◆ HUF_decompress4X2_usingDTable_internal_default()

size_t duckdb_zstd::HUF_decompress4X2_usingDTable_internal_default ( void * dst,
size_t dstSize,
void const * cSrc,
size_t cSrcSize,
HUF_DTable const * DTable )
static
638226 {
638227 return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
638228}

◆ HUF_decompress4X2_usingDTable_internal_fast_c_loop()

HUF_FAST_BMI2_ATTRS void duckdb_zstd::HUF_decompress4X2_usingDTable_internal_fast_c_loop ( HUF_DecompressFastArgs * args)
static
638233 {
638234 return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
638235}
638236
638237static HUF_FAST_BMI2_ATTRS
638238void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args)
638239{
638240 U64 bits[4];
638241 BYTE const* ip[4];
638242 BYTE* op[4];
638243 BYTE* oend[4];
638244 HUF_DEltX2 const* const dtable = (HUF_DEltX2 const*)args->dt;
638245 BYTE const* const ilowest = args->ilowest;
638246
638247 /* Copy the arguments to local registers. */
638248 ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
638249 ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip));
638250 ZSTD_memcpy(&op, &args->op, sizeof(op));
638251
638252 oend[0] = op[1];
638253 oend[1] = op[2];
638254 oend[2] = op[3];
638255 oend[3] = args->oend;
638256
638257 assert(MEM_isLittleEndian());
638258 assert(!MEM_32bits());
638259
638260 for (;;) {
638261 BYTE* olimit;
638262 int stream;
638263
638264 /* Assert loop preconditions */
638265#ifndef NDEBUG
638266 for (stream = 0; stream < 4; ++stream) {
638267 assert(op[stream] <= oend[stream]);
638268 assert(ip[stream] >= ilowest);
638269 }
638270#endif
638271 /* Compute olimit */
638272 {
638273 /* Each loop does 5 table lookups for each of the 4 streams.
638274 * Each table lookup consumes up to 11 bits of input, and produces
638275 * up to 2 bytes of output.
638276 */
638277 /* We can consume up to 7 bytes of input per iteration per stream.
638278 * We also know that each input pointer is >= ip[0]. So we can run
638279 * iters loops before running out of input.
638280 */
638281 size_t iters = (size_t)(ip[0] - ilowest) / 7;
638282 /* Each iteration can produce up to 10 bytes of output per stream.
638283 * Each output stream my advance at different rates. So take the
638284 * minimum number of safe iterations among all the output streams.
638285 */
638286 for (stream = 0; stream < 4; ++stream) {
638287 size_t const oiters = (size_t)(oend[stream] - op[stream]) / 10;
638288 iters = MIN(iters, oiters);
638289 }
638290
638291 /* Each iteration produces at least 5 output symbols. So until
638292 * op[3] crosses olimit, we know we haven't executed iters
638293 * iterations yet. This saves us maintaining an iters counter,
638294 * at the expense of computing the remaining # of iterations
638295 * more frequently.
638296 */
638297 olimit = op[3] + (iters * 5);
638298
638299 /* Exit the fast decoding loop once we reach the end. */
638300 if (op[3] == olimit)
638301 break;
638302
638303 /* Exit the decoding loop if any input pointer has crossed the
638304 * previous one. This indicates corruption, and a precondition
638305 * to our loop is that ip[i] >= ip[0].
638306 */
638307 for (stream = 1; stream < 4; ++stream) {
638308 if (ip[stream] < ip[stream - 1])
638309 goto _out;
638310 }
638311 }
638312
638313#ifndef NDEBUG
638314 for (stream = 1; stream < 4; ++stream) {
638315 assert(ip[stream] >= ip[stream - 1]);
638316 }
638317#endif
638318
638319#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3) \
638320 do { \
638321 if ((_decode3) || (_stream) != 3) { \
638322 int const index = (int)(bits[(_stream)] >> 53); \
638323 HUF_DEltX2 const entry = dtable[index]; \
638324 MEM_write16(op[(_stream)], entry.sequence); \
638325 bits[(_stream)] <<= (entry.nbBits) & 0x3F; \
638326 op[(_stream)] += (entry.length); \
638327 } \
638328 } while (0)
638329
638330#define HUF_4X2_RELOAD_STREAM(_stream) \
638331 do { \
638332 HUF_4X2_DECODE_SYMBOL(3, 1); \
638333 { \
638334 int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
638335 int const nbBits = ctz & 7; \
638336 int const nbBytes = ctz >> 3; \
638337 ip[(_stream)] -= nbBytes; \
638338 bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \
638339 bits[(_stream)] <<= nbBits; \
638340 } \
638341 } while (0)
638342
638343 /* Manually unroll the loop because compilers don't consistently
638344 * unroll the inner loops, which destroys performance.
638345 */
638346 do {
638347 /* Decode 5 symbols from each of the first 3 streams.
638348 * The final stream will be decoded during the reload phase
638349 * to reduce register pressure.
638350 */
638351 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0);
638352 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0);
638353 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0);
638354 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0);
638355 HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0);
638356
638357 /* Decode one symbol from the final stream */
638358 HUF_4X2_DECODE_SYMBOL(3, 1);
638359
638360 /* Decode 4 symbols from the final stream & reload bitstreams.
638361 * The final stream is reloaded last, meaning that all 5 symbols
638362 * are decoded from the final stream before it is reloaded.
638363 */
638364 HUF_4X_FOR_EACH_STREAM(HUF_4X2_RELOAD_STREAM);
638365 } while (op[3] < olimit);
638366 }
638367
638368#undef HUF_4X2_DECODE_SYMBOL
638369#undef HUF_4X2_RELOAD_STREAM
638370

◆ HUF_decompress4X2_usingDTable_internal_fast()

HUF_FAST_BMI2_ATTRS size_t duckdb_zstd::HUF_decompress4X2_usingDTable_internal_fast ( void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
const HUF_DTable * DTable,
HUF_DecompressFastLoopFn loopFn )
static
638385 {
638386 void const* dt = DTable + 1;
638387 const BYTE* const ilowest = (const BYTE*)cSrc;
638388 BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
638390 {
638391 size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
638392 FORWARD_IF_ERROR(ret, "Failed to init asm args");
638393 if (ret == 0)
638394 return 0;
638395 }
638396
638397 assert(args.ip[0] >= args.ilowest);
638398 loopFn(&args);
638399
638400 /* note : op4 already verified within main loop */
638401 assert(args.ip[0] >= ilowest);
638402 assert(args.ip[1] >= ilowest);
638403 assert(args.ip[2] >= ilowest);
638404 assert(args.ip[3] >= ilowest);
638405 assert(args.op[3] <= oend);
638406
638407 assert(ilowest == args.ilowest);
638408 assert(ilowest + 6 == args.iend[0]);
638409 (void)ilowest;
638410
638411 /* finish bitStreams one by one */
638412 {
638413 size_t const segmentSize = (dstSize+3) / 4;
638414 BYTE* segmentEnd = (BYTE*)dst;
638415 int i;
638416 for (i = 0; i < 4; ++i) {
638417 BIT_DStream_t bit;
638418 if (segmentSize <= (size_t)(oend - segmentEnd))
638419 segmentEnd += segmentSize;
638420 else
638421 segmentEnd = oend;
638422 FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption");
638423 args.op[i] += HUF_decodeStreamX2(args.op[i], &bit, segmentEnd, (HUF_DEltX2 const*)dt, HUF_DECODER_FAST_TABLELOG);
638424 if (args.op[i] != segmentEnd)

◆ HUF_decompress4X2_usingDTable_internal()

size_t duckdb_zstd::HUF_decompress4X2_usingDTable_internal ( void * dst,
size_t dstSize,
void const * cSrc,
size_t cSrcSize,
HUF_DTable const * DTable,
int flags )
static
638435{
638436 HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X2_usingDTable_internal_default;
638437 HUF_DecompressFastLoopFn loopFn = HUF_decompress4X2_usingDTable_internal_fast_c_loop;
638438
638439#if DYNAMIC_BMI2
638440 if (flags & HUF_flags_bmi2) {
638441 fallbackFn = HUF_decompress4X2_usingDTable_internal_bmi2;
638442 } else {
638443 return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
638444 }
638445#endif
638446

◆ HUF_decompress4X2_DCtx_wksp()

size_t duckdb_zstd::HUF_decompress4X2_DCtx_wksp ( HUF_DTable * dctx,
void * dst,
size_t dstSize,
const void * cSrc,
size_t cSrcSize,
void * workSpace,
size_t wkspSize,
int flags )
static
638475{
638476 const BYTE* ip = (const BYTE*) cSrc;
638477
638478 size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize,

◆ ZSTD_DCtx_get_bmi2()

MEM_STATIC int duckdb_zstd::ZSTD_DCtx_get_bmi2 ( const struct ZSTD_DCtx_s * dctx)
638900 {

◆ ZSTD_loadDEntropy()

size_t duckdb_zstd::ZSTD_loadDEntropy ( ZSTD_entropyDTables_t * entropy,
const void *const dict,
size_t const dictSize )

ZSTD_loadDEntropy() : dict : must point at beginning of a valid zstd dictionary.

Returns
: size of dictionary header (size of magic number + dict ID + entropy tables)

ZSTD_loadDEntropy() : dict : must point at beginning of a valid zstd dictionary.

Returns
: size of entropy tables read
640755{
640756 const BYTE* dictPtr = (const BYTE*)dict;
640757 const BYTE* const dictEnd = dictPtr + dictSize;
640758
640759 RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small");
640760 assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */
640761 dictPtr += 8; /* skip header = magic + dictID */
640762
640763 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
640764 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
640765 ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
640766 { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */
640767 size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
640768#ifdef HUF_FORCE_DECOMPRESS_X1
640769 /* in minimal huffman, we always use X1 variants */
640770 size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
640771 dictPtr, dictEnd - dictPtr,
640772 workspace, workspaceSize, /* flags */ 0);
640773#else
640774 size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
640775 dictPtr, (size_t)(dictEnd - dictPtr),
640776 workspace, workspaceSize, /* flags */ 0);
640777#endif
640778 RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, "");
640779 dictPtr += hSize;
640780 }
640781
640782 { short offcodeNCount[MaxOff+1];
640783 unsigned offcodeMaxValue = MaxOff, offcodeLog;
640784 size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr));
640785 RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
640786 RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, "");
640787 RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
640788 ZSTD_buildFSETable( entropy->OFTable,
640789 offcodeNCount, offcodeMaxValue,
640790 OF_base, OF_bits,
640791 offcodeLog,
640792 entropy->workspace, sizeof(entropy->workspace),
640793 /* bmi2 */0);
640794 dictPtr += offcodeHeaderSize;
640795 }
640796
640797 { short matchlengthNCount[MaxML+1];
640798 unsigned matchlengthMaxValue = MaxML, matchlengthLog;
640799 size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
640800 RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
640801 RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, "");
640802 RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
640803 ZSTD_buildFSETable( entropy->MLTable,
640804 matchlengthNCount, matchlengthMaxValue,
640805 ML_base, ML_bits,
640806 matchlengthLog,
640807 entropy->workspace, sizeof(entropy->workspace),
640808 /* bmi2 */ 0);
640809 dictPtr += matchlengthHeaderSize;
640810 }
640811
640812 { short litlengthNCount[MaxLL+1];
640813 unsigned litlengthMaxValue = MaxLL, litlengthLog;
640814 size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
640815 RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
640816 RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, "");
640817 RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
640818 ZSTD_buildFSETable( entropy->LLTable,
640819 litlengthNCount, litlengthMaxValue,
640820 LL_base, LL_bits,
640821 litlengthLog,
640822 entropy->workspace, sizeof(entropy->workspace),
640823 /* bmi2 */ 0);
640824 dictPtr += litlengthHeaderSize;
640825 }
640826
640827 RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
640828 { int i;
640829 size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
640830 for (i=0; i<3; i++) {
640831 U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
Definition duckdb.cpp:638760

◆ ZSTD_checkContinuity()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void duckdb_zstd::ZSTD_checkContinuity ( ZSTD_DCtx * dctx,
const void * dst,
size_t dstSize )

ZSTD_checkContinuity() : check if next dst follows previous position, where decompression ended. If yes, do nothing (continue on current segment). If not, classify previous segment as "external dictionary", and start a new segment. This function cannot fail.

643907{
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_DDict_dictContent()

const void * duckdb_zstd::ZSTD_DDict_dictContent ( const ZSTD_DDict * ddict)

◆ ZSTD_DDict_dictSize()

size_t duckdb_zstd::ZSTD_DDict_dictSize ( const ZSTD_DDict * ddict)
639009{
639010 assert(ddict != NULL);
639011 return ddict->dictContent;

◆ ZSTD_copyDDictParameters()

void duckdb_zstd::ZSTD_copyDDictParameters ( ZSTD_DCtx * dctx,
const ZSTD_DDict * ddict )
639015{
639016 assert(ddict != NULL);
639017 return ddict->dictSize;
639018}
639019
639020void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
639021{
639022 DEBUGLOG(4, "ZSTD_copyDDictParameters");
639023 assert(dctx != NULL);
639024 assert(ddict != NULL);
639025 dctx->dictID = ddict->dictID;
639026 dctx->prefixStart = ddict->dictContent;
639027 dctx->virtualStart = ddict->dictContent;
639028 dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize;
639029 dctx->previousDstEnd = dctx->dictEnd;
639030#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
639031 dctx->dictContentBeginForFuzzing = dctx->prefixStart;
639032 dctx->dictContentEndForFuzzing = dctx->previousDstEnd;
639033#endif
639034 if (ddict->entropyPresent) {
639035 dctx->litEntropy = 1;
639036 dctx->fseEntropy = 1;
639037 dctx->LLTptr = ddict->entropy.LLTable;
639038 dctx->MLTptr = ddict->entropy.MLTable;
639039 dctx->OFTptr = ddict->entropy.OFTable;
639040 dctx->HUFptr = ddict->entropy.hufTable;
639041 dctx->entropy.rep[0] = ddict->entropy.rep[0];

◆ ZSTD_loadEntropy_intoDDict()

size_t duckdb_zstd::ZSTD_loadEntropy_intoDDict ( ZSTD_DDict * ddict,
ZSTD_dictContentType_e dictContentType )
static
639054{
639055 ddict->dictID = 0;
639056 ddict->entropyPresent = 0;
639057 if (dictContentType == ZSTD_dct_rawContent) return 0;
639058
639059 if (ddict->dictSize < 8) {
639060 if (dictContentType == ZSTD_dct_fullDict)
639061 return ERROR(dictionary_corrupted); /* only accept specified dictionaries */
639062 return 0; /* pure content mode */
639063 }
639064 { U32 const magic = MEM_readLE32(ddict->dictContent);
639065 if (magic != ZSTD_MAGIC_DICTIONARY) {
639066 if (dictContentType == ZSTD_dct_fullDict)
639067 return ERROR(dictionary_corrupted); /* only accept specified dictionaries */
639068 return 0; /* pure content mode */
639069 }
639070 }
639071 ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE);
639072

◆ ZSTD_initDDict_internal()

size_t duckdb_zstd::ZSTD_initDDict_internal ( ZSTD_DDict * ddict,
const void * dict,
size_t dictSize,
ZSTD_dictLoadMethod_e dictLoadMethod,
ZSTD_dictContentType_e dictContentType )
static
639086{
639087 if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) {
639088 ddict->dictBuffer = NULL;
639089 ddict->dictContent = dict;
639090 if (!dict) dictSize = 0;
639091 } else {
639092 void* const internalBuffer = ZSTD_customMalloc(dictSize, ddict->cMem);
639093 ddict->dictBuffer = internalBuffer;
639094 ddict->dictContent = internalBuffer;
639095 if (!internalBuffer) return ERROR(memory_allocation);
639096 ZSTD_memcpy(internalBuffer, dict, dictSize);
639097 }
639098 ddict->dictSize = dictSize;

◆ ZSTD_decompressBlock_internal()

size_t duckdb_zstd::ZSTD_decompressBlock_internal ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const streaming_operation streaming )
643797{ /* blockType == blockCompressed */
643798 const BYTE* ip = (const BYTE*)src;
643799 DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize);
643800
643801 /* Note : the wording of the specification
643802 * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx).
643803 * This generally does not happen, as it makes little sense,
643804 * since an uncompressed block would feature same size and have no decompression cost.
643805 * Also, note that decoder from reference libzstd before < v1.5.4
643806 * would consider this edge case as an error.
643807 * As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx)
643808 * for broader compatibility with the deployed ecosystem of zstd decoders */
643809 RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, "");
643810
643811 /* Decode literals section */
643812 { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming);
643813 DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize);
643814 if (ZSTD_isError(litCSize)) return litCSize;
643815 ip += litCSize;
643816 srcSize -= litCSize;
643817 }
643818
643819 /* Build Decoding Tables */
643820 {
643821 /* Compute the maximum block size, which must also work when !frame and fParams are unset.
643822 * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t.
643823 */
643824 size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx));
643825 size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd((BYTE*)dst, blockSizeMax), (BYTE const*)dctx->virtualStart);
643826 /* isLongOffset must be true if there are long offsets.
643827 * Offsets are long if they are larger than ZSTD_maxShortOffset().
643828 * We don't expect that to be the case in 64-bit mode.
643829 *
643830 * We check here to see if our history is large enough to allow long offsets.
643831 * If it isn't, then we can't possible have (valid) long offsets. If the offset
643832 * is invalid, then it is okay to read it incorrectly.
643833 *
643834 * If isLongOffsets is true, then we will later check our decoding table to see
643835 * if it is even possible to generate long offsets.
643836 */
643837 ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset()));
643838 /* These macros control at build-time which decompressor implementation
643839 * we use. If neither is defined, we do some inspection and dispatch at
643840 * runtime.
643841 */
643842#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
643843 !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
643844 int usePrefetchDecoder = dctx->ddictIsCold;
643845#else
643846 /* Set to 1 to avoid computing offset info if we don't need to.
643847 * Otherwise this value is ignored.
643848 */
643849 int usePrefetchDecoder = 1;
643850#endif
643851 int nbSeq;
643852 size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
643853 if (ZSTD_isError(seqHSize)) return seqHSize;
643854 ip += seqHSize;
643855 srcSize -= seqHSize;
643856
643857 RETURN_ERROR_IF((dst == NULL || dstCapacity == 0) && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
643858 RETURN_ERROR_IF(MEM_64bits() && sizeof(size_t) == sizeof(void*) && (size_t)(-1) - (size_t)dst < (size_t)(1 << 20), dstSize_tooSmall,
643859 "invalid dst");
643860
643861 /* If we could potentially have long offsets, or we might want to use the prefetch decoder,
643862 * compute information about the share of long offsets, and the maximum nbAdditionalBits.
643863 * NOTE: could probably use a larger nbSeq limit
643864 */
643865 if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) {
643866 ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq);
643867 if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) {
643868 /* If isLongOffset, but the maximum number of additional bits that we see in our table is small
643869 * enough, then we know it is impossible to have too long an offset in this block, so we can
643870 * use the regular offset decoder.
643871 */
643872 isLongOffset = ZSTD_lo_isRegularOffset;
643873 }
643874 if (!usePrefetchDecoder) {
643875 U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
643876 usePrefetchDecoder = (info.longOffsetShare >= minShare);
643877 }
643878 }
643879
643880 dctx->ddictIsCold = 0;
643881
643882#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
643883 !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
643884 if (usePrefetchDecoder) {
643885#else
643886 (void)usePrefetchDecoder;
643887 {
643888#endif
643889#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
643890 return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
643891#endif
643892 }
643893
643894#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
643895 /* else */
static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx *dctx, const void *src, size_t srcSize, void *dst, size_t dstCapacity, const streaming_operation streaming)
Definition duckdb.cpp:641849
static size_t ZSTD_totalHistorySize(BYTE *op, BYTE const *virtualStart)
Definition duckdb.cpp:643717
static size_t ZSTD_maxShortOffset(void)
Definition duckdb.cpp:643766

◆ ZSTD_buildFSETable()

void duckdb_zstd::ZSTD_buildFSETable ( ZSTD_seqSymbol * dt,
const short * normalizedCounter,
unsigned maxSymbolValue,
const U32 * baseValue,
const U8 * nbAdditionalBits,
unsigned tableLog,
void * wksp,
size_t wkspSize,
int bmi2 )
642342{
642343 ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
642344 baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
642345}
642346#endif
642347
642348void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
642349 const short* normalizedCounter, unsigned maxSymbolValue,
642350 const U32* baseValue, const U8* nbAdditionalBits,
642351 unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)
642352{
642353#if DYNAMIC_BMI2
642354 if (bmi2) {
642355 ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,
642356 baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);

◆ ZSTD_decompressBlock_deprecated()

size_t duckdb_zstd::ZSTD_decompressBlock_deprecated ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
643920{
643921 size_t dSize;

◆ ZSTD_DDictHashSet_getIndex()

size_t duckdb_zstd::ZSTD_DDictHashSet_getIndex ( const ZSTD_DDictHashSet * hashSet,
U32 dictID )
static
639393 {
639394
639395/* Hash function to determine starting position of dict insertion within the table

◆ ZSTD_DDictHashSet_emplaceDDict()

size_t duckdb_zstd::ZSTD_DDictHashSet_emplaceDDict ( ZSTD_DDictHashSet * hashSet,
const ZSTD_DDict * ddict )
static
639408 {
639409 const U32 dictID = ZSTD_getDictID_fromDDict(ddict);
639410 size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
639411 const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1;
639412 RETURN_ERROR_IF(hashSet->ddictPtrCount == hashSet->ddictPtrTableSize, GENERIC, "Hash set is full!");
639413 DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx);
639414 while (hashSet->ddictPtrTable[idx] != NULL) {
639415 /* Replace existing ddict if inserting ddict with same dictID */
639416 if (ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]) == dictID) {
639417 DEBUGLOG(4, "DictID already exists, replacing rather than adding");
639418 hashSet->ddictPtrTable[idx] = ddict;
639419 return 0;
639420 }
639421 idx &= idxRangeMask;
ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict *ddict)
Definition duckdb.cpp:639195

◆ ZSTD_DDictHashSet_expand()

size_t duckdb_zstd::ZSTD_DDictHashSet_expand ( ZSTD_DDictHashSet * hashSet,
ZSTD_customMem customMem )
static
639434 {
639435 size_t newTableSize = hashSet->ddictPtrTableSize * DDICT_HASHSET_RESIZE_FACTOR;
639436 const ZSTD_DDict** newTable = (const ZSTD_DDict**)ZSTD_customCalloc(sizeof(ZSTD_DDict*) * newTableSize, customMem);
639437 const ZSTD_DDict** oldTable = hashSet->ddictPtrTable;
639438 size_t oldTableSize = hashSet->ddictPtrTableSize;
639439 size_t i;
639440
639441 DEBUGLOG(4, "Expanding DDict hash table! Old size: %zu new size: %zu", oldTableSize, newTableSize);
639442 RETURN_ERROR_IF(!newTable, memory_allocation, "Expanded hashset allocation failed!");
639443 hashSet->ddictPtrTable = newTable;
639444 hashSet->ddictPtrTableSize = newTableSize;
639445 hashSet->ddictPtrCount = 0;
639446 for (i = 0; i < oldTableSize; ++i) {
639447 if (oldTable[i] != NULL) {

◆ ZSTD_DDictHashSet_getDDict()

const ZSTD_DDict * duckdb_zstd::ZSTD_DDictHashSet_getDDict ( ZSTD_DDictHashSet * hashSet,
U32 dictID )
static
639459 {
639460 size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
639461 const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1;
639462 DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx);
639463 for (;;) {
639464 size_t currDictID = ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]);
639465 if (currDictID == dictID || currDictID == 0) {
639466 /* currDictID == 0 implies a NULL ddict entry */
639467 break;
639468 } else {

◆ ZSTD_createDDictHashSet()

ZSTD_DDictHashSet * duckdb_zstd::ZSTD_createDDictHashSet ( ZSTD_customMem customMem)
static
639481 {
639482 ZSTD_DDictHashSet* ret = (ZSTD_DDictHashSet*)ZSTD_customMalloc(sizeof(ZSTD_DDictHashSet), customMem);
639483 DEBUGLOG(4, "Allocating new hash set");
639484 if (!ret)
639485 return NULL;
639486 ret->ddictPtrTable = (const ZSTD_DDict**)ZSTD_customCalloc(DDICT_HASHSET_TABLE_BASE_SIZE * sizeof(ZSTD_DDict*), customMem);
639487 if (!ret->ddictPtrTable) {
Definition duckdb.cpp:638784

◆ ZSTD_freeDDictHashSet()

void duckdb_zstd::ZSTD_freeDDictHashSet ( ZSTD_DDictHashSet * hashSet,
ZSTD_customMem customMem )
static
639499 {
639500 DEBUGLOG(4, "Freeing ddict hash set");

◆ ZSTD_DDictHashSet_addDDict()

size_t duckdb_zstd::ZSTD_DDictHashSet_addDDict ( ZSTD_DDictHashSet * hashSet,
const ZSTD_DDict * ddict,
ZSTD_customMem customMem )
static
639512 {

◆ ZSTD_startingInputLength()

size_t duckdb_zstd::ZSTD_startingInputLength ( ZSTD_format_e format)
static
639532 { return sizeof(ZSTD_DCtx); }
639533
639534

◆ ZSTD_DCtx_resetParameters()

void duckdb_zstd::ZSTD_DCtx_resetParameters ( ZSTD_DCtx * dctx)
static
639536{
639537 size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format);
639538 /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
639539 assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
639540 return startingInputLength;
639541}
639542
639543static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx)
639544{
639545 assert(dctx->streamStage == zdss_init);
639546 dctx->format = ZSTD_f_zstd1;
#define ZSTD_FRAMEHEADERSIZE_PREFIX(format)
Definition duckdb.cpp:408351

◆ ZSTD_initDCtx_internal()

void duckdb_zstd::ZSTD_initDCtx_internal ( ZSTD_DCtx * dctx)
static
639556{
639557 dctx->staticSize = 0;
639558 dctx->ddict = NULL;
639559 dctx->ddictLocal = NULL;
639560 dctx->dictEnd = NULL;
639561 dctx->ddictIsCold = 0;
639562 dctx->dictUses = ZSTD_dont_use;
639563 dctx->inBuff = NULL;
639564 dctx->inBuffSize = 0;
639565 dctx->outBuffSize = 0;
639566 dctx->streamStage = zdss_init;
639567#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
639568 dctx->legacyContext = NULL;
639569 dctx->previousLegacyVersion = 0;
639570#endif
639571 dctx->noForwardProgress = 0;
639572 dctx->oversizedDuration = 0;
639573 dctx->isFrameDecompression = 1;
639574#if DYNAMIC_BMI2
639575 dctx->bmi2 = ZSTD_cpuSupportsBmi2();
MEM_STATIC int ZSTD_cpuSupportsBmi2(void)
Definition duckdb.cpp:614296

◆ ZSTD_createDCtx_internal()

ZSTD_DCtx * duckdb_zstd::ZSTD_createDCtx_internal ( ZSTD_customMem customMem)
static
639597 {
639598 if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
639599

◆ ZSTD_clearDict()

void duckdb_zstd::ZSTD_clearDict ( ZSTD_DCtx * dctx)
static
639614{
639615 DEBUGLOG(3, "ZSTD_createDCtx");
639616 return ZSTD_createDCtx_internal(ZSTD_defaultCMem);
639617}
639618

◆ ZSTD_DCtx_selectFrameDDict()

void duckdb_zstd::ZSTD_DCtx_selectFrameDDict ( ZSTD_DCtx * dctx)
static
639663 {
639664 assert(dctx->refMultipleDDicts && dctx->ddictSet);
639665 DEBUGLOG(4, "Adjusting DDict based on requested dict ID from frame");
639666 if (dctx->ddict) {
639667 const ZSTD_DDict* frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dctx->fParams.dictID);
639668 if (frameDDict) {
639669 DEBUGLOG(4, "DDict found!");

◆ ZSTD_frameHeaderSize_internal()

size_t duckdb_zstd::ZSTD_frameHeaderSize_internal ( const void * src,
size_t srcSize,
ZSTD_format_e format )
static

ZSTD_frameHeaderSize_internal() : srcSize must be large enough to reach header size fields. note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.

Returns
: size of the Frame Header or an error code, which can be tested with ZSTD_isError()
639720{
639721 size_t const minInputSize = ZSTD_startingInputLength(format);
639722 RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, "");
639723
639724 { BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
639725 U32 const dictID= fhd & 3;
Here is the caller graph for this function:

◆ readSkippableFrameSize()

size_t duckdb_zstd::readSkippableFrameSize ( void const * src,
size_t srcSize )
static
639881 {
639882 return 0;
639883 } else {
639884 return zfh.frameContentSize;
639885 } }
639886}
639887
639888static size_t readSkippableFrameSize(void const* src, size_t srcSize)
639889{
639890 size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
639891 U32 sizeU32;
639892
639893 RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, "");
639894
639895 sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);

◆ ZSTD_decodeFrameHeader()

size_t duckdb_zstd::ZSTD_decodeFrameHeader ( ZSTD_DCtx * dctx,
const void * src,
size_t headerSize )
static

ZSTD_decodeFrameHeader() : headerSize must be the size provided by ZSTD_frameHeaderSize(). If multiple DDict references are enabled, also will choose the correct DDict to use.

Returns
: 0 if success, or an error code, which can be tested using ZSTD_isError()
640004{
640005 size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
640006 if (ZSTD_isError(result)) return result; /* invalid header */
640007 RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small");
640008
640009 /* Reference DDict requested by frame if dctx references multiple ddicts */
640010 if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts && dctx->ddictSet) {
640011 ZSTD_DCtx_selectFrameDDict(dctx);
640012 }
640013
640014#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
640015 /* Skip the dictID check in fuzzing mode, because it makes the search
640016 * harder.
640017 */
640018 RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID),
Here is the caller graph for this function:

◆ ZSTD_errorFrameSizeInfo()

ZSTD_frameSizeInfo duckdb_zstd::ZSTD_errorFrameSizeInfo ( size_t ret)
static
640021 : 0;
640022 if (dctx->validateChecksum) XXH64_reset(&dctx->xxhState, 0);
640023 dctx->processedCSize += headerSize;
640024 return 0;
640025}
640026

◆ ZSTD_findFrameSizeInfo()

ZSTD_frameSizeInfo duckdb_zstd::ZSTD_findFrameSizeInfo ( const void * src,
size_t srcSize,
ZSTD_format_e format )
static
640028{
640029 ZSTD_frameSizeInfo frameSizeInfo;
640030 frameSizeInfo.compressedSize = ret;
640031 frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
640032 return frameSizeInfo;
640033}
640034
640035static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize, ZSTD_format_e format)
640036{
640037 ZSTD_frameSizeInfo frameSizeInfo;
640038 ZSTD_memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo));
640039
640040#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
640041 if (format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize))
640042 return ZSTD_findFrameSizeInfoLegacy(src, srcSize);
640043#endif
640044
640045 if (format == ZSTD_f_zstd1 && (srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
640046 && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
640047 frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize);
640048 assert(ZSTD_isError(frameSizeInfo.compressedSize) ||
640049 frameSizeInfo.compressedSize <= srcSize);
640050 return frameSizeInfo;
640051 } else {
640052 const BYTE* ip = (const BYTE*)src;
640053 const BYTE* const ipstart = ip;
640054 size_t remainingSize = srcSize;
640055 size_t nbBlocks = 0;
640056 ZSTD_frameHeader zfh;
640057
640058 /* Extract Frame Header */
640059 { size_t const ret = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, format);
640060 if (ZSTD_isError(ret))
640061 return ZSTD_errorFrameSizeInfo(ret);
640062 if (ret > 0)
640063 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
640064 }
640065
640066 ip += zfh.headerSize;
640067 remainingSize -= zfh.headerSize;
640068
640069 /* Iterate over each block */
640070 while (1) {
640071 blockProperties_t blockProperties;
640072 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
640073 if (ZSTD_isError(cBlockSize))
640074 return ZSTD_errorFrameSizeInfo(cBlockSize);
640075
640076 if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
640077 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
640078
640079 ip += ZSTD_blockHeaderSize + cBlockSize;
640080 remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
640081 nbBlocks++;
640082
640083 if (blockProperties.lastBlock) break;
640084 }
640085
640086 /* Final frame content checksum */
640087 if (zfh.checksumFlag) {
640088 if (remainingSize < 4)
640089 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
640090 ip += 4;
640091 }
640092
640093 frameSizeInfo.nbBlocks = nbBlocks;
Definition duckdb.cpp:614275

◆ ZSTD_findFrameCompressedSize_advanced()

size_t duckdb_zstd::ZSTD_findFrameCompressedSize_advanced ( const void * src,
size_t srcSize,
ZSTD_format_e format )
static
640097 : (unsigned long long)nbBlocks * zfh.blockSizeMax;
640098 return frameSizeInfo;

◆ ZSTD_copyRawBlock()

size_t duckdb_zstd::ZSTD_copyRawBlock ( void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize )
static
640190 : %u bytes", (unsigned)blockSize);
640191 ZSTD_checkContinuity(dctx, blockStart, blockSize);
640192 dctx->previousDstEnd = (const char*)blockStart + blockSize;
640193 return blockSize;
640194}
640195
640196
640197static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
640198 const void* src, size_t srcSize)
640199{
640200 DEBUGLOG(5, "ZSTD_copyRawBlock");
640201 RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, "");

◆ ZSTD_setRleBlock()

size_t duckdb_zstd::ZSTD_setRleBlock ( void * dst,
size_t dstCapacity,
BYTE b,
size_t regenSize )
static
640213{
640214 RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, "");

◆ ZSTD_DCtx_trace_end()

void duckdb_zstd::ZSTD_DCtx_trace_end ( ZSTD_DCtx const * dctx,
U64 uncompressedSize,
U64 compressedSize,
unsigned streaming )
static
640224{
640225#if ZSTD_TRACE
640226 if (dctx->traceCtx && ZSTD_trace_decompress_end != NULL) {
640227 ZSTD_Trace trace;
640228 ZSTD_memset(&trace, 0, sizeof(trace));
640229 trace.version = ZSTD_VERSION_NUMBER;
640230 trace.streaming = streaming;
640231 if (dctx->ddict) {
640232 trace.dictionaryID = ZSTD_getDictID_fromDDict(dctx->ddict);
640233 trace.dictionarySize = ZSTD_DDict_dictSize(dctx->ddict);
640234 trace.dictionaryIsCold = dctx->ddictIsCold;
640235 }
640236 trace.uncompressedSize = (size_t)uncompressedSize;
640237 trace.compressedSize = (size_t)compressedSize;
640238 trace.dctx = dctx;
640239 ZSTD_trace_decompress_end(dctx->traceCtx, &trace);
640240 }

◆ ZSTD_decompressFrame()

size_t duckdb_zstd::ZSTD_decompressFrame ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void ** srcPtr,
size_t * srcSizePtr )
static

ZSTD_decompressFrame() : @dctx must be properly initialized will update *srcPtr and *srcSizePtr, to make *srcPtr progress by one frame.

640257{
640258 const BYTE* const istart = (const BYTE*)(*srcPtr);
640259 const BYTE* ip = istart;
640260 BYTE* const ostart = (BYTE*)dst;
640261 BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart;
640262 BYTE* op = ostart;
640263 size_t remainingSrcSize = *srcSizePtr;
640264
640265 DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);
640266
640267 /* check */
640269 remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize,
640270 srcSize_wrong, "");
640271
640272 /* Frame Header */
640273 { size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal(
640274 ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format);
640275 if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
640276 RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize,
640277 srcSize_wrong, "");
640278 FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , "");
640279 ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
640280 }
640281
640282 /* Shrink the blockSizeMax if enabled */
640283 if (dctx->maxBlockSizeParam != 0)
640284 dctx->fParams.blockSizeMax = MIN(dctx->fParams.blockSizeMax, (unsigned)dctx->maxBlockSizeParam);
640285
640286 /* Loop on each block */
640287 while (1) {
640288 BYTE* oBlockEnd = oend;
640289 size_t decodedSize;
640290 blockProperties_t blockProperties;
640291 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
640292 if (ZSTD_isError(cBlockSize)) return cBlockSize;
640293
640294 ip += ZSTD_blockHeaderSize;
640295 remainingSrcSize -= ZSTD_blockHeaderSize;
640296 RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, "");
640297
640298 if (ip >= op && ip < oBlockEnd) {
640299 /* We are decompressing in-place. Limit the output pointer so that we
640300 * don't overwrite the block that we are currently reading. This will
640301 * fail decompression if the input & output pointers aren't spaced
640302 * far enough apart.
640303 *
640304 * This is important to set, even when the pointers are far enough
640305 * apart, because ZSTD_decompressBlock_internal() can decide to store
640306 * literals in the output buffer, after the block it is decompressing.
640307 * Since we don't want anything to overwrite our input, we have to tell
640308 * ZSTD_decompressBlock_internal to never write past ip.
640309 *
640310 * See ZSTD_allocateLiteralsBuffer() for reference.
640311 */
640312 oBlockEnd = op + (ip - op);
640313 }
640314
640315 switch(blockProperties.blockType)
640316 {
640317 case bt_compressed:
640318 assert(dctx->isFrameDecompression == 1);
640319 decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oBlockEnd-op), ip, cBlockSize, not_streaming);
640320 break;
640321 case bt_raw :
640322 /* Use oend instead of oBlockEnd because this function is safe to overlap. It uses memmove. */
640323 decodedSize = ZSTD_copyRawBlock(op, (size_t)(oend-op), ip, cBlockSize);
640324 break;
640325 case bt_rle :
640326 decodedSize = ZSTD_setRleBlock(op, (size_t)(oBlockEnd-op), *ip, blockProperties.origSize);
640327 break;
640328 case bt_reserved :
640329 default:
640330 RETURN_ERROR(corruption_detected, "invalid block type");
640331 }
640332 FORWARD_IF_ERROR(decodedSize, "Block decompression failure");
640333 DEBUGLOG(5, "Decompressed block of dSize = %u", (unsigned)decodedSize);
640334 if (dctx->validateChecksum) {
640335 XXH64_update(&dctx->xxhState, op, decodedSize);
640336 }
640337 if (decodedSize) /* support dst = NULL,0 */ {
640338 op += decodedSize;
640339 }
640340 assert(ip != NULL);
640341 ip += cBlockSize;
640342 remainingSrcSize -= cBlockSize;
640343 if (blockProperties.lastBlock) break;
640344 }
640345
640346 if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
640347 RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize,
640348 corruption_detected, "");
640349 }
640350 if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
640351 RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, "");
640352 if (!dctx->forceIgnoreChecksum) {
640353 U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
640354 U32 checkRead;
640355 checkRead = MEM_readLE32(ip);
640356 RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, "");
640357 }
640358 ip += 4;
640359 remainingSrcSize -= 4;
640360 }

◆ ZSTD_decompressMultiFrame()

ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_decompressMultiFrame ( ZSTD_DCtx * dctx,
void * dst,
size_t dstCapacity,
const void * src,
size_t srcSize,
const void * dict,
size_t dictSize,
const ZSTD_DDict * ddict )
static
640376{
640377 void* const dststart = dst;
640378 int moreThan1Frame = 0;
640379
640380 DEBUGLOG(5, "ZSTD_decompressMultiFrame");
640381 assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */
640382
640383 if (ddict) {
640384 dict = ZSTD_DDict_dictContent(ddict);
640385 dictSize = ZSTD_DDict_dictSize(ddict);
640386 }
640387
640388 while (srcSize >= ZSTD_startingInputLength(dctx->format)) {
640389
640390#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
640391 if (dctx->format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) {
640392 size_t decodedSize;
640393 size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
640394 if (ZSTD_isError(frameSize)) return frameSize;
640395 RETURN_ERROR_IF(dctx->staticSize, memory_allocation,
640396 "legacy support is not compatible with static dctx");
640397
640398 decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
640399 if (ZSTD_isError(decodedSize)) return decodedSize;
640400
640401 {
640402 unsigned long long const expectedSize = ZSTD_getFrameContentSize(src, srcSize);
640403 RETURN_ERROR_IF(expectedSize == ZSTD_CONTENTSIZE_ERROR, corruption_detected, "Corrupted frame header!");
640404 if (expectedSize != ZSTD_CONTENTSIZE_UNKNOWN) {
640405 RETURN_ERROR_IF(expectedSize != decodedSize, corruption_detected,
640406 "Frame header size does not match decoded size!");
640407 }
640408 }
640409
640410 assert(decodedSize <= dstCapacity);
640411 dst = (BYTE*)dst + decodedSize;
640412 dstCapacity -= decodedSize;
640413
640414 src = (const BYTE*)src + frameSize;
640415 srcSize -= frameSize;
640416
640417 continue;
640418 }
640419#endif
640420
640421 if (dctx->format == ZSTD_f_zstd1 && srcSize >= 4) {
640422 U32 const magicNumber = MEM_readLE32(src);
640423 DEBUGLOG(5, "reading magic number %08X", (unsigned)magicNumber);
640424 if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
640425 /* skippable frame detected : skip it */
640426 size_t const skippableSize = readSkippableFrameSize(src, srcSize);
640427 FORWARD_IF_ERROR(skippableSize, "invalid skippable frame");
640428 assert(skippableSize <= srcSize);
640429
640430 src = (const BYTE *)src + skippableSize;
640431 srcSize -= skippableSize;
640432 continue; /* check next frame */
640433 } }
640434
640435 if (ddict) {
640436 /* we were called from ZSTD_decompress_usingDDict */
640437 FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), "");
640438 } else {
640439 /* this will initialize correctly with no dict if dict == NULL, so
640440 * use this in all cases but ddict */
640441 FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), "");
640442 }
640443 ZSTD_checkContinuity(dctx, dst, dstCapacity);
640444
640445 { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
640446 &src, &srcSize);
640448 (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
640449 && (moreThan1Frame==1),
640450 srcSize_wrong,
640451 "At least one frame successfully completed, "
640452 "but following bytes are garbage: "
640453 "it's more likely to be a srcSize error, "
640454 "specifying more input bytes than size of frame(s). "
640455 "Note: one could be unlucky, it might be a corruption error instead, "
640456 "happening right at the place where we expect zstd magic bytes. "
640457 "But this is _much_ less likely than a srcSize field error.");
640458 if (ZSTD_isError(res)) return res;
640459 assert(res <= dstCapacity);
640460 if (res != 0)
640461 dst = (BYTE*)dst + res;
640462 dstCapacity -= res;
640463 }
ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult)
Definition duckdb.cpp:614335
void ZSTD_checkContinuity(ZSTD_DCtx *dctx, const void *dst, size_t dstSize)
Definition duckdb.cpp:643899
static size_t ZSTD_decompressFrame(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void **srcPtr, size_t *srcSizePtr)
Definition duckdb.cpp:640247

◆ ZSTD_getDDict()

ZSTD_DDict const * duckdb_zstd::ZSTD_getDDict ( ZSTD_DCtx * dctx)
static
640476{
640477 return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
640478}
640479
640480
640481static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx)
640482{
640483 switch (dctx->dictUses) {
640484 default:
640485 assert(0 /* Impossible */);
640486 ZSTD_FALLTHROUGH;
640487 case ZSTD_dont_use:
640488 ZSTD_clearDict(dctx);
640489 return NULL;

◆ ZSTD_nextSrcSizeToDecompressWithInputSize()

size_t duckdb_zstd::ZSTD_nextSrcSizeToDecompressWithInputSize ( ZSTD_DCtx * dctx,
size_t inputSize )
static

Similar to ZSTD_nextSrcSizeToDecompress(), but when a block input can be streamed, we allow taking a partial block as the input. Currently only raw uncompressed blocks can be streamed.

For blocks that can be streamed, this allows us to reduce the latency until we produce output, and avoid copying the input.

Parameters
inputSize- The total amount of input that the caller currently has.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_isSkipFrame()

int duckdb_zstd::ZSTD_isSkipFrame ( ZSTD_DCtx * dctx)
static
640563:
640564

◆ RETURN_ERROR_IF()

duckdb_zstd::RETURN_ERROR_IF ( srcSize ! = ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize),
srcSize_wrong ,
"not allowed"  )

ZSTD_decompressContinue() : srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())

Returns
: nb of bytes generated into dst (necessarily <= `dstCapacity) or an error code, which can be tested using ZSTD_isError() */ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); /* Sanity check
Here is the call graph for this function:

◆ switch()

duckdb_zstd::switch ( dctx-> stage)
640578 :%u)", (unsigned)srcSize);
640579 /* Sanity check */
640580 RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed");
640581 ZSTD_checkContinuity(dctx, dst, dstCapacity);
640582
640583 dctx->processedCSize += srcSize;
640584
640585 switch (dctx->stage)
640586 {
640587 case ZSTDds_getFrameHeaderSize :
640588 assert(src != NULL);
640589 if (dctx->format == ZSTD_f_zstd1) { /* allows header */
640590 assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */
640591 if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
640592 ZSTD_memcpy(dctx->headerBuffer, src, srcSize);
640593 dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */
640594 dctx->stage = ZSTDds_decodeSkippableHeader;
640595 return 0;
640596 } }
640597 dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
640598 if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
640599 ZSTD_memcpy(dctx->headerBuffer, src, srcSize);
640600 dctx->expected = dctx->headerSize - srcSize;
640601 dctx->stage = ZSTDds_decodeFrameHeader;
640602 return 0;
640603
640604 case ZSTDds_decodeFrameHeader:
640605 assert(src != NULL);
640606 ZSTD_memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
640607 FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), "");
640608 dctx->expected = ZSTD_blockHeaderSize;
640609 dctx->stage = ZSTDds_decodeBlockHeader;
640610 return 0;
640611
640612 case ZSTDds_decodeBlockHeader:
640613 { blockProperties_t bp;
640614 size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
640615 if (ZSTD_isError(cBlockSize)) return cBlockSize;
640616 RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum");
640617 dctx->expected = cBlockSize;
640618 dctx->bType = bp.blockType;
640619 dctx->rleSize = bp.origSize;
640620 if (cBlockSize) {
640621 dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
640622 return 0;
640623 }
640624 /* empty block */
640625 if (bp.lastBlock) {
640626 if (dctx->fParams.checksumFlag) {
640627 dctx->expected = 4;
640628 dctx->stage = ZSTDds_checkChecksum;
640629 } else {
640630 dctx->expected = 0; /* end of frame */
640631 dctx->stage = ZSTDds_getFrameHeaderSize;
640632 }
640633 } else {
640634 dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */
640635 dctx->stage = ZSTDds_decodeBlockHeader;
640636 }
640637 return 0;
640638 }
640639
640640 case ZSTDds_decompressLastBlock:
640641 case ZSTDds_decompressBlock:
640642 DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
640643 { size_t rSize;
640644 switch(dctx->bType)
640645 {
640646 case bt_compressed:
640647 DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
640648 assert(dctx->isFrameDecompression == 1);
640649 rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, is_streaming);
640650 dctx->expected = 0; /* Streaming not supported */
640651 break;
640652 case bt_raw :
640653 assert(srcSize <= dctx->expected);
640654 rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
640655 FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed");
640656 assert(rSize == srcSize);
640657 dctx->expected -= rSize;
640658 break;
640659 case bt_rle :
640660 rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
640661 dctx->expected = 0; /* Streaming not supported */
640662 break;
640663 case bt_reserved : /* should never happen */
640664 default:
640665 RETURN_ERROR(corruption_detected, "invalid block type");
640666 }
640667 FORWARD_IF_ERROR(rSize, "");
640668 RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum");
640669 DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
640670 dctx->decodedSize += rSize;
640671 if (dctx->validateChecksum) XXH64_update(&dctx->xxhState, dst, rSize);
640672 dctx->previousDstEnd = (char*)dst + rSize;
640673
640674 /* Stay on the same stage until we are finished streaming the block. */
640675 if (dctx->expected > 0) {
640676 return rSize;
640677 }
640678
640679 if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */
640680 DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
640681 RETURN_ERROR_IF(
640682 dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
640683 && dctx->decodedSize != dctx->fParams.frameContentSize,
640684 corruption_detected, "");
640685 if (dctx->fParams.checksumFlag) { /* another round for frame checksum */
640686 dctx->expected = 4;
640687 dctx->stage = ZSTDds_checkChecksum;
640688 } else {
640689 ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1);
640690 dctx->expected = 0; /* ends here */
640691 dctx->stage = ZSTDds_getFrameHeaderSize;
640692 }
640693 } else {
640694 dctx->stage = ZSTDds_decodeBlockHeader;
640695 dctx->expected = ZSTD_blockHeaderSize;
640696 }
640697 return rSize;
640698 }
640699
640700 case ZSTDds_checkChecksum:
640701 assert(srcSize == 4); /* guaranteed by dctx->expected */
640702 {
640703 if (dctx->validateChecksum) {
640704 U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
640705 U32 const check32 = MEM_readLE32(src);
640706 DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
640707 RETURN_ERROR_IF(check32 != h32, checksum_wrong, "");
640708 }
640709 ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1);
640710 dctx->expected = 0;
640711 dctx->stage = ZSTDds_getFrameHeaderSize;
640712 return 0;
640713 }
640714
640715 case ZSTDds_decodeSkippableHeader:
640716 assert(src != NULL);
640717 assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
640718 assert(dctx->format != ZSTD_f_zstd1_magicless);
640719 ZSTD_memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */
640720 dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */
640721 dctx->stage = ZSTDds_skipFrame;
640722 return 0;
640723
640724 case ZSTDds_skipFrame:
640725 dctx->expected = 0;
Size2i Size
void read(const FileNode &fn, optflow::GPCTree::Node &node, optflow::GPCTree::Node)

◆ ZSTD_refDictContent()

size_t duckdb_zstd::ZSTD_refDictContent ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize )
static
640729 :
640730 assert(0); /* impossible */
640731 RETURN_ERROR(GENERIC, "impossible to reach"); /* some compilers require default to do something */
640732 }
640733}
640734
640735
640736static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
640737{
640738 dctx->dictEnd = dctx->previousDstEnd;
640739 dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
640740 dctx->prefixStart = dict;

◆ ZSTD_decompress_insertDictionary()

size_t duckdb_zstd::ZSTD_decompress_insertDictionary ( ZSTD_DCtx * dctx,
const void * dict,
size_t dictSize )
static
640841{
640842 if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
640843 { U32 const magic = MEM_readLE32(dict);
640844 if (magic != ZSTD_MAGIC_DICTIONARY) {
640845 return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */
640846 } }
640847 dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
640848
640849 /* load entropy tables */
640850 { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
640851 RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, "");
640852 dict = (const char*)dict + eSize;
size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t *entropy, const void *const dict, size_t const dictSize)
Definition duckdb.cpp:640746

◆ ZSTD_dParam_withinBounds()

int duckdb_zstd::ZSTD_dParam_withinBounds ( ZSTD_dParameter dParam,
int value )
static

◆ ZSTD_decodingBufferSize_internal()

size_t duckdb_zstd::ZSTD_decodingBufferSize_internal ( unsigned long long windowSize,
unsigned long long frameContentSize,
size_t blockSizeMax )
static
641267{
641268 return ZSTD_sizeof_DCtx(dctx);
641269}
641270
641271static size_t ZSTD_decodingBufferSize_internal(unsigned long long windowSize, unsigned long long frameContentSize, size_t blockSizeMax)
641272{
641273 size_t const blockSize = MIN((size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX), blockSizeMax);
641274 /* We need blockSize + WILDCOPY_OVERLENGTH worth of buffer so that if a block
641275 * ends at windowSize + WILDCOPY_OVERLENGTH + 1 bytes, we can start writing
641276 * the block at the beginning of the output buffer, and maintain a full window.
641277 *
641278 * We need another blockSize worth of buffer so that we can store split
641279 * literals at the end of the block without overwriting the extDict window.
641280 */

◆ ZSTD_DCtx_isOverflow()

int duckdb_zstd::ZSTD_DCtx_isOverflow ( ZSTD_DStream * zds,
size_t const neededInBuffSize,
size_t const neededOutBuffSize )
static

◆ ZSTD_DCtx_updateOversizedDuration()

void duckdb_zstd::ZSTD_DCtx_updateOversizedDuration ( ZSTD_DStream * zds,
size_t const neededInBuffSize,
size_t const neededOutBuffSize )
static
641318{
641319 return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR;
641320}
641321

◆ ZSTD_DCtx_isOversizedTooLong()

int duckdb_zstd::ZSTD_DCtx_isOversizedTooLong ( ZSTD_DStream * zds)
static
641323{
641324 if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize))
641325 zds->oversizedDuration++;
641326 else

◆ ZSTD_checkOutBuffer()

size_t duckdb_zstd::ZSTD_checkOutBuffer ( ZSTD_DStream const * zds,
ZSTD_outBuffer const * output )
static
641331{
641332 return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION;
641333}
641334
641335/* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */
641336static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output)
641337{
641338 ZSTD_outBuffer const expect = zds->expectedOutBuffer;
641339 /* No requirement when ZSTD_obm_stable is not enabled. */
641340 if (zds->outBufferMode != ZSTD_bm_stable)
641341 return 0;
641342 /* Any buffer is allowed in zdss_init, this must be the same for every other call until
641343 * the context is reset.
641344 */
ZSTD_DCtx ZSTD_DStream
Definition duckdb.cpp:408008

◆ ZSTD_decompressContinueStream()

size_t duckdb_zstd::ZSTD_decompressContinueStream ( ZSTD_DStream * zds,
char ** op,
char * oend,
void const * src,
size_t srcSize )
static
641360 {
641361 int const isSkipFrame = ZSTD_isSkipFrame(zds);
641362 if (zds->outBufferMode == ZSTD_bm_buffered) {
641363 size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart;
641364 size_t const decodedSize = ZSTD_decompressContinue(zds,
641365 zds->outBuff + zds->outStart, dstSize, src, srcSize);
641366 FORWARD_IF_ERROR(decodedSize, "");
641367 if (!decodedSize && !isSkipFrame) {
641368 zds->streamStage = zdss_read;
641369 } else {
641370 zds->outEnd = zds->outStart + decodedSize;
641371 zds->streamStage = zdss_flush;
641372 }
641373 } else {
641374 /* Write directly into the output buffer */
641375 size_t const dstSize = isSkipFrame ? 0 : (size_t)(oend - *op);
641376 size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize);
641377 FORWARD_IF_ERROR(decodedSize, "");
641378 *op += decodedSize;

◆ ZSTD_copy4()

void duckdb_zstd::ZSTD_copy4 ( void * dst,
const void * src )
static

◆ ZSTD_blockSizeMax()

size_t duckdb_zstd::ZSTD_blockSizeMax ( ZSTD_DCtx const * dctx)
static
641769 { ZSTD_memcpy(dst, src, 4); }
641770
641771
641772/*-*************************************************************
641773 * Block decoding
641774 ***************************************************************/

◆ ZSTD_allocateLiteralsBuffer()

void duckdb_zstd::ZSTD_allocateLiteralsBuffer ( ZSTD_DCtx * dctx,
void *const dst,
const size_t dstCapacity,
const size_t litSize,
const streaming_operation streaming,
const size_t expectedWriteSize,
const unsigned splitImmediately )
static
641804{
641805 size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
641806 assert(litSize <= blockSizeMax);
641807 assert(dctx->isFrameDecompression || streaming == not_streaming);
641808 assert(expectedWriteSize <= blockSizeMax);
641809 if (streaming == not_streaming && dstCapacity > blockSizeMax + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) {
641810 /* If we aren't streaming, we can just put the literals after the output
641811 * of the current block. We don't need to worry about overwriting the
641812 * extDict of our window, because it doesn't exist.
641813 * So if we have space after the end of the block, just put it there.
641814 */
641815 dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH;
641816 dctx->litBufferEnd = dctx->litBuffer + litSize;
641817 dctx->litBufferLocation = ZSTD_in_dst;
641818 } else if (litSize <= ZSTD_LITBUFFEREXTRASIZE) {
641819 /* Literals fit entirely within the extra buffer, put them there to avoid
641820 * having to split the literals.
641821 */
641822 dctx->litBuffer = dctx->litExtraBuffer;
641823 dctx->litBufferEnd = dctx->litBuffer + litSize;
641824 dctx->litBufferLocation = ZSTD_not_in_dst;
641825 } else {
641826 assert(blockSizeMax > ZSTD_LITBUFFEREXTRASIZE);
641827 /* Literals must be split between the output block and the extra lit
641828 * buffer. We fill the extra lit buffer with the tail of the literals,
641829 * and put the rest of the literals at the end of the block, with
641830 * WILDCOPY_OVERLENGTH of buffer room to allow for overreads.
641831 * This MUST not write more than our maxBlockSize beyond dst, because in
641832 * streaming mode, that could overwrite part of our extDict window.
641833 */
641834 if (splitImmediately) {
641835 /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */
641836 dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
641837 dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE;
641838 } else {
641839 /* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */

◆ ZSTD_decodeLiteralsBlock()

size_t duckdb_zstd::ZSTD_decodeLiteralsBlock ( ZSTD_DCtx * dctx,
const void * src,
size_t srcSize,
void * dst,
size_t dstCapacity,
const streaming_operation streaming )
static

ZSTD_decodeLiteralsBlock() : Where it is possible to do so without being stomped by the output during decompression, the literals block will be stored in the dstBuffer. If there is room to do so, it will be stored in full in the excess dst space after where the current block will be output. Otherwise it will be stored at the end of the current dst blockspace, with a small portion being stored in dctx->litExtraBuffer to help keep it "ahead" of the current output write.

Returns
: nb of bytes read from src (< srcSize ) note : symbol not declared but exposed for fullbench
641854 : nb of bytes read from src (< srcSize )
641855 * note : symbol not declared but exposed for fullbench */
641856static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
641857 const void* src, size_t srcSize, /* note : srcSize < BLOCKSIZE */
641858 void* dst, size_t dstCapacity, const streaming_operation streaming)
641859{
641860 DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
641861 RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");
641862
641863 { const BYTE* const istart = (const BYTE*) src;
641864 symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
641865 size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
641866
641867 switch(litEncType)
641868 {
641869 case set_repeat:
641870 DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
641871 RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
641872 ZSTD_FALLTHROUGH;
641873
641874 case set_compressed:
641875 RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need up to 5 for case 3");
641876 { size_t lhSize, litSize, litCSize;
641877 U32 singleStream=0;
641878 U32 const lhlCode = (istart[0] >> 2) & 3;
641879 U32 const lhc = MEM_readLE32(istart);
641880 size_t hufSuccess;
641881 size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
641882 int const flags = 0
641883 | (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0)
641884 | (dctx->disableHufAsm ? HUF_flags_disableAsm : 0);
641885 switch(lhlCode)
641886 {
641887 case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */
641888 /* 2 - 2 - 10 - 10 */
641889 singleStream = !lhlCode;
641890 lhSize = 3;
641891 litSize = (lhc >> 4) & 0x3FF;
641892 litCSize = (lhc >> 14) & 0x3FF;
641893 break;
641894 case 2:
641895 /* 2 - 2 - 14 - 14 */
641896 lhSize = 4;
641897 litSize = (lhc >> 4) & 0x3FFF;
641898 litCSize = lhc >> 18;
641899 break;
641900 case 3:
641901 /* 2 - 2 - 18 - 18 */
641902 lhSize = 5;
641903 litSize = (lhc >> 4) & 0x3FFFF;
641904 litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
641905 break;
641906 }
641907 RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
641908 RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
641909 if (!singleStream)
641910 RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong,
641911 "Not enough literals (%zu) for the 4-streams mode (min %u)",
641912 litSize, MIN_LITERALS_FOR_4_STREAMS);
641913 RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");
641914 RETURN_ERROR_IF(expectedWriteSize < litSize , dstSize_tooSmall, "");
641915 ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 0);
641916
641917 /* prefetch huffman table if cold */
641918 if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
641919 PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
641920 }
641921
641922 if (litEncType==set_repeat) {
641923 if (singleStream) {
641924 hufSuccess = HUF_decompress1X_usingDTable(
641925 dctx->litBuffer, litSize, istart+lhSize, litCSize,
641926 dctx->HUFptr, flags);
641927 } else {
641928 assert(litSize >= MIN_LITERALS_FOR_4_STREAMS);
641929 hufSuccess = HUF_decompress4X_usingDTable(
641930 dctx->litBuffer, litSize, istart+lhSize, litCSize,
641931 dctx->HUFptr, flags);
641932 }
641933 } else {
641934 if (singleStream) {
641935#if defined(HUF_FORCE_DECOMPRESS_X2)
641936 hufSuccess = HUF_decompress1X_DCtx_wksp(
641937 dctx->entropy.hufTable, dctx->litBuffer, litSize,
641938 istart+lhSize, litCSize, dctx->workspace,
641939 sizeof(dctx->workspace), flags);
641940#else
641941 hufSuccess = HUF_decompress1X1_DCtx_wksp(
641942 dctx->entropy.hufTable, dctx->litBuffer, litSize,
641943 istart+lhSize, litCSize, dctx->workspace,
641944 sizeof(dctx->workspace), flags);
641945#endif
641946 } else {
641947 hufSuccess = HUF_decompress4X_hufOnly_wksp(
641948 dctx->entropy.hufTable, dctx->litBuffer, litSize,
641949 istart+lhSize, litCSize, dctx->workspace,
641950 sizeof(dctx->workspace), flags);
641951 }
641952 }
641953 if (dctx->litBufferLocation == ZSTD_split)
641954 {
641955 assert(litSize > ZSTD_LITBUFFEREXTRASIZE);
641956 ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
641957 ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE);
641958 dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
641959 dctx->litBufferEnd -= WILDCOPY_OVERLENGTH;
641960 assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax);
641961 }
641962
641963 RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");
641964
641965 dctx->litPtr = dctx->litBuffer;
641966 dctx->litSize = litSize;
641967 dctx->litEntropy = 1;
641968 if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
641969 return litCSize + lhSize;
641970 }
641971
641972 case set_basic:
641973 { size_t litSize, lhSize;
641974 U32 const lhlCode = ((istart[0]) >> 2) & 3;
641975 size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
641976 switch(lhlCode)
641977 {
641978 case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
641979 lhSize = 1;
641980 litSize = istart[0] >> 3;
641981 break;
641982 case 1:
641983 lhSize = 2;
641984 litSize = MEM_readLE16(istart) >> 4;
641985 break;
641986 case 3:
641987 lhSize = 3;
641988 RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize = 3");
641989 litSize = MEM_readLE24(istart) >> 4;
641990 break;
641991 }
641992
641993 RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
641994 RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
641995 RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
641996 ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
641997 if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
641998 RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
641999 if (dctx->litBufferLocation == ZSTD_split)
642000 {
642001 ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize - ZSTD_LITBUFFEREXTRASIZE);
642002 ZSTD_memcpy(dctx->litExtraBuffer, istart + lhSize + litSize - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
642003 }
642004 else
642005 {
642006 ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize);
642007 }
642008 dctx->litPtr = dctx->litBuffer;
642009 dctx->litSize = litSize;
642010 return lhSize+litSize;
642011 }
642012 /* direct reference into compressed stream */
642013 dctx->litPtr = istart+lhSize;
642014 dctx->litSize = litSize;
642015 dctx->litBufferEnd = dctx->litPtr + litSize;
642016 dctx->litBufferLocation = ZSTD_not_in_dst;
642017 return lhSize+litSize;
642018 }
642019
642020 case set_rle:
642021 { U32 const lhlCode = ((istart[0]) >> 2) & 3;
642022 size_t litSize, lhSize;
642023 size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
642024 switch(lhlCode)
642025 {
642026 case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
642027 lhSize = 1;
642028 litSize = istart[0] >> 3;
642029 break;
642030 case 1:
642031 lhSize = 2;
642032 RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 3");
642033 litSize = MEM_readLE16(istart) >> 4;
642034 break;
642035 case 3:
642036 lhSize = 3;
642037 RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 4");
642038 litSize = MEM_readLE24(istart) >> 4;
642039 break;
642040 }
642041 RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
642042 RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
642043 RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
642044 ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
642045 if (dctx->litBufferLocation == ZSTD_split)
642046 {
642047 ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize - ZSTD_LITBUFFEREXTRASIZE);
642048 ZSTD_memset(dctx->litExtraBuffer, istart[lhSize], ZSTD_LITBUFFEREXTRASIZE);
642049 }
642050 else
642051 {
642052 ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize);
642053 }
642054 dctx->litPtr = dctx->litBuffer;
642055 dctx->litSize = litSize;
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZSTD_decodeLiteralsBlock_wrapper()

size_t duckdb_zstd::ZSTD_decodeLiteralsBlock_wrapper ( ZSTD_DCtx * dctx,
const void * src,
size_t srcSize,
void * dst,
size_t dstCapacity )

◆ ZSTD_buildSeqTable_rle()

void duckdb_zstd::ZSTD_buildSeqTable_rle ( ZSTD_seqSymbol * dt,
U32 baseValue,
U8 nbAddBits )
static
642178 { 0, 0, 6, 32}, { 0, 16, 6,65539},
642179 { 0, 15, 6,32771}, { 0, 14, 6,16387},
642180 { 0, 13, 6, 8195}, { 0, 12, 6, 4099},
642181 { 0, 11, 6, 2051}, { 0, 10, 6, 1027},
642182}; /* ML_defaultDTable */
642183
642184
642185static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U8 nbAddBits)
642186{
642187 void* ptr = dt;
642188 ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
642189 ZSTD_seqSymbol* const cell = dt + 1;
642190
642191 DTableH->tableLog = 0;
642192 DTableH->fastMode = 0;
Definition duckdb.cpp:638742
Definition duckdb.cpp:638747

◆ ZSTD_buildFSETable_body()

FORCE_INLINE_TEMPLATE void duckdb_zstd::ZSTD_buildFSETable_body ( ZSTD_seqSymbol * dt,
const short * normalizedCounter,
unsigned maxSymbolValue,
const U32 * baseValue,
const U8 * nbAdditionalBits,
unsigned tableLog,
void * wksp,
size_t wkspSize )
642211{
642212 ZSTD_seqSymbol* const tableDecode = dt+1;
642213 U32 const maxSV1 = maxSymbolValue + 1;
642214 U32 const tableSize = 1 << tableLog;
642215
642216 U16* symbolNext = (U16*)wksp;
642217 BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);
642218 U32 highThreshold = tableSize - 1;
642219
642220
642221 /* Sanity Checks */
642222 assert(maxSymbolValue <= MaxSeq);
642223 assert(tableLog <= MaxFSELog);
642224 assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);
642225 (void)wkspSize;
642226 /* Init, lay down lowprob symbols */
642227 { ZSTD_seqSymbol_header DTableH;
642228 DTableH.tableLog = tableLog;
642229 DTableH.fastMode = 1;
642230 { S16 const largeLimit= (S16)(1 << (tableLog-1));
642231 U32 s;
642232 for (s=0; s<maxSV1; s++) {
642233 if (normalizedCounter[s]==-1) {
642234 tableDecode[highThreshold--].baseValue = s;
642235 symbolNext[s] = 1;
642236 } else {
642237 if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
642238 assert(normalizedCounter[s]>=0);
642239 symbolNext[s] = (U16)normalizedCounter[s];
642240 } } }
642241 ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
642242 }
642243
642244 /* Spread symbols */
642245 assert(tableSize <= 512);
642246 /* Specialized symbol spreading for the case when there are
642247 * no low probability (-1 count) symbols. When compressing
642248 * small blocks we avoid low probability symbols to hit this
642249 * case, since header decoding speed matters more.
642250 */
642251 if (highThreshold == tableSize - 1) {
642252 size_t const tableMask = tableSize-1;
642253 size_t const step = FSE_TABLESTEP(tableSize);
642254 /* First lay down the symbols in order.
642255 * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
642256 * misses since small blocks generally have small table logs, so nearly
642257 * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
642258 * our buffer to handle the over-write.
642259 */
642260 {
642261 U64 const add = 0x0101010101010101ull;
642262 size_t pos = 0;
642263 U64 sv = 0;
642264 U32 s;
642265 for (s=0; s<maxSV1; ++s, sv += add) {
642266 int i;
642267 int const n = normalizedCounter[s];
642268 MEM_write64(spread + pos, sv);
642269 for (i = 8; i < n; i += 8) {
642270 MEM_write64(spread + pos + i, sv);
642271 }
642272 assert(n>=0);
642273 pos += (size_t)n;
642274 }
642275 }
642276 /* Now we spread those positions across the table.
642277 * The benefit of doing it in two stages is that we avoid the
642278 * variable size inner loop, which caused lots of branch misses.
642279 * Now we can run through all the positions without any branch misses.
642280 * We unroll the loop twice, since that is what empirically worked best.
642281 */
642282 {
642283 size_t position = 0;
642284 size_t s;
642285 size_t const unroll = 2;
642286 assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
642287 for (s = 0; s < (size_t)tableSize; s += unroll) {
642288 size_t u;
642289 for (u = 0; u < unroll; ++u) {
642290 size_t const uPosition = (position + (u * step)) & tableMask;
642291 tableDecode[uPosition].baseValue = spread[s + u];
642292 }
642293 position = (position + (unroll * step)) & tableMask;
642294 }
642295 assert(position == 0);
642296 }
642297 } else {
642298 U32 const tableMask = tableSize-1;
642299 U32 const step = FSE_TABLESTEP(tableSize);
642300 U32 s, position = 0;
642301 for (s=0; s<maxSV1; s++) {
642302 int i;
642303 int const n = normalizedCounter[s];
642304 for (i=0; i<n; i++) {
642305 tableDecode[position].baseValue = s;
642306 position = (position + step) & tableMask;
642307 while (UNLIKELY(position > highThreshold)) position = (position + step) & tableMask; /* lowprob area */
642308 } }
642309 assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
642310 }
642311
642312 /* Build Decoding table */
642313 {
642314 U32 u;
642315 for (u=0; u<tableSize; u++) {
642316 U32 const symbol = tableDecode[u].baseValue;
642317 U32 const nextState = symbolNext[symbol]++;
642318 tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );

◆ ZSTD_buildFSETable_body_default()

void duckdb_zstd::ZSTD_buildFSETable_body_default ( ZSTD_seqSymbol * dt,
const short * normalizedCounter,
unsigned maxSymbolValue,
const U32 * baseValue,
const U8 * nbAdditionalBits,
unsigned tableLog,
void * wksp,
size_t wkspSize )
static

◆ ZSTD_buildSeqTable()

size_t duckdb_zstd::ZSTD_buildSeqTable ( ZSTD_seqSymbol * DTableSpace,
const ZSTD_seqSymbol ** DTablePtr,
symbolEncodingType_e type,
unsigned max,
U32 maxLog,
const void * src,
size_t srcSize,
const U32 * baseValue,
const U8 * nbAdditionalBits,
const ZSTD_seqSymbol * defaultTable,
U32 flagRepeatTable,
int ddictIsCold,
int nbSeq,
U32 * wksp,
size_t wkspSize,
int bmi2 )
static

ZSTD_buildSeqTable() :

Returns
: nb bytes read from src, or an error code if it fails
642376{
642377 switch(type)
642378 {
642379 case set_rle :
642380 RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
642381 RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
642382 { U32 const symbol = *(const BYTE*)src;
642383 U32 const baseline = baseValue[symbol];
642384 U8 const nbBits = nbAdditionalBits[symbol];
642385 ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
642386 }
642387 *DTablePtr = DTableSpace;
642388 return 1;
642389 case set_basic :
642390 *DTablePtr = defaultTable;
642391 return 0;
642392 case set_repeat:
642393 RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
642394 /* prefetch FSE table if used */
642395 if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
642396 const void* const pStart = *DTablePtr;
642397 size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
642398 PREFETCH_AREA(pStart, pSize);
642399 }
642400 return 0;
642401 case set_compressed :
642402 { unsigned tableLog;
642403 S16 norm[MaxSeq+1];
642404 size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
642405 RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
642406 RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
642407 ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);
642408 *DTablePtr = DTableSpace;
Here is the caller graph for this function:

◆ ZSTD_overlapCopy8()

HINT_INLINE void duckdb_zstd::ZSTD_overlapCopy8 ( BYTE ** op,
BYTE const ** ip,
size_t offset )

ZSTD_overlapCopy8() : Copies 8 bytes from ip to op and updates op and ip where ip <= op. If the offset is < 8 then the offset is spread to at least 8 bytes.

Precondition: *ip <= *op Postcondition: *op - *op >= 8

642526 {
642527 assert(*ip <= *op);
642528 if (offset < 8) {
642529 /* close range match, overlap */
642530 static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
642531 static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
642532 int const sub2 = dec64table[offset];
642533 (*op)[0] = (*ip)[0];
642534 (*op)[1] = (*ip)[1];
642535 (*op)[2] = (*ip)[2];
642536 (*op)[3] = (*ip)[3];
642537 *ip += dec32table[offset];
642538 ZSTD_copy4(*op+4, *ip);
642539 *ip -= sub2;

◆ ZSTD_safecopy()

void duckdb_zstd::ZSTD_safecopy ( BYTE * op,
const BYTE *const oend_w,
BYTE const * ip,
ptrdiff_t length,
ZSTD_overlap_e ovtype )
static

ZSTD_safecopy() : Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer and write up to 16 bytes past oend_w (op >= oend_w is allowed). This function is only called in the uncommon case where the sequence is near the end of the block. It should be fast for a single long sequence, but can be slow for several short sequences.

Parameters
ovtypecontrols the overlap detection
  • ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  • ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart. The src buffer must be before the dst buffer.
642555 : The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
642556 * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
642557 * The src buffer must be before the dst buffer.
642558 */
642559static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
642560 ptrdiff_t const diff = op - ip;
642561 BYTE* const oend = op + length;
642562
642563 assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
642564 (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
642565
642566 if (length < 8) {
642567 /* Handle short lengths. */
642568 while (op < oend) *op++ = *ip++;
642569 return;
642570 }
642571 if (ovtype == ZSTD_overlap_src_before_dst) {
642572 /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
642573 assert(length >= 8);
642574 ZSTD_overlapCopy8(&op, &ip, diff);
642575 length -= 8;
642576 assert(op - ip >= 8);
642577 assert(op <= oend);
642578 }
642579
642580 if (oend <= oend_w) {
642581 /* No risk of overwrite. */
642582 ZSTD_wildcopy(op, ip, length, ovtype);
642583 return;
642584 }
642585 if (op <= oend_w) {
642586 /* Wildcopy until we get close to the end. */
642587 assert(oend > oend_w);
T & at(int idx, std::vector< T > &items)
HINT_INLINE void ZSTD_overlapCopy8(BYTE **op, BYTE const **ip, size_t offset)
Definition duckdb.cpp:642519
static void ZSTD_safecopy(BYTE *op, const BYTE *const oend_w, BYTE const *ip, ptrdiff_t length, ZSTD_overlap_e ovtype)
Definition duckdb.cpp:642552

◆ ZSTD_safecopyDstBeforeSrc()

void duckdb_zstd::ZSTD_safecopyDstBeforeSrc ( BYTE * op,
const BYTE * ip,
ptrdiff_t length )
static
642599 {
642600 ptrdiff_t const diff = op - ip;
642601 BYTE* const oend = op + length;
642602
642603 if (length < 8 || diff > -8) {
642604 /* Handle short lengths, close overlaps, and dst not before src. */
642605 while (op < oend) *op++ = *ip++;
642606 return;
642607 }
642608
642609 if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) {
642610 ZSTD_wildcopy(op, ip, oend - WILDCOPY_OVERLENGTH - op, ZSTD_no_overlap);

◆ ZSTD_execSequenceEnd()

FORCE_NOINLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_execSequenceEnd ( BYTE * op,
BYTE *const oend,
seq_t sequence,
const BYTE ** litPtr,
const BYTE *const litLimit,
const BYTE *const prefixStart,
const BYTE *const virtualStart,
const BYTE *const dictEnd )
642624 : This function needs to be fast for a single long sequence, but doesn't need
642625 * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
642626 */
642627FORCE_NOINLINE
642628ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
642629size_t ZSTD_execSequenceEnd(BYTE* op,
642630 BYTE* const oend, seq_t sequence,
642631 const BYTE** litPtr, const BYTE* const litLimit,
642632 const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
642633{
642634 BYTE* const oLitEnd = op + sequence.litLength;
642635 size_t const sequenceLength = sequence.litLength + sequence.matchLength;
642636 const BYTE* const iLitEnd = *litPtr + sequence.litLength;
642637 const BYTE* match = oLitEnd - sequence.offset;
642638 BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
642639
642640 /* bounds checks : careful of address space overflow in 32-bit mode */
642641 RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
642642 RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
642643 assert(op < op + sequenceLength);
642644 assert(oLitEnd < op + sequenceLength);
642645
642646 /* copy literals */
642647 ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
642648 op = oLitEnd;
642649 *litPtr = iLitEnd;
642650
642651 /* copy Match */
642652 if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
642653 /* offset beyond prefix */
642654 RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
642655 match = dictEnd - (prefixStart - match);
642656 if (match + sequence.matchLength <= dictEnd) {
642657 ZSTD_memmove(oLitEnd, match, sequence.matchLength);
642658 return sequenceLength;
642659 }
642660 /* span extDict & currentPrefixSegment */
642661 { size_t const length1 = dictEnd - match;
642662 ZSTD_memmove(oLitEnd, match, length1);
642663 op = oLitEnd + length1;

◆ ZSTD_execSequenceEndSplitLitBuffer()

FORCE_NOINLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_execSequenceEndSplitLitBuffer ( BYTE * op,
BYTE *const oend,
const BYTE *const oend_w,
seq_t sequence,
const BYTE ** litPtr,
const BYTE *const litLimit,
const BYTE *const prefixStart,
const BYTE *const virtualStart,
const BYTE *const dictEnd )
642681{
642682 BYTE* const oLitEnd = op + sequence.litLength;
642683 size_t const sequenceLength = sequence.litLength + sequence.matchLength;
642684 const BYTE* const iLitEnd = *litPtr + sequence.litLength;
642685 const BYTE* match = oLitEnd - sequence.offset;
642686
642687
642688 /* bounds checks : careful of address space overflow in 32-bit mode */
642689 RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
642690 RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
642691 assert(op < op + sequenceLength);
642692 assert(oLitEnd < op + sequenceLength);
642693
642694 /* copy literals */
642695 RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer");
642696 ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength);
642697 op = oLitEnd;
642698 *litPtr = iLitEnd;
642699
642700 /* copy Match */
642701 if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
642702 /* offset beyond prefix */
642703 RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
642704 match = dictEnd - (prefixStart - match);
642705 if (match + sequence.matchLength <= dictEnd) {
642706 ZSTD_memmove(oLitEnd, match, sequence.matchLength);
642707 return sequenceLength;
642708 }
642709 /* span extDict & currentPrefixSegment */
642710 { size_t const length1 = dictEnd - match;
642711 ZSTD_memmove(oLitEnd, match, length1);
642712 op = oLitEnd + length1;

◆ ZSTD_execSequence()

HINT_INLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_execSequence ( BYTE * op,
BYTE *const oend,
seq_t sequence,
const BYTE ** litPtr,
const BYTE *const litLimit,
const BYTE *const prefixStart,
const BYTE *const virtualStart,
const BYTE *const dictEnd )
642727{
642728 BYTE* const oLitEnd = op + sequence.litLength;
642729 size_t const sequenceLength = sequence.litLength + sequence.matchLength;
642730 BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
642731 BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */
642732 const BYTE* const iLitEnd = *litPtr + sequence.litLength;
642733 const BYTE* match = oLitEnd - sequence.offset;
642734
642735 assert(op != NULL /* Precondition */);
642736 assert(oend_w < oend /* No underflow */);
642737
642738#if defined(__aarch64__)
642739 /* prefetch sequence starting from match that will be used for copy later */
642740 PREFETCH_L1(match);
642741#endif
642742 /* Handle edge cases in a slow path:
642743 * - Read beyond end of literals
642744 * - Match end is within WILDCOPY_OVERLIMIT of oend
642745 * - 32-bit mode and the match length overflows
642746 */
642747 if (UNLIKELY(
642748 iLitEnd > litLimit ||
642749 oMatchEnd > oend_w ||
642750 (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
642751 return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
642752
642753 /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
642754 assert(op <= oLitEnd /* No overflow */);
642755 assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
642756 assert(oMatchEnd <= oend /* No underflow */);
642757 assert(iLitEnd <= litLimit /* Literal length is in bounds */);
642758 assert(oLitEnd <= oend_w /* Can wildcopy literals */);
642759 assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
642760
642761 /* Copy Literals:
642762 * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
642763 * We likely don't need the full 32-byte wildcopy.
642764 */
642765 assert(WILDCOPY_OVERLENGTH >= 16);
642766 ZSTD_copy16(op, (*litPtr));
642767 if (UNLIKELY(sequence.litLength > 16)) {
642768 ZSTD_wildcopy(op + 16, (*litPtr) + 16, sequence.litLength - 16, ZSTD_no_overlap);
642769 }
642770 op = oLitEnd;
642771 *litPtr = iLitEnd; /* update for next sequence */
642772
642773 /* Copy Match */
642774 if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
642775 /* offset beyond prefix -> go into extDict */
642776 RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
642777 match = dictEnd + (match - prefixStart);
642778 if (match + sequence.matchLength <= dictEnd) {
642779 ZSTD_memmove(oLitEnd, match, sequence.matchLength);
642780 return sequenceLength;
642781 }
642782 /* span extDict & currentPrefixSegment */
642783 { size_t const length1 = dictEnd - match;
642784 ZSTD_memmove(oLitEnd, match, length1);
642785 op = oLitEnd + length1;
642786 sequence.matchLength -= length1;
642787 match = prefixStart;
642788 }
642789 }
642790 /* Match within prefix of 1 or more bytes */
642791 assert(op <= oMatchEnd);
642792 assert(oMatchEnd <= oend_w);
642793 assert(match >= prefixStart);
642794 assert(sequence.matchLength >= 1);
642795
642796 /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
642797 * without overlap checking.
642798 */
642799 if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
642800 /* We bet on a full wildcopy for matches, since we expect matches to be
642801 * longer than literals (in general). In silesia, ~10% of matches are longer
642802 * than 16 bytes.
642803 */
642804 ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
642805 return sequenceLength;
642806 }
642807 assert(sequence.offset < WILDCOPY_VECLEN);
642808
642809 /* Copy 8 bytes and spread the offset to be >= 8. */
642810 ZSTD_overlapCopy8(&op, &match, sequence.offset);
642811

◆ ZSTD_execSequenceSplitLitBuffer()

HINT_INLINE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t duckdb_zstd::ZSTD_execSequenceSplitLitBuffer ( BYTE * op,
BYTE *const oend,
const BYTE *const oend_w,
seq_t sequence,
const BYTE ** litPtr,
const BYTE *const litLimit,
const BYTE *const prefixStart,
const BYTE *const virtualStart,
const BYTE *const dictEnd )
642826{
642827 BYTE* const oLitEnd = op + sequence.litLength;
642828 size_t const sequenceLength = sequence.litLength + sequence.matchLength;
642829 BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
642830 const BYTE* const iLitEnd = *litPtr + sequence.litLength;
642831 const BYTE* match = oLitEnd - sequence.offset;
642832
642833 assert(op != NULL /* Precondition */);
642834 assert(oend_w < oend /* No underflow */);
642835 /* Handle edge cases in a slow path:
642836 * - Read beyond end of literals
642837 * - Match end is within WILDCOPY_OVERLIMIT of oend
642838 * - 32-bit mode and the match length overflows
642839 */
642840 if (UNLIKELY(
642841 iLitEnd > litLimit ||
642842 oMatchEnd > oend_w ||
642843 (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
642844 return ZSTD_execSequenceEndSplitLitBuffer(op, oend, oend_w, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
642845
642846 /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
642847 assert(op <= oLitEnd /* No overflow */);
642848 assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
642849 assert(oMatchEnd <= oend /* No underflow */);
642850 assert(iLitEnd <= litLimit /* Literal length is in bounds */);
642851 assert(oLitEnd <= oend_w /* Can wildcopy literals */);
642852 assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
642853
642854 /* Copy Literals:
642855 * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
642856 * We likely don't need the full 32-byte wildcopy.
642857 */
642858 assert(WILDCOPY_OVERLENGTH >= 16);
642859 ZSTD_copy16(op, (*litPtr));
642860 if (UNLIKELY(sequence.litLength > 16)) {
642861 ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
642862 }
642863 op = oLitEnd;
642864 *litPtr = iLitEnd; /* update for next sequence */
642865
642866 /* Copy Match */
642867 if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
642868 /* offset beyond prefix -> go into extDict */
642869 RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
642870 match = dictEnd + (match - prefixStart);
642871 if (match + sequence.matchLength <= dictEnd) {
642872 ZSTD_memmove(oLitEnd, match, sequence.matchLength);
642873 return sequenceLength;
642874 }
642875 /* span extDict & currentPrefixSegment */
642876 { size_t const length1 = dictEnd - match;
642877 ZSTD_memmove(oLitEnd, match, length1);
642878 op = oLitEnd + length1;
642879 sequence.matchLength -= length1;
642880 match = prefixStart;
642881 } }
642882 /* Match within prefix of 1 or more bytes */
642883 assert(op <= oMatchEnd);
642884 assert(oMatchEnd <= oend_w);
642885 assert(match >= prefixStart);
642886 assert(sequence.matchLength >= 1);
642887
642888 /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
642889 * without overlap checking.
642890 */
642891 if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
642892 /* We bet on a full wildcopy for matches, since we expect matches to be
642893 * longer than literals (in general). In silesia, ~10% of matches are longer
642894 * than 16 bytes.
642895 */
642896 ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
642897 return sequenceLength;
642898 }
642899 assert(sequence.offset < WILDCOPY_VECLEN);
642900
642901 /* Copy 8 bytes and spread the offset to be >= 8. */
642902 ZSTD_overlapCopy8(&op, &match, sequence.offset);
642903

◆ ZSTD_initFseState()

void duckdb_zstd::ZSTD_initFseState ( ZSTD_fseState * DStatePtr,
BIT_DStream_t * bitD,
const ZSTD_seqSymbol * dt )
static
642915{
642916 const void* ptr = dt;

◆ ZSTD_updateFseStateWithDInfo()

FORCE_INLINE_TEMPLATE void duckdb_zstd::ZSTD_updateFseStateWithDInfo ( ZSTD_fseState * DStatePtr,
BIT_DStream_t * bitD,
U16 nextState,
U32 nbBits )
642919 : val=%u using %u bits",
642920 (U32)DStatePtr->state, DTableH->tableLog);
642921 BIT_reloadDStream(bitD);
642922 DStatePtr->table = dt + 1;
642923}

◆ ZSTD_decodeSequence()

FORCE_INLINE_TEMPLATE seq_t duckdb_zstd::ZSTD_decodeSequence ( seqState_t * seqState,
const ZSTD_longOffset_e longOffsets,
const int isLastSeq )

ZSTD_decodeSequence(): longOffsets : tells the decoder to reload more bit while decoding large offsets only used in 32-bit mode

Returns
: Sequence (litL + matchL + offset)
642952{
642953 seq_t seq;
642954 /*
642955 * ZSTD_seqSymbol is a 64 bits wide structure.
642956 * It can be loaded in one operation
642957 * and its fields extracted by simply shifting or bit-extracting on aarch64.
642958 * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh
642959 * operations that cause performance drop. This can be avoided by using this
642960 * ZSTD_memcpy hack.
642961 */
642962#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__))
642963 ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS;
642964 ZSTD_seqSymbol* const llDInfo = &llDInfoS;
642965 ZSTD_seqSymbol* const mlDInfo = &mlDInfoS;
642966 ZSTD_seqSymbol* const ofDInfo = &ofDInfoS;
642967 ZSTD_memcpy(llDInfo, seqState->stateLL.table + seqState->stateLL.state, sizeof(ZSTD_seqSymbol));
642968 ZSTD_memcpy(mlDInfo, seqState->stateML.table + seqState->stateML.state, sizeof(ZSTD_seqSymbol));
642969 ZSTD_memcpy(ofDInfo, seqState->stateOffb.table + seqState->stateOffb.state, sizeof(ZSTD_seqSymbol));
642970#else
642971 const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state;
642972 const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state;
642973 const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state;
642974#endif
642975 seq.matchLength = mlDInfo->baseValue;
642976 seq.litLength = llDInfo->baseValue;
642977 { U32 const ofBase = ofDInfo->baseValue;
642978 BYTE const llBits = llDInfo->nbAdditionalBits;
642979 BYTE const mlBits = mlDInfo->nbAdditionalBits;
642980 BYTE const ofBits = ofDInfo->nbAdditionalBits;
642981 BYTE const totalBits = llBits+mlBits+ofBits;
642982
642983 U16 const llNext = llDInfo->nextState;
642984 U16 const mlNext = mlDInfo->nextState;
642985 U16 const ofNext = ofDInfo->nextState;
642986 U32 const llnbBits = llDInfo->nbBits;
642987 U32 const mlnbBits = mlDInfo->nbBits;
642988 U32 const ofnbBits = ofDInfo->nbBits;
642989
642990 assert(llBits <= MaxLLBits);
642991 assert(mlBits <= MaxMLBits);
642992 assert(ofBits <= MaxOff);
642993 /*
642994 * As gcc has better branch and block analyzers, sometimes it is only
642995 * valuable to mark likeliness for clang, it gives around 3-4% of
642996 * performance.
642997 */
642998
642999 /* sequence */
643000 { size_t offset;
643001 if (ofBits > 1) {
643002 ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
643003 ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
643004 ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);
643005 ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);
643006 if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
643007 /* Always read extra bits, this keeps the logic simple,
643008 * avoids branches, and avoids accidentally reading 0 bits.
643009 */
643010 U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32;
643011 offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
643012 BIT_reloadDStream(&seqState->DStream);
643013 offset += BIT_readBitsFast(&seqState->DStream, extraBits);
643014 } else {
643015 offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
643016 if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
643017 }
643018 seqState->prevOffset[2] = seqState->prevOffset[1];
643019 seqState->prevOffset[1] = seqState->prevOffset[0];
643020 seqState->prevOffset[0] = offset;
643021 } else {
643022 U32 const ll0 = (llDInfo->baseValue == 0);
643023 if (LIKELY((ofBits == 0))) {
643024 offset = seqState->prevOffset[ll0];
643025 seqState->prevOffset[1] = seqState->prevOffset[!ll0];
643026 seqState->prevOffset[0] = offset;
643027 } else {
643028 offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
643029 { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
643030 temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */
643031 if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
643032 seqState->prevOffset[1] = seqState->prevOffset[0];
643033 seqState->prevOffset[0] = offset = temp;
643034 } } }
643035 seq.offset = offset;
643036 }
643037
643038 if (mlBits > 0)
643039 seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
643040
643041 if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
643042 BIT_reloadDStream(&seqState->DStream);
643043 if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
643044 BIT_reloadDStream(&seqState->DStream);
643045 /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
643046 ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
643047
643048 if (llBits > 0)
643049 seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
643050
643051 if (MEM_32bits())
643052 BIT_reloadDStream(&seqState->DStream);
643053
643054 DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
643055 (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
643056
643057 if (!isLastSeq) {
643058 /* don't update FSE state for last Sequence */
643059 ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */
643060 ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */
643061 if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
Definition duckdb.cpp:642493

◆ ZSTD_decompressSequences_bodySplitLitBuffer()

FORCE_INLINE_TEMPLATE size_t DONT_VECTORIZE duckdb_zstd::ZSTD_decompressSequences_bodySplitLitBuffer ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
643129{
643130 const BYTE* ip = (const BYTE*)seqStart;
643131 const BYTE* const iend = ip + seqSize;
643132 BYTE* const ostart = (BYTE*)dst;
643133 BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, maxDstSize);
643134 BYTE* op = ostart;
643135 const BYTE* litPtr = dctx->litPtr;
643136 const BYTE* litBufferEnd = dctx->litBufferEnd;
643137 const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
643138 const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
643139 const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
643140 DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq);
643141
643142 /* Literals are split between internal buffer & output buffer */
643143 if (nbSeq) {
643144 seqState_t seqState;
643145 dctx->fseEntropy = 1;
643146 { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
643148 ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
643149 corruption_detected, "");
643150 ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
643151 ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
643152 ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
643153 assert(dst != NULL);
643154
643155 ZSTD_STATIC_ASSERT(
643156 BIT_DStream_unfinished < BIT_DStream_completed &&
643157 BIT_DStream_endOfBuffer < BIT_DStream_completed &&
643158 BIT_DStream_completed < BIT_DStream_overflow);
643159
643160 /* decompress without overrunning litPtr begins */
643161 { seq_t sequence = {0,0,0}; /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one iteration) */
643162 /* Align the decompression loop to 32 + 16 bytes.
643163 *
643164 * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
643165 * speed swings based on the alignment of the decompression loop. This
643166 * performance swing is caused by parts of the decompression loop falling
643167 * out of the DSB. The entire decompression loop should fit in the DSB,
643168 * when it can't we get much worse performance. You can measure if you've
643169 * hit the good case or the bad case with this perf command for some
643170 * compressed file test.zst:
643171 *
643172 * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
643173 * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
643174 *
643175 * If you see most cycles served out of the MITE you've hit the bad case.
643176 * If you see most cycles served out of the DSB you've hit the good case.
643177 * If it is pretty even then you may be in an okay case.
643178 *
643179 * This issue has been reproduced on the following CPUs:
643180 * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
643181 * Use Instruments->Counters to get DSB/MITE cycles.
643182 * I never got performance swings, but I was able to
643183 * go from the good case of mostly DSB to half of the
643184 * cycles served from MITE.
643185 * - Coffeelake: Intel i9-9900k
643186 * - Coffeelake: Intel i7-9700k
643187 *
643188 * I haven't been able to reproduce the instability or DSB misses on any
643189 * of the following CPUS:
643190 * - Haswell
643191 * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
643192 * - Skylake
643193 *
643194 * Alignment is done for each of the three major decompression loops:
643195 * - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer
643196 * - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer
643197 * - ZSTD_decompressSequences_body
643198 * Alignment choices are made to minimize large swings on bad cases and influence on performance
643199 * from changes external to this code, rather than to overoptimize on the current commit.
643200 *
643201 * If you are seeing performance stability this script can help test.
643202 * It tests on 4 commits in zstd where I saw performance change.
643203 *
643204 * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
643205 */
643206#if defined(__GNUC__) && defined(__x86_64__)
643207 __asm__(".p2align 6");
643208# if __GNUC__ >= 7
643209 /* good for gcc-7, gcc-9, and gcc-11 */
643210 __asm__("nop");
643211 __asm__(".p2align 5");
643212 __asm__("nop");
643213 __asm__(".p2align 4");
643214# if __GNUC__ == 8 || __GNUC__ == 10
643215 /* good for gcc-8 and gcc-10 */
643216 __asm__("nop");
643217 __asm__(".p2align 3");
643218# endif
643219# endif
643220#endif
643221
643222 /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */
643223 for ( ; nbSeq; nbSeq--) {
643224 sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
643225 if (litPtr + sequence.litLength > dctx->litBufferEnd) break;
643226 { size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
643227#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643228 assert(!ZSTD_isError(oneSeqSize));
643229 ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
643230#endif
643231 if (UNLIKELY(ZSTD_isError(oneSeqSize)))
643232 return oneSeqSize;
643233 DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
643234 op += oneSeqSize;
643235 } }
643236 DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)");
643237
643238 /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */
643239 if (nbSeq > 0) {
643240 const size_t leftoverLit = dctx->litBufferEnd - litPtr;
643241 DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength);
643242 if (leftoverLit) {
643243 RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
643244 ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
643245 sequence.litLength -= leftoverLit;
643246 op += leftoverLit;
643247 }
643248 litPtr = dctx->litExtraBuffer;
643249 litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
643250 dctx->litBufferLocation = ZSTD_not_in_dst;
643251 { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
643252#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643253 assert(!ZSTD_isError(oneSeqSize));
643254 ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
643255#endif
643256 if (UNLIKELY(ZSTD_isError(oneSeqSize)))
643257 return oneSeqSize;
643258 DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
643259 op += oneSeqSize;
643260 }
643261 nbSeq--;
643262 }
643263 }
643264
643265 if (nbSeq > 0) {
643266 /* there is remaining lit from extra buffer */
643267
643268#if defined(__GNUC__) && defined(__x86_64__)
643269 __asm__(".p2align 6");
643270 __asm__("nop");
643271# if __GNUC__ != 7
643272 /* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */
643273 __asm__(".p2align 4");
643274 __asm__("nop");
643275 __asm__(".p2align 3");
643276# elif __GNUC__ >= 11
643277 __asm__(".p2align 3");
643278# else
643279 __asm__(".p2align 5");
643280 __asm__("nop");
643281 __asm__(".p2align 3");
643282# endif
643283#endif
643284
643285 for ( ; nbSeq ; nbSeq--) {
643286 seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
643287 size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
643288#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643289 assert(!ZSTD_isError(oneSeqSize));
643290 ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
643291#endif
643292 if (UNLIKELY(ZSTD_isError(oneSeqSize)))
643293 return oneSeqSize;
643294 DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
643295 op += oneSeqSize;
643296 }
643297 }
643298
643299 /* check if reached exact end */
643300 DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq);
643301 RETURN_ERROR_IF(nbSeq, corruption_detected, "");
643302 DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed);
643303 RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
643304 /* save reps for next block */
643305 { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
643306 }
643307
643308 /* last literal segment */
643309 if (dctx->litBufferLocation == ZSTD_split) {
643310 /* split hasn't been reached yet, first get dst then copy litExtraBuffer */
643311 size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
643312 DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize);
643313 RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
643314 if (op != NULL) {
643315 ZSTD_memmove(op, litPtr, lastLLSize);
643316 op += lastLLSize;
643317 }
643318 litPtr = dctx->litExtraBuffer;
643319 litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
643320 dctx->litBufferLocation = ZSTD_not_in_dst;
643321 }
643322 /* copy last literals from internal buffer */
643323 { size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
643324 DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize);
643325 RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
643326 if (op != NULL) {
MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t *bitD)
Definition duckdb.cpp:609948
FORCE_INLINE_TEMPLATE seq_t ZSTD_decodeSequence(seqState_t *seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq)
Definition duckdb.cpp:642944
Definition duckdb.cpp:642504

◆ ZSTD_decompressSequences_body()

FORCE_INLINE_TEMPLATE size_t DONT_VECTORIZE duckdb_zstd::ZSTD_decompressSequences_body ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
643341{
643342 const BYTE* ip = (const BYTE*)seqStart;
643343 const BYTE* const iend = ip + seqSize;
643344 BYTE* const ostart = (BYTE*)dst;
643345 BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ZSTD_maybeNullPtrAdd(ostart, maxDstSize) : dctx->litBuffer;
643346 BYTE* op = ostart;
643347 const BYTE* litPtr = dctx->litPtr;
643348 const BYTE* const litEnd = litPtr + dctx->litSize;
643349 const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart);
643350 const BYTE* const vBase = (const BYTE*)(dctx->virtualStart);
643351 const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd);
643352 DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq);
643353
643354 /* Regen sequences */
643355 if (nbSeq) {
643356 seqState_t seqState;
643357 dctx->fseEntropy = 1;
643358 { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
643360 ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend - ip)),
643361 corruption_detected, "");
643362 ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
643363 ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
643364 ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
643365 assert(dst != NULL);
643366
643367#if defined(__GNUC__) && defined(__x86_64__)
643368 __asm__(".p2align 6");
643369 __asm__("nop");
643370# if __GNUC__ >= 7
643371 __asm__(".p2align 5");
643372 __asm__("nop");
643373 __asm__(".p2align 3");
643374# else
643375 __asm__(".p2align 4");
643376 __asm__("nop");
643377 __asm__(".p2align 3");
643378# endif
643379#endif
643380
643381 for ( ; nbSeq ; nbSeq--) {
643382 seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
643383 size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
643384#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643385 assert(!ZSTD_isError(oneSeqSize));
643386 ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
643387#endif
643388 if (UNLIKELY(ZSTD_isError(oneSeqSize)))
643389 return oneSeqSize;
643390 DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
643391 op += oneSeqSize;
643392 }
643393
643394 /* check if reached exact end */
643395 assert(nbSeq == 0);
643396 RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
643397 /* save reps for next block */
643398 { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
643399 }
643400
643401 /* last literal segment */
643402 { size_t const lastLLSize = (size_t)(litEnd - litPtr);
643403 DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize);
643404 RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
643405 if (op != NULL) {

◆ ZSTD_decompressSequences_default()

size_t duckdb_zstd::ZSTD_decompressSequences_default ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static

◆ ZSTD_decompressSequencesSplitLitBuffer_default()

size_t duckdb_zstd::ZSTD_decompressSequencesSplitLitBuffer_default ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static
643419{
643420 return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
643421}
643422
643423static size_t

◆ ZSTD_prefetchMatch()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::ZSTD_prefetchMatch ( size_t prefetchPos,
seq_t const sequence,
const BYTE *const prefixStart,
const BYTE *const dictEnd )
643439{
643440 prefetchPos += sequence.litLength;
643441 { const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;

◆ ZSTD_decompressSequencesLong_body()

FORCE_INLINE_TEMPLATE size_t duckdb_zstd::ZSTD_decompressSequencesLong_body ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
643460{
643461 const BYTE* ip = (const BYTE*)seqStart;
643462 const BYTE* const iend = ip + seqSize;
643463 BYTE* const ostart = (BYTE*)dst;
643464 BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ZSTD_maybeNullPtrAdd(ostart, maxDstSize);
643465 BYTE* op = ostart;
643466 const BYTE* litPtr = dctx->litPtr;
643467 const BYTE* litBufferEnd = dctx->litBufferEnd;
643468 const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
643469 const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
643470 const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
643471
643472 /* Regen sequences */
643473 if (nbSeq) {
643474#define STORED_SEQS 8
643475#define STORED_SEQS_MASK (STORED_SEQS-1)
643476#define ADVANCED_SEQS STORED_SEQS
643477 seq_t sequences[STORED_SEQS];
643478 int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
643479 seqState_t seqState;
643480 int seqNb;
643481 size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
643482
643483 dctx->fseEntropy = 1;
643484 { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
643485 assert(dst != NULL);
643486 assert(iend >= ip);
643488 ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
643489 corruption_detected, "");
643490 ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
643491 ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
643492 ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
643493
643494 /* prepare in advance */
643495 for (seqNb=0; seqNb<seqAdvance; seqNb++) {
643496 seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
643497 prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
643498 sequences[seqNb] = sequence;
643499 }
643500
643501 /* decompress without stomping litBuffer */
643502 for (; seqNb < nbSeq; seqNb++) {
643503 seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
643504
643505 if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {
643506 /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
643507 const size_t leftoverLit = dctx->litBufferEnd - litPtr;
643508 if (leftoverLit)
643509 {
643510 RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
643511 ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
643512 sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
643513 op += leftoverLit;
643514 }
643515 litPtr = dctx->litExtraBuffer;
643516 litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
643517 dctx->litBufferLocation = ZSTD_not_in_dst;
643518 { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
643519#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643520 assert(!ZSTD_isError(oneSeqSize));
643521 ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
643522#endif
643523 if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
643524
643525 prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
643526 sequences[seqNb & STORED_SEQS_MASK] = sequence;
643527 op += oneSeqSize;
643528 } }
643529 else
643530 {
643531 /* lit buffer is either wholly contained in first or second split, or not split at all*/
643532 size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
643533 ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength - WILDCOPY_OVERLENGTH, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
643534 ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
643535#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643536 assert(!ZSTD_isError(oneSeqSize));
643537 ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
643538#endif
643539 if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
643540
643541 prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
643542 sequences[seqNb & STORED_SEQS_MASK] = sequence;
643543 op += oneSeqSize;
643544 }
643545 }
643546 RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
643547
643548 /* finish queue */
643549 seqNb -= seqAdvance;
643550 for ( ; seqNb<nbSeq ; seqNb++) {
643551 seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
643552 if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {
643553 const size_t leftoverLit = dctx->litBufferEnd - litPtr;
643554 if (leftoverLit) {
643555 RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
643556 ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
643557 sequence->litLength -= leftoverLit;
643558 op += leftoverLit;
643559 }
643560 litPtr = dctx->litExtraBuffer;
643561 litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
643562 dctx->litBufferLocation = ZSTD_not_in_dst;
643563 { size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
643564#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643565 assert(!ZSTD_isError(oneSeqSize));
643566 ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
643567#endif
643568 if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
643569 op += oneSeqSize;
643570 }
643571 }
643572 else
643573 {
643574 size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
643575 ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
643576 ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
643577#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
643578 assert(!ZSTD_isError(oneSeqSize));
643579 ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
643580#endif
643581 if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
643582 op += oneSeqSize;
643583 }
643584 }
643585
643586 /* save reps for next block */
643587 { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
643588 }
643589
643590 /* last literal segment */
643591 if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */
643592 size_t const lastLLSize = litBufferEnd - litPtr;
643593 RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
643594 if (op != NULL) {
643595 ZSTD_memmove(op, litPtr, lastLLSize);
643596 op += lastLLSize;
643597 }
643598 litPtr = dctx->litExtraBuffer;
643599 litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
643600 }
643601 { size_t const lastLLSize = litBufferEnd - litPtr;
643602 RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
643603 if (op != NULL) {

◆ ZSTD_decompressSequencesLong_default()

size_t duckdb_zstd::ZSTD_decompressSequencesLong_default ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static

◆ ZSTD_decompressSequences()

size_t duckdb_zstd::ZSTD_decompressSequences ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static
643671{
643672 DEBUGLOG(5, "ZSTD_decompressSequences");

◆ ZSTD_decompressSequencesSplitLitBuffer()

size_t duckdb_zstd::ZSTD_decompressSequencesSplitLitBuffer ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static
643674 {
643675 return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
643676 }
643677#endif
643678 return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
643679}
643680static size_t
643681ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
643682 const void* seqStart, size_t seqSize, int nbSeq,
643683 const ZSTD_longOffset_e isLongOffset)
643684{
643685 DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer");

◆ ZSTD_decompressSequencesLong()

size_t duckdb_zstd::ZSTD_decompressSequencesLong ( ZSTD_DCtx * dctx,
void * dst,
size_t maxDstSize,
const void * seqStart,
size_t seqSize,
int nbSeq,
const ZSTD_longOffset_e isLongOffset )
static
643707{
643708 DEBUGLOG(5, "ZSTD_decompressSequencesLong");

◆ ZSTD_totalHistorySize()

size_t duckdb_zstd::ZSTD_totalHistorySize ( BYTE * op,
BYTE const * virtualStart )
static
Returns
The total size of the history referenceable by zstd, including both the prefix and the extDict. At op any offset larger than this is invalid.

◆ ZSTD_getOffsetInfo()

ZSTD_OffsetInfo duckdb_zstd::ZSTD_getOffsetInfo ( const ZSTD_seqSymbol * offTable,
int nbSeq )
static
643742{
643743 ZSTD_OffsetInfo info = {0, 0};
643744 /* If nbSeq == 0, then the offTable is uninitialized, but we have
643745 * no sequences, so both values should be 0.
643746 */
643747 if (nbSeq != 0) {
643748 const void* ptr = offTable;
643749 U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
643750 const ZSTD_seqSymbol* table = offTable + 1;
643751 U32 const max = 1 << tableLog;
643752 U32 u;
643753 DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
643754
643755 assert(max <= (1 << OffFSELog)); /* max not too large */
643756 for (u=0; u<max; u++) {
643757 info.maxNbAdditionalBits = MAX(info.maxNbAdditionalBits, table[u].nbAdditionalBits);
643758 if (table[u].nbAdditionalBits > 22) info.longOffsetShare += 1;
643759 }
Definition duckdb.cpp:643722

◆ ZSTD_maxShortOffset()

size_t duckdb_zstd::ZSTD_maxShortOffset ( void )
static
Returns
The maximum offset we can decode in one read of our bitstream, without reloading more bits in the middle of the offset bits read. Any offsets larger than this must use the long offset decoder.
643774{
643775 if (MEM_64bits()) {
643776 /* We can decode any offset without reloading bits.
643777 * This might change if the max window size grows.
643778 */
643779 ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
643780 return (size_t)-1;
643781 } else {
643782 /* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1.
643783 * This offBase would require STREAM_ACCUMULATOR_MIN extra bits.
643784 * Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset.
Here is the call graph for this function:

◆ ZBUFF_DEPRECATED()

duckdb_zstd::ZBUFF_DEPRECATED ( "use ZSTD_CStreamInSize" )

Functions below provide recommended buffer sizes for Compression or Decompression operations. These sizes are just hints, they tend to offer better latency

Here is the call graph for this function:

◆ ZBUFF_isError()

unsigned duckdb_zstd::ZBUFF_isError ( size_t errorCode)

ZBUFF_isError() : tells if a return value is an error code

◆ ZBUFF_getErrorName()

const char * duckdb_zstd::ZBUFF_getErrorName ( size_t errorCode)

ZBUFF_getErrorName() : provides error code string from function result (useful for debugging)

◆ ZBUFF_createCCtx()

ZBUFF_CCtx * duckdb_zstd::ZBUFF_createCCtx ( void )
644259 : recommended buffer sizes (not compulsory)
644260* input : ZSTD_BLOCKSIZE_MAX (128 KB), internal unit size, it improves latency to use this value.
644261* output : ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + ZBUFF_endFrameSize : ensures it's always possible to write/flush/end a full block at best speed.
644262* ***********************************************************/

◆ ZBUFF_createCCtx_advanced()

ZBUFF_CCtx * duckdb_zstd::ZBUFF_createCCtx_advanced ( ZSTD_customMem customMem)
644264 {
644265
644266ZBUFF_CCtx* ZBUFF_createCCtx(void)
644267{

◆ ZBUFF_freeCCtx()

size_t duckdb_zstd::ZBUFF_freeCCtx ( ZBUFF_CCtx * zbc)
644272{

◆ ZBUFF_compressInit_advanced()

size_t duckdb_zstd::ZBUFF_compressInit_advanced ( ZBUFF_CCtx * zbc,
const void * dict,
size_t dictSize,
ZSTD_parameters params,
unsigned long long pledgedSrcSize )
644277{
644278 return ZSTD_freeCStream(zbc);
644279}
644280
644281
644282/* ====== Initialization ====== */
644283
644284size_t ZBUFF_compressInit_advanced(ZBUFF_CCtx* zbc,
644285 const void* dict, size_t dictSize,
644286 ZSTD_parameters params, unsigned long long pledgedSrcSize)
644287{
644288 if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* preserve "0 == unknown" behavior */
644289 FORWARD_IF_ERROR(ZSTD_CCtx_reset(zbc, ZSTD_reset_session_only), "");
644290 FORWARD_IF_ERROR(ZSTD_CCtx_setPledgedSrcSize(zbc, pledgedSrcSize), "");
644291
644293 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_windowLog, params.cParams.windowLog), "");
644294 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_hashLog, params.cParams.hashLog), "");
644295 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_chainLog, params.cParams.chainLog), "");
644296 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_searchLog, params.cParams.searchLog), "");
644297 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_minMatch, params.cParams.minMatch), "");
644298 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_targetLength, params.cParams.targetLength), "");
644299 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_strategy, params.cParams.strategy), "");
644300

◆ ZBUFF_compressInitDictionary()

size_t duckdb_zstd::ZBUFF_compressInitDictionary ( ZBUFF_CCtx * zbc,
const void * dict,
size_t dictSize,
int compressionLevel )

◆ ZBUFF_compressInit()

size_t duckdb_zstd::ZBUFF_compressInit ( ZBUFF_CCtx * zbc,
int compressionLevel )
644310{
644311 FORWARD_IF_ERROR(ZSTD_CCtx_reset(zbc, ZSTD_reset_session_only), "");
644312 FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(zbc, ZSTD_c_compressionLevel, compressionLevel), "");
644313 FORWARD_IF_ERROR(ZSTD_CCtx_loadDictionary(zbc, dict, dictSize), "");
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx *cctx, const void *dict, size_t dictSize)
Definition duckdb.cpp:621018

◆ ZBUFF_compressContinue()

size_t duckdb_zstd::ZBUFF_compressContinue ( ZBUFF_CCtx * zbc,
void * dst,
size_t * dstCapacityPtr,
const void * src,
size_t * srcSizePtr )
644318{
644319 return ZSTD_initCStream(zbc, compressionLevel);
644320}
644321
644322/* ====== Compression ====== */
644323
644324
644325size_t ZBUFF_compressContinue(ZBUFF_CCtx* zbc,
644326 void* dst, size_t* dstCapacityPtr,
644327 const void* src, size_t* srcSizePtr)
644328{
644329 size_t result;
644330 ZSTD_outBuffer outBuff;
644331 ZSTD_inBuffer inBuff;
644332 outBuff.dst = dst;
644333 outBuff.pos = 0;
644334 outBuff.size = *dstCapacityPtr;
644335 inBuff.src = src;
ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream *zcs, int compressionLevel)
Definition duckdb.cpp:625643

◆ ZBUFF_compressFlush()

size_t duckdb_zstd::ZBUFF_compressFlush ( ZBUFF_CCtx * zbc,
void * dst,
size_t * dstCapacityPtr )
644349{
644350 size_t result;
644351 ZSTD_outBuffer outBuff;

◆ ZBUFF_compressEnd()

size_t duckdb_zstd::ZBUFF_compressEnd ( ZBUFF_CCtx * zbc,
void * dst,
size_t * dstCapacityPtr )
644362{
644363 size_t result;
644364 ZSTD_outBuffer outBuff;

◆ ZBUFF_recommendedCInSize()

size_t duckdb_zstd::ZBUFF_recommendedCInSize ( void )

◆ ZBUFF_recommendedCOutSize()

size_t duckdb_zstd::ZBUFF_recommendedCOutSize ( void )

◆ ZBUFF_createDCtx()

ZBUFF_DCtx * duckdb_zstd::ZBUFF_createDCtx ( void )

◆ ZBUFF_createDCtx_advanced()

ZBUFF_DCtx * duckdb_zstd::ZBUFF_createDCtx_advanced ( ZSTD_customMem customMem)
644411 {
644412
644413ZBUFF_DCtx* ZBUFF_createDCtx(void)
644414{

◆ ZBUFF_freeDCtx()

size_t duckdb_zstd::ZBUFF_freeDCtx ( ZBUFF_DCtx * zbd)
644419{

◆ ZBUFF_decompressInitDictionary()

size_t duckdb_zstd::ZBUFF_decompressInitDictionary ( ZBUFF_DCtx * zbd,
const void * dict,
size_t dictSize )
644424{
644425 return ZSTD_freeDStream(zbd);
644426}
644427

◆ ZBUFF_decompressInit()

size_t duckdb_zstd::ZBUFF_decompressInit ( ZBUFF_DCtx * zbd)
644432{

◆ ZBUFF_decompressContinue()

size_t duckdb_zstd::ZBUFF_decompressContinue ( ZBUFF_DCtx * zbd,
void * dst,
size_t * dstCapacityPtr,
const void * src,
size_t * srcSizePtr )
644437{
644438 return ZSTD_initDStream(zbd);
644439}
644440
644441
644442/* *** Decompression *** */
644443
644444size_t ZBUFF_decompressContinue(ZBUFF_DCtx* zbd,
644445 void* dst, size_t* dstCapacityPtr,
644446 const void* src, size_t* srcSizePtr)
644447{
644448 ZSTD_outBuffer outBuff;
644449 ZSTD_inBuffer inBuff;
644450 size_t result;
644451 outBuff.dst = dst;
644452 outBuff.pos = 0;
644453 outBuff.size = *dstCapacityPtr;
644454 inBuff.src = src;
ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream *zds)
Definition duckdb.cpp:641044

◆ ZBUFF_recommendedDInSize()

size_t duckdb_zstd::ZBUFF_recommendedDInSize ( void )

◆ ZBUFF_recommendedDOutSize()

size_t duckdb_zstd::ZBUFF_recommendedDOutSize ( void )

◆ ZDICT_trainFromBuffer()

size_t duckdb_zstd::ZDICT_trainFromBuffer ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples )

Zstd dictionary builder

FAQ

Why should I use a dictionary?

Zstd can use dictionaries to improve compression ratio of small data. Traditionally small files don't compress well because there is very little repetition in a single sample, since it is small. But, if you are compressing many similar files, like a bunch of JSON records that share the same structure, you can train a dictionary on ahead of time on some samples of these files. Then, zstd can use the dictionary to find repetitions that are present across samples. This can vastly improve compression ratio.

When is a dictionary useful?

Dictionaries are useful when compressing many small files that are similar. The larger a file is, the less benefit a dictionary will have. Generally, we don't expect dictionary compression to be effective past 100KB. And the smaller a file is, the more we would expect the dictionary to help.

How do I use a dictionary?

Simply pass the dictionary to the zstd compressor with ZSTD_CCtx_loadDictionary(). The same dictionary must then be passed to the decompressor, using ZSTD_DCtx_loadDictionary(). There are other more advanced functions that allow selecting some options, see zstd.h for complete documentation.

What is a zstd dictionary?

A zstd dictionary has two pieces: Its header, and its content. The header contains a magic number, the dictionary ID, and entropy tables. These entropy tables allow zstd to save on header costs in the compressed file, which really matters for small data. The content is just bytes, which are repeated content that is common across many samples.

What is a raw content dictionary?

A raw content dictionary is just bytes. It doesn't have a zstd dictionary header, a dictionary ID, or entropy tables. Any buffer is a valid raw content dictionary.

How do I train a dictionary?

Gather samples from your use case. These samples should be similar to each other. If you have several use cases, you could try to train one dictionary per use case.

Pass those samples to ZDICT_trainFromBuffer() and that will train your dictionary. There are a few advanced versions of this function, but this is a great starting point. If you want to further tune your dictionary you could try ZDICT_optimizeTrainFromBuffer_cover(). If that is too slow you can try ZDICT_optimizeTrainFromBuffer_fastCover().

If the dictionary training function fails, that is likely because you either passed too few samples, or a dictionary would not be effective for your data. Look at the messages that the dictionary trainer printed, if it doesn't say too few samples, then a dictionary would not be effective.

How large should my dictionary be?

A reasonable dictionary size, the dictBufferCapacity, is about 100KB. The zstd CLI defaults to a 110KB dictionary. You likely don't need a dictionary larger than that. But, most use cases can get away with a smaller dictionary. The advanced dictionary builders can automatically shrink the dictionary for you, and select the smallest size that doesn't hurt compression ratio too much. See the shrinkDict parameter. A smaller dictionary can save memory, and potentially speed up compression.

How many samples should I provide to the dictionary builder?

We generally recommend passing ~100x the size of the dictionary in samples. A few thousand should suffice. Having too few samples can hurt the dictionaries effectiveness. Having more samples will only improve the dictionaries effectiveness. But having too many samples can slow down the dictionary builder.

How do I determine if a dictionary will be effective?

Simply train a dictionary and try it out. You can use zstd's built in benchmarking tool to test the dictionary effectiveness.

Benchmark levels 1-3 without a dictionary

zstd -b1e3 -r /path/to/my/files

Benchmark levels 1-3 with a dictionary

zstd -b1e3 -r /path/to/my/files -D /path/to/my/dictionary

When should I retrain a dictionary?

You should retrain a dictionary when its effectiveness drops. Dictionary effectiveness drops as the data you are compressing changes. Generally, we do expect dictionaries to "decay" over time, as your data changes, but the rate at which they decay depends on your use case. Internally, we regularly retrain dictionaries, and if the new dictionary performs significantly better than the old dictionary, we will ship the new dictionary.

I have a raw content dictionary, how do I turn it into a zstd dictionary?

If you have a raw content dictionary, e.g. by manually constructing it, or using a third-party dictionary builder, you can turn it into a zstd dictionary by using ZDICT_finalizeDictionary(). You'll also have to provide some samples of the data. It will add the zstd header to the raw content, which contains a dictionary ID and entropy tables, which will improve compression ratio, and allow zstd to write the dictionary ID into the frame, if you so choose.

Do I have to use zstd's dictionary builder?

No! You can construct dictionary content however you please, it is just bytes. It will always be valid as a raw content dictionary. If you want a zstd dictionary, which can improve compression ratio, use ZDICT_finalizeDictionary().

What is the attack surface of a zstd dictionary?

Zstd is heavily fuzz tested, including loading fuzzed dictionaries, so zstd should never crash, or access out-of-bounds memory no matter what the dictionary is. However, if an attacker can control the dictionary during decompression, they can cause zstd to generate arbitrary bytes, just like if they controlled the compressed data.

ZDICT_trainFromBuffer(): Train a dictionary from an array of samples. Redirect towards ZDICT_optimizeTrainFromBuffer_fastCover() single-threaded, with d=8, steps=4, f=20, and accel=1. Samples must be stored concatenated in a single flat buffer samplesBuffer, supplied with an array of sizes samplesSizes, providing the size of each sample, in order. The resulting dictionary will be saved into dictBuffer.

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). Note: Dictionary training will fail if there are not enough samples to construct a dictionary, or if most of the samples are too small (< 8 bytes being the lower limit). If dictionary training fails, you should use zstd without a dictionary, as the dictionary would've been ineffective anyways. If you believe your samples would benefit from a dictionary please open an issue with details, and we can look into it. Note: ZDICT_trainFromBuffer()'s memory usage is about 6 MB. Tips: In general, a reasonable dictionary has a size of ~ 100 KB. It's possible to select smaller or larger size, just by specifying dictBufferCapacity. In general, it's recommended to provide a few thousands samples, though this can vary a lot. It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
650299{
650301 DEBUGLOG(3, "ZDICT_trainFromBuffer");
650302 memset(&params, 0, sizeof(params));
650303 params.d = 8;
650304 params.steps = 4;
650305 /* Use default level since no compression level information is available */
650306 params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
Definition duckdb.cpp:644833
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZDICT_finalizeDictionary()

size_t duckdb_zstd::ZDICT_finalizeDictionary ( void * dstDictBuffer,
size_t maxDictSize,
const void * dictContent,
size_t dictContentSize,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_params_t parameters )

ZDICT_finalizeDictionary(): Given a custom content as a basis for dictionary, and a set of samples, finalize dictionary by adding headers and statistics according to the zstd dictionary format.

Samples must be stored concatenated in a flat buffer samplesBuffer, supplied with an array of sizes samplesSizes, providing the size of each sample in order. The samples are used to construct the statistics, so they should be representative of what you will compress with this dictionary.

The compression level can be set in parameters. You should pass the compression level you expect to use in production. The statistics for each compression level differ, so tuning the dictionary for the compression level can help quite a bit.

You can set an explicit dictionary ID in parameters, or allow us to pick a random dictionary ID for you, but we can't guarantee no collisions.

The dstDictBuffer and the dictContent may overlap, and the content will be appended to the end of the header. If the header + the content doesn't fit in maxDictSize the beginning of the content is truncated to make room, since it is presumed that the most profitable content is at the end of the dictionary, since that is the cheapest to reference.

maxDictSize must be >= max(dictContentSize, ZSTD_DICTSIZE_MIN).

Returns
: size of dictionary stored into dstDictBuffer (<= maxDictSize), or an error code, which can be tested by ZDICT_isError(). Note: ZDICT_finalizeDictionary() will push notifications into stderr if instructed to, using notificationLevel>0. NOTE: This function currently may fail in several edge cases including:
  • Not enough samples
  • Samples are uncompressible
  • Samples are all exactly the same
650049{
650050 size_t hSize;
650051#define HBUFFSIZE 256 /* should prove large enough for all entropy headers */
650052 BYTE header[HBUFFSIZE];
650053 int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
650054 U32 const notificationLevel = params.notificationLevel;
650055 /* The final dictionary content must be at least as large as the largest repcode */
650056 size_t const minContentSize = (size_t)ZDICT_maxRep(repStartValue);
650057 size_t paddingSize;
650058
650059 /* check conditions */
650060 DEBUGLOG(4, "ZDICT_finalizeDictionary");
650061 if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
650062 if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
650063
650064 /* dictionary header */
650065 MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
650066 { U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
650067 U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
650068 U32 const dictID = params.dictID ? params.dictID : compliantID;
650069 MEM_writeLE32(header+4, dictID);
650070 }
650071 hSize = 8;
650072
650073 /* entropy tables */
650074 DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
650075 DISPLAYLEVEL(2, "statistics ... \n");
650076 { size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
650077 compressionLevel,
650078 samplesBuffer, samplesSizes, nbSamples,
650079 customDictContent, dictContentSize,
650080 notificationLevel);
650081 if (ZDICT_isError(eSize)) return eSize;
650082 hSize += eSize;
650083 }
650084
650085 /* Shrink the content size if it doesn't fit in the buffer */
650086 if (hSize + dictContentSize > dictBufferCapacity) {
650087 dictContentSize = dictBufferCapacity - hSize;
650088 }
650089
650090 /* Pad the dictionary content with zeros if it is too small */
650091 if (dictContentSize < minContentSize) {
650092 RETURN_ERROR_IF(hSize + minContentSize > dictBufferCapacity, dstSize_tooSmall,
650093 "dictBufferCapacity too small to fit max repcode");
650094 paddingSize = minContentSize - dictContentSize;
650095 } else {
650096 paddingSize = 0;
650097 }
650098
650099 {
650100 size_t const dictSize = hSize + paddingSize + dictContentSize;
650101
650102 /* The dictionary consists of the header, optional padding, and the content.
650103 * The padding comes before the content because the "best" position in the
650104 * dictionary is the last byte.
650105 */
650106 BYTE* const outDictHeader = (BYTE*)dictBuffer;
650107 BYTE* const outDictPadding = outDictHeader + hSize;
650108 BYTE* const outDictContent = outDictPadding + paddingSize;
650109
650110 assert(dictSize <= dictBufferCapacity);
650111 assert(outDictContent + dictContentSize == (BYTE*)dictBuffer + dictSize);
650112
650113 /* First copy the customDictContent into its final location.
650114 * `customDictContent` and `dictBuffer` may overlap, so we must
650115 * do this before any other writes into the output buffer.
650116 * Then copy the header & padding into the output buffer.
650117 */
static U32 ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])
Definition duckdb.cpp:650029
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ZDICT_getDictID()

unsigned duckdb_zstd::ZDICT_getDictID ( const void * dictBuffer,
size_t dictSize )

extracts dictID;

Returns
zero if error (not a valid dictionary)
649285 { return ERR_isError(errorCode); }
649286
649287const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }

◆ ZDICT_getDictHeaderSize()

size_t duckdb_zstd::ZDICT_getDictHeaderSize ( const void * dictBuffer,
size_t dictSize )
649290{
649291 if (dictSize < 8) return 0;
649292 if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
649293 return MEM_readLE32((const char*)dictBuffer + 4);
649294}
649295
649296size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
649297{
649298 size_t headerSize;
649299 if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
649300
649301 { ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
649302 U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
649303 if (!bs || !wksp) {
649304 headerSize = ERROR(memory_allocation);
649305 } else {
649306 ZSTD_reset_compressedBlockState(bs);
649307 headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);
649308 }

◆ ZDICT_isError()

unsigned duckdb_zstd::ZDICT_isError ( size_t errorCode)

◆ ZDICT_getErrorName()

const char * duckdb_zstd::ZDICT_getErrorName ( size_t errorCode)

◆ ZDICT_trainFromBuffer_cover()

ZDICTLIB_STATIC_API size_t duckdb_zstd::ZDICT_trainFromBuffer_cover ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_cover_params_t parameters )

ZDICT_trainFromBuffer_cover(): Train a dictionary from an array of samples using the COVER algorithm. Samples must be stored concatenated in a single flat buffer samplesBuffer, supplied with an array of sizes samplesSizes, providing the size of each sample, in order. The resulting dictionary will be saved into dictBuffer.

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). See ZDICT_trainFromBuffer() for details on failure modes. Note: ZDICT_trainFromBuffer_cover() requires about 9 bytes of memory for each input byte. Tips: In general, a reasonable dictionary has a size of ~ 100 KB. It's possible to select smaller or larger size, just by specifying dictBufferCapacity. In general, it's recommended to provide a few thousands samples, though this can vary a lot. It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
645873{
645874 BYTE* const dict = (BYTE*)dictBuffer;
645875 COVER_ctx_t ctx;
645876 COVER_map_t activeDmers;
645877 parameters.splitPoint = 1.0;
645878 /* Initialize global data */
645879 g_displayLevel = (int)parameters.zParams.notificationLevel;
645880 /* Checks */
645881 if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
645882 DISPLAYLEVEL(1, "Cover parameters incorrect\n");
645883 return ERROR(parameter_outOfBound);
645884 }
645885 if (nbSamples == 0) {
645886 DISPLAYLEVEL(1, "Cover must have at least one input file\n");
645887 return ERROR(srcSize_wrong);
645888 }
645889 if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
645890 DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
645891 ZDICT_DICTSIZE_MIN);
645892 return ERROR(dstSize_tooSmall);
645893 }
645894 /* Initialize context and activeDmers */
645895 {
645896 size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
645897 parameters.d, parameters.splitPoint);
645898 if (ZSTD_isError(initVal)) {
645899 return initVal;
645900 }
645901 }
645902 COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, g_displayLevel);
645903 if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
645904 DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
645905 COVER_ctx_destroy(&ctx);
645906 return ERROR(memory_allocation);
645907 }
645908
645909 DISPLAYLEVEL(2, "Building dictionary\n");
645910 {
645911 const size_t tail =
645912 COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
645913 dictBufferCapacity, parameters);
645914 const size_t dictionarySize = ZDICT_finalizeDictionary(
645915 dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
645916 samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
645917 if (!ZSTD_isError(dictionarySize)) {
645918 DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, unsigned d, double splitPoint)
Definition duckdb.cpp:645672
static void COVER_ctx_destroy(COVER_ctx_t *ctx)
Definition duckdb.cpp:645643
static int COVER_checkParameters(ZDICT_cover_params_t parameters, size_t maxDictSize)
Definition duckdb.cpp:645619
ZDICTLIB_API size_t ZDICT_finalizeDictionary(void *dstDictBuffer, size_t maxDictSize, const void *dictContent, size_t dictContentSize, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_params_t parameters)
Definition duckdb.cpp:650038
static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs, COVER_map_t *activeDmers, void *dictBuffer, size_t dictBufferCapacity, ZDICT_cover_params_t parameters)
Definition duckdb.cpp:645810
static int COVER_map_init(COVER_map_t *map, U32 size)
Definition duckdb.cpp:645245
void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
Definition duckdb.cpp:645774
Definition duckdb.cpp:645342
unsigned notificationLevel
Definition duckdb.cpp:644729
Here is the call graph for this function:

◆ ZDICT_optimizeTrainFromBuffer_cover()

ZDICTLIB_STATIC_API size_t duckdb_zstd::ZDICT_optimizeTrainFromBuffer_cover ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_cover_params_t * parameters )

ZDICT_optimizeTrainFromBuffer_cover(): The same requirements as above hold for all the parameters except parameters. This function tries many parameter combinations and picks the best parameters. *parameters is filled with the best parameters found, dictionary constructed with those parameters is stored in dictBuffer.

All of the parameters d, k, steps are optional. If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}. if steps is zero it defaults to its default value. If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). On success *parameters contains the parameters selected. See ZDICT_trainFromBuffer() for details on failure modes. Note: ZDICT_optimizeTrainFromBuffer_cover() requires about 8 bytes of memory for each input byte and additionally another 5 bytes of memory for each byte of memory for each thread.
646261{
646262 /* constants */
646263 const unsigned nbThreads = parameters->nbThreads;
646264 const double splitPoint =
646265 parameters->splitPoint <= 0.0 ? COVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
646266 const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
646267 const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
646268 const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
646269 const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
646270 const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
646271 const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
646272 const unsigned kIterations =
646273 (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
646274 const unsigned shrinkDict = 0;
646275 /* Local variables */
646276 const int displayLevel = parameters->zParams.notificationLevel;
646277 unsigned iteration = 1;
646278 unsigned d;
646279 unsigned k;
646280 COVER_best_t best;
646281 POOL_ctx *pool = NULL;
646282 int warned = 0;
646283
646284 (void) kIterations;
646285 (void) iteration;
646286
646287 /* Checks */
646288 if (splitPoint <= 0 || splitPoint > 1) {
646289 LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
646290 return ERROR(parameter_outOfBound);
646291 }
646292 if (kMinK < kMaxD || kMaxK < kMinK) {
646293 LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
646294 return ERROR(parameter_outOfBound);
646295 }
646296 if (nbSamples == 0) {
646297 DISPLAYLEVEL(1, "Cover must have at least one input file\n");
646298 return ERROR(srcSize_wrong);
646299 }
646300 if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
646301 DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
646302 ZDICT_DICTSIZE_MIN);
646303 return ERROR(dstSize_tooSmall);
646304 }
646305 if (nbThreads > 1) {
646306 pool = POOL_create(nbThreads, 1);
646307 if (!pool) {
646308 return ERROR(memory_allocation);
646309 }
646310 }
646311 /* Initialization */
646312 COVER_best_init(&best);
646313 /* Turn down global display level to clean up display at level 2 and below */
646314 g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
646315 /* Loop through d first because each new value needs a new context */
646316 LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
646317 kIterations);
646318 for (d = kMinD; d <= kMaxD; d += 2) {
646319 /* Initialize the context for this value of d */
646320 COVER_ctx_t ctx;
646321 LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
646322 {
646323 const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint);
646324 if (ZSTD_isError(initVal)) {
646325 LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
646326 COVER_best_destroy(&best);
646327 POOL_free(pool);
646328 return initVal;
646329 }
646330 }
646331 if (!warned) {
646332 COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
646333 warned = 1;
646334 }
646335 /* Loop through k reusing the same context */
646336 for (k = kMinK; k <= kMaxK; k += kStepSize) {
646337 /* Prepare the arguments */
646340 LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
646341 if (!data) {
646342 LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
646343 COVER_best_destroy(&best);
646344 COVER_ctx_destroy(&ctx);
646345 POOL_free(pool);
646346 return ERROR(memory_allocation);
646347 }
646348 data->ctx = &ctx;
646349 data->best = &best;
646350 data->dictBufferCapacity = dictBufferCapacity;
646351 data->parameters = *parameters;
646352 data->parameters.k = k;
646353 data->parameters.d = d;
646354 data->parameters.splitPoint = splitPoint;
646355 data->parameters.steps = kSteps;
646356 data->parameters.shrinkDict = shrinkDict;
646357 data->parameters.zParams.notificationLevel = g_displayLevel;
646358 /* Check the parameters */
646359 if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
646360 DISPLAYLEVEL(1, "Cover parameters incorrect\n");
646361 free(data);
646362 continue;
646363 }
646364 /* Call the function and pass ownership of data to it */
646365 COVER_best_start(&best);
646366 if (pool) {
646367 POOL_add(pool, &COVER_tryParameters, data);
646368 } else {
646369 COVER_tryParameters(data);
646370 }
646371 /* Print status */
646372 LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
646373 (unsigned)((iteration * 100) / kIterations));
646374 ++iteration;
646375 }
646376 COVER_best_wait(&best);
646377 COVER_ctx_destroy(&ctx);
646378 }
646379 LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
646380 /* Fill the output buffer and parameters with output of the best parameters */
646381 {
646382 const size_t dictSize = best.dictSize;
646383 if (ZSTD_isError(best.compressedSize)) {
646384 const size_t compressedSize = best.compressedSize;
646385 COVER_best_destroy(&best);
646386 POOL_free(pool);
646387 return compressedSize;
646388 }
void POOL_add(POOL_ctx *ctx, POOL_function function, void *opaque)
Definition duckdb.cpp:611997
void COVER_best_start(COVER_best_t *best)
Definition duckdb.cpp:646022
void COVER_best_wait(COVER_best_t *best)
Definition duckdb.cpp:645992
static void COVER_tryParameters(void *opaque)
Definition duckdb.cpp:646205
void COVER_best_destroy(COVER_best_t *best)
Definition duckdb.cpp:646006
struct duckdb_zstd::COVER_tryParameters_data_s COVER_tryParameters_data_t
struct duckdb_zstd::COVER_best_s COVER_best_t
void COVER_best_init(COVER_best_t *best)
Definition duckdb.cpp:645978
Here is the call graph for this function:

◆ ZDICT_trainFromBuffer_fastCover()

ZDICTLIB_STATIC_API size_t duckdb_zstd::ZDICT_trainFromBuffer_fastCover ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_fastCover_params_t parameters )

ZDICT_trainFromBuffer_fastCover(): Train a dictionary from an array of samples using a modified version of COVER algorithm. Samples must be stored concatenated in a single flat buffer samplesBuffer, supplied with an array of sizes samplesSizes, providing the size of each sample, in order. d and k are required. All other parameters are optional, will use default values if not provided The resulting dictionary will be saved into dictBuffer.

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). See ZDICT_trainFromBuffer() for details on failure modes. Note: ZDICT_trainFromBuffer_fastCover() requires 6 * 2^f bytes of memory. Tips: In general, a reasonable dictionary has a size of ~ 100 KB. It's possible to select smaller or larger size, just by specifying dictBufferCapacity. In general, it's recommended to provide a few thousands samples, though this can vary a lot. It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
648958{
648959 BYTE* const dict = (BYTE*)dictBuffer;
648960 FASTCOVER_ctx_t ctx;
648961 ZDICT_cover_params_t coverParams;
648962 FASTCOVER_accel_t accelParams;
648963 /* Initialize global data */
648964 g_displayLevel = (int)parameters.zParams.notificationLevel;
648965 /* Assign splitPoint and f if not provided */
648966 parameters.splitPoint = 1.0;
648967 parameters.f = parameters.f == 0 ? DEFAULT_F : parameters.f;
648968 parameters.accel = parameters.accel == 0 ? DEFAULT_ACCEL : parameters.accel;
648969 /* Convert to cover parameter */
648970 memset(&coverParams, 0 , sizeof(coverParams));
648971 FASTCOVER_convertToCoverParams(parameters, &coverParams);
648972 /* Checks */
648973 if (!FASTCOVER_checkParameters(coverParams, dictBufferCapacity, parameters.f,
648974 parameters.accel)) {
648975 DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
648976 return ERROR(parameter_outOfBound);
648977 }
648978 if (nbSamples == 0) {
648979 DISPLAYLEVEL(1, "FASTCOVER must have at least one input file\n");
648980 return ERROR(srcSize_wrong);
648981 }
648982 if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
648983 DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
648984 ZDICT_DICTSIZE_MIN);
648985 return ERROR(dstSize_tooSmall);
648986 }
648987 /* Assign corresponding FASTCOVER_accel_t to accelParams*/
648988 accelParams = FASTCOVER_defaultAccelParameters[parameters.accel];
648989 /* Initialize context */
648990 {
648991 size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
648992 coverParams.d, parameters.splitPoint, parameters.f,
648993 accelParams);
648994 if (ZSTD_isError(initVal)) {
648995 DISPLAYLEVEL(1, "Failed to initialize context\n");
648996 return initVal;
648997 }
648998 }
648999 COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, g_displayLevel);
649000 /* Build the dictionary */
649001 DISPLAYLEVEL(2, "Building dictionary\n");
649002 {
649003 /* Initialize array to keep track of frequency of dmer within activeSegment */
649004 U16* segmentFreqs = (U16 *)calloc(((U64)1 << parameters.f), sizeof(U16));
649005 const size_t tail = FASTCOVER_buildDictionary(&ctx, ctx.freqs, dictBuffer,
649006 dictBufferCapacity, coverParams, segmentFreqs);
649007 const unsigned nbFinalizeSamples = (unsigned)(ctx.nbTrainSamples * ctx.accelParams.finalize / 100);
649008 const size_t dictionarySize = ZDICT_finalizeDictionary(
649009 dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
649010 samplesBuffer, samplesSizes, nbFinalizeSamples, coverParams.zParams);
649011 if (!ZSTD_isError(dictionarySize)) {
649012 DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
static size_t FASTCOVER_buildDictionary(const FASTCOVER_ctx_t *ctx, U32 *freqs, void *dictBuffer, size_t dictBufferCapacity, ZDICT_cover_params_t parameters, U16 *segmentFreqs)
Definition duckdb.cpp:648798
static size_t FASTCOVER_ctx_init(FASTCOVER_ctx_t *ctx, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, unsigned d, double splitPoint, unsigned f, FASTCOVER_accel_t accelParams)
Definition duckdb.cpp:648709
Definition duckdb.cpp:648499
Definition duckdb.cpp:648523
Definition duckdb.cpp:644822
Here is the call graph for this function:

◆ ZDICT_optimizeTrainFromBuffer_fastCover()

ZDICTLIB_STATIC_API size_t duckdb_zstd::ZDICT_optimizeTrainFromBuffer_fastCover ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_fastCover_params_t * parameters )

ZDICT_optimizeTrainFromBuffer_fastCover(): The same requirements as above hold for all the parameters except parameters. This function tries many parameter combinations (specifically, k and d combinations) and picks the best parameters. *parameters is filled with the best parameters found, dictionary constructed with those parameters is stored in dictBuffer. All of the parameters d, k, steps, f, and accel are optional. If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}. if steps is zero it defaults to its default value. If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000]. If f is zero, default value of 20 is used. If accel is zero, default value of 1 is used.

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). On success *parameters contains the parameters selected. See ZDICT_trainFromBuffer() for details on failure modes. Note: ZDICT_optimizeTrainFromBuffer_fastCover() requires about 6 * 2^f bytes of memory for each thread.
649028{
649029 ZDICT_cover_params_t coverParams;
649030 FASTCOVER_accel_t accelParams;
649031 /* constants */
649032 const unsigned nbThreads = parameters->nbThreads;
649033 const double splitPoint =
649034 parameters->splitPoint <= 0.0 ? FASTCOVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
649035 const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
649036 const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
649037 const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
649038 const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
649039 const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
649040 const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
649041 const unsigned kIterations =
649042 (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
649043 const unsigned f = parameters->f == 0 ? DEFAULT_F : parameters->f;
649044 const unsigned accel = parameters->accel == 0 ? DEFAULT_ACCEL : parameters->accel;
649045 const unsigned shrinkDict = 0;
649046 /* Local variables */
649047 const int displayLevel = (int)parameters->zParams.notificationLevel;
649048 unsigned iteration = 1;
649049 unsigned d;
649050 unsigned k;
649051 COVER_best_t best;
649052 POOL_ctx *pool = NULL;
649053 int warned = 0;
649054
649055 (void) kIterations;
649056 (void) iteration;
649057
649058 /* Checks */
649059 if (splitPoint <= 0 || splitPoint > 1) {
649060 LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect splitPoint\n");
649061 return ERROR(parameter_outOfBound);
649062 }
649063 if (accel == 0 || accel > FASTCOVER_MAX_ACCEL) {
649064 LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect accel\n");
649065 return ERROR(parameter_outOfBound);
649066 }
649067 if (kMinK < kMaxD || kMaxK < kMinK) {
649068 LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect k\n");
649069 return ERROR(parameter_outOfBound);
649070 }
649071 if (nbSamples == 0) {
649072 LOCALDISPLAYLEVEL(displayLevel, 1, "FASTCOVER must have at least one input file\n");
649073 return ERROR(srcSize_wrong);
649074 }
649075 if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
649076 LOCALDISPLAYLEVEL(displayLevel, 1, "dictBufferCapacity must be at least %u\n",
649077 ZDICT_DICTSIZE_MIN);
649078 return ERROR(dstSize_tooSmall);
649079 }
649080 if (nbThreads > 1) {
649081 pool = POOL_create(nbThreads, 1);
649082 if (!pool) {
649083 return ERROR(memory_allocation);
649084 }
649085 }
649086 /* Initialization */
649087 COVER_best_init(&best);
649088 memset(&coverParams, 0 , sizeof(coverParams));
649089 FASTCOVER_convertToCoverParams(*parameters, &coverParams);
649090 accelParams = FASTCOVER_defaultAccelParameters[accel];
649091 /* Turn down global display level to clean up display at level 2 and below */
649092 g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
649093 /* Loop through d first because each new value needs a new context */
649094 LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
649095 kIterations);
649096 for (d = kMinD; d <= kMaxD; d += 2) {
649097 /* Initialize the context for this value of d */
649098 FASTCOVER_ctx_t ctx;
649099 LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
649100 {
649101 size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, f, accelParams);
649102 if (ZSTD_isError(initVal)) {
649103 LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
649104 COVER_best_destroy(&best);
649105 POOL_free(pool);
649106 return initVal;
649107 }
649108 }
649109 if (!warned) {
649110 COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, displayLevel);
649111 warned = 1;
649112 }
649113 /* Loop through k reusing the same context */
649114 for (k = kMinK; k <= kMaxK; k += kStepSize) {
649115 /* Prepare the arguments */
649118 LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
649119 if (!data) {
649120 LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
649121 COVER_best_destroy(&best);
649122 FASTCOVER_ctx_destroy(&ctx);
649123 POOL_free(pool);
649124 return ERROR(memory_allocation);
649125 }
649126 data->ctx = &ctx;
649127 data->best = &best;
649128 data->dictBufferCapacity = dictBufferCapacity;
649129 data->parameters = coverParams;
649130 data->parameters.k = k;
649131 data->parameters.d = d;
649132 data->parameters.splitPoint = splitPoint;
649133 data->parameters.steps = kSteps;
649134 data->parameters.shrinkDict = shrinkDict;
649135 data->parameters.zParams.notificationLevel = (unsigned)g_displayLevel;
649136 /* Check the parameters */
649137 if (!FASTCOVER_checkParameters(data->parameters, dictBufferCapacity,
649138 data->ctx->f, accel)) {
649139 DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
649140 free(data);
649141 continue;
649142 }
649143 /* Call the function and pass ownership of data to it */
649144 COVER_best_start(&best);
649145 if (pool) {
649146 POOL_add(pool, &FASTCOVER_tryParameters, data);
649147 } else {
649149 }
649150 /* Print status */
649151 LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
649152 (unsigned)((iteration * 100) / kIterations));
649153 ++iteration;
649154 }
649155 COVER_best_wait(&best);
649156 FASTCOVER_ctx_destroy(&ctx);
649157 }
649158 LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
649159 /* Fill the output buffer and parameters with output of the best parameters */
649160 {
649161 const size_t dictSize = best.dictSize;
649162 if (ZSTD_isError(best.compressedSize)) {
649163 const size_t compressedSize = best.compressedSize;
649164 COVER_best_destroy(&best);
649165 POOL_free(pool);
649166 return compressedSize;
649167 }
649168 FASTCOVER_convertToFastCoverParams(best.parameters, parameters, f, accel);
static void FASTCOVER_ctx_destroy(FASTCOVER_ctx_t *ctx)
Definition duckdb.cpp:648664
struct duckdb_zstd::FASTCOVER_tryParameters_data_s FASTCOVER_tryParameters_data_t
static void FASTCOVER_tryParameters(void *opaque)
Definition duckdb.cpp:648871
Here is the call graph for this function:

◆ ZDICT_trainFromBuffer_legacy()

size_t duckdb_zstd::ZDICT_trainFromBuffer_legacy ( void * dictBuffer,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_legacy_params_t parameters )

ZDICT_trainFromBuffer_legacy(): Train a dictionary from an array of samples. Samples must be stored concatenated in a single flat buffer samplesBuffer, supplied with an array of sizes samplesSizes, providing the size of each sample, in order. The resulting dictionary will be saved into dictBuffer. parameters is optional and can be provided with values set to 0 to mean "default".

Returns
: size of dictionary stored into dictBuffer (<= dictBufferCapacity) or an error code, which can be tested with ZDICT_isError(). See ZDICT_trainFromBuffer() for details on failure modes. Tips: In general, a reasonable dictionary has a size of ~ 100 KB. It's possible to select smaller or larger size, just by specifying dictBufferCapacity. In general, it's recommended to provide a few thousands samples, though this can vary a lot. It's recommended that total size of all samples be about ~x100 times the target size of dictionary. Note: ZDICT_trainFromBuffer_legacy() will send notifications into stderr if instructed to, using notificationLevel>0.
650277{
650278 size_t result;
650279 void* newBuff;
650280 size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
650281 if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0; /* not enough content => no dictionary */
650282
650283 newBuff = malloc(sBuffSize + NOISELENGTH);
650284 if (!newBuff) return ERROR(memory_allocation);
650285
650286 memcpy(newBuff, samplesBuffer, sBuffSize);
650287 ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH); /* guard band, for end of buffer condition */

◆ ZDICT_addEntropyTablesFromBuffer()

size_t duckdb_zstd::ZDICT_addEntropyTablesFromBuffer ( void * dictBuffer,
size_t dictContentSize,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples )

◆ COVER_computeEpochs()

COVER_epoch_info_t duckdb_zstd::COVER_computeEpochs ( U32 maxDictSize,
U32 nbDmers,
U32 k,
U32 passes )

Computes the number of epochs and the size of each epoch. We will make sure that each epoch gets at least 10 * k bytes.

The COVER algorithms divide the data up into epochs of equal size and select one segment from each epoch.

Parameters
maxDictSizeThe maximum allowed dictionary size.
nbDmersThe number of dmers we are training on.
kThe parameter k (segment size).
passesThe target number of passes over the dmer corpus. More passes means a better dictionary.
645799{
645800 const U32 minEpochSize = k * 10;
645801 COVER_epoch_info_t epochs;
645802 epochs.num = MAX(1, maxDictSize / k / passes);
645803 epochs.size = nbDmers / epochs.num;
645804 if (epochs.size >= minEpochSize) {
645805 assert(epochs.size * epochs.num <= nbDmers);
Definition duckdb.cpp:645049

◆ COVER_warnOnSmallCorpus()

void duckdb_zstd::COVER_warnOnSmallCorpus ( size_t maxDictSize,
size_t nbDmers,
int displayLevel )

Warns the user when their corpus is too small.

645775 : &COVER_cmp), &COVER_group);
645776 ctx->freqs = ctx->suffix;
645777 ctx->suffix = NULL;
645778 return 0;
645779}
645780
645781void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
645782{
645783 const double ratio = (double)nbDmers / (double)maxDictSize;
645784 if (ratio >= 10) {
645785 return;
645786 }
645787 LOCALDISPLAYLEVEL(displayLevel, 1,
645788 "WARNING: The maximum dictionary size %u is too large "
static void COVER_group(COVER_ctx_t *ctx, const void *group, const void *groupEnd)
Definition duckdb.cpp:645475
static int COVER_cmp(COVER_ctx_t *ctx, const void *lp, const void *rp)
Definition duckdb.cpp:645380

◆ COVER_checkTotalCompressedSize()

size_t duckdb_zstd::COVER_checkTotalCompressedSize ( const ZDICT_cover_params_t parameters,
const size_t * samplesSizes,
const BYTE * samples,
size_t * offsets,
size_t nbTrainSamples,
size_t nbSamples,
BYTE *const dict,
size_t dictBufferCapacity )

Checks total compressed size of a dictionary

645933 {
645934 size_t totalCompressedSize = ERROR(GENERIC);
645935 /* Pointers */
645936 ZSTD_CCtx *cctx;
645937 ZSTD_CDict *cdict;
645938 void *dst;
645939 /* Local variables */
645940 size_t dstCapacity;
645941 size_t i;
645942 /* Allocate dst with enough space to compress the maximum sized sample */
645943 {
645944 size_t maxSampleSize = 0;
645945 i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
645946 for (; i < nbSamples; ++i) {
645947 maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
645948 }
645949 dstCapacity = ZSTD_compressBound(maxSampleSize);
645950 dst = malloc(dstCapacity);
645951 }
645952 /* Create the cctx and cdict */
645953 cctx = ZSTD_createCCtx();
645954 cdict = ZSTD_createCDict(dict, dictBufferCapacity,
645955 parameters.zParams.compressionLevel);
645956 if (!dst || !cctx || !cdict) {
645957 goto _compressCleanup;
645958 }
645959 /* Compress each sample and sum their sizes (or error) */
645960 totalCompressedSize = dictBufferCapacity;
645961 i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
645962 for (; i < nbSamples; ++i) {
645963 const size_t size = ZSTD_compress_usingCDict(
645964 cctx, dst, dstCapacity, samples + offsets[i],
645965 samplesSizes[i], cdict);
645966 if (ZSTD_isError(size)) {
645967 totalCompressedSize = size;
645968 goto _compressCleanup;
645969 }
645970 totalCompressedSize += size;
645971 }
645972_compressCleanup:
ZSTDLIB_API ZSTD_CDict * ZSTD_createCDict(const void *dictBuffer, size_t dictSize, int compressionLevel)
Definition duckdb.cpp:625275
ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict)
Definition duckdb.cpp:625478
int compressionLevel
Definition duckdb.cpp:644728

◆ COVER_sum()

size_t duckdb_zstd::COVER_sum ( const size_t * samplesSizes,
unsigned nbSamples )

Returns the sum of the sample sizes.

645373 {

◆ COVER_best_init()

void duckdb_zstd::COVER_best_init ( COVER_best_t * best)

Initialize the COVER_best_t.

645985 {
645986 if (best==NULL) return; /* compatible with init on NULL */
645987 (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);

◆ COVER_best_wait()

void duckdb_zstd::COVER_best_wait ( COVER_best_t * best)

Wait until liveJobs == 0.

645999 {
646000 if (!best) {
646001 return;

◆ COVER_best_destroy()

void duckdb_zstd::COVER_best_destroy ( COVER_best_t * best)

Call COVER_best_wait() and then destroy the COVER_best_t.

646013 {
646014 if (!best) {
646015 return;
646016 }

◆ COVER_best_start()

void duckdb_zstd::COVER_best_start ( COVER_best_t * best)

Called when a thread is about to be launched. Increments liveJobs.

646029 {

◆ COVER_best_finish()

void duckdb_zstd::COVER_best_finish ( COVER_best_t * best,
ZDICT_cover_params_t parameters,
COVER_dictSelection_t selection )

Called when a thread finishes executing, both on error or success. Decrements liveJobs and signals any waiting threads if liveJobs == 0. If this dictionary is the best so far save it and its parameters.

646046{
646047 void* dict = selection.dictContent;
646048 size_t compressedSize = selection.totalCompressedSize;
646049 size_t dictSize = selection.dictSize;
646050 if (!best) {
646051 return;
646052 }
646053 {
646054 size_t liveJobs;
646055 ZSTD_pthread_mutex_lock(&best->mutex);
646056 --best->liveJobs;
646057 liveJobs = best->liveJobs;
646058 /* If the new dictionary is better */
646059 if (compressedSize < best->compressedSize) {
646060 /* Allocate space if necessary */
646061 if (!best->dict || best->dictSize < dictSize) {
646062 if (best->dict) {
646063 free(best->dict);
646064 }
646065 best->dict = malloc(dictSize);
646066 if (!best->dict) {
646067 best->compressedSize = ERROR(GENERIC);
646068 best->dictSize = 0;
646069 ZSTD_pthread_cond_signal(&best->cond);
646070 ZSTD_pthread_mutex_unlock(&best->mutex);
646071 return;
646072 }
646073 }
646074 /* Save the dictionary, parameters, and size */
646075 if (dict) {
646076 memcpy(best->dict, dict, dictSize);
646077 best->dictSize = dictSize;
646078 best->parameters = parameters;
646079 best->compressedSize = compressedSize;
646080 }

◆ COVER_dictSelectionIsError()

unsigned duckdb_zstd::COVER_dictSelectionIsError ( COVER_dictSelection_t selection)

Error function for COVER_selectDict function. Checks if the return value is an error.

◆ COVER_dictSelectionError()

COVER_dictSelection_t duckdb_zstd::COVER_dictSelectionError ( size_t error)

Error function for COVER_selectDict function. Returns a struct where return.totalCompressedSize is a ZSTD error.

◆ COVER_dictSelectionFree()

void duckdb_zstd::COVER_dictSelectionFree ( COVER_dictSelection_t selection)

Always call after selectDict is called to free up used memory from newly created dictionary.

◆ COVER_selectDict()

COVER_dictSelection_t duckdb_zstd::COVER_selectDict ( BYTE * customDictContent,
size_t dictBufferCapacity,
size_t dictContentSize,
const BYTE * samplesBuffer,
const size_t * samplesSizes,
unsigned nbFinalizeSamples,
size_t nbCheckSamples,
size_t nbSamples,
ZDICT_cover_params_t params,
size_t * offsets,
size_t totalCompressedSize )

Called to finalize the dictionary and select one based on whether or not the shrink-dict flag was enabled. If enabled the dictionary used is the smallest dictionary within a specified regression of the compressed size from the largest dictionary.

646106 {
646107 free(selection.dictContent);
646108}
646109
646110COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBufferCapacity,
646111 size_t dictContentSize, const BYTE* samplesBuffer, const size_t* samplesSizes, unsigned nbFinalizeSamples,
646112 size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t* offsets, size_t totalCompressedSize) {
646113
646114 size_t largestDict = 0;
646115 size_t largestCompressed = 0;
646116 BYTE* customDictContentEnd = customDictContent + dictContentSize;
646117
646118 BYTE* largestDictbuffer = (BYTE*)malloc(dictBufferCapacity);
646119 BYTE* candidateDictBuffer = (BYTE*)malloc(dictBufferCapacity);
646120 double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
646121
646122 if (!largestDictbuffer || !candidateDictBuffer) {
646123 free(largestDictbuffer);
646124 free(candidateDictBuffer);
646125 return COVER_dictSelectionError(dictContentSize);
646126 }
646127
646128 /* Initial dictionary size and compressed size */
646129 memcpy(largestDictbuffer, customDictContent, dictContentSize);
646130 dictContentSize = ZDICT_finalizeDictionary(
646131 largestDictbuffer, dictBufferCapacity, customDictContent, dictContentSize,
646132 samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
646133
646134 if (ZDICT_isError(dictContentSize)) {
646135 free(largestDictbuffer);
646136 free(candidateDictBuffer);
646137 return COVER_dictSelectionError(dictContentSize);
646138 }
646139
646140 totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
646141 samplesBuffer, offsets,
646142 nbCheckSamples, nbSamples,
646143 largestDictbuffer, dictContentSize);
646144
646145 if (ZSTD_isError(totalCompressedSize)) {
646146 free(largestDictbuffer);
646147 free(candidateDictBuffer);
646148 return COVER_dictSelectionError(totalCompressedSize);
646149 }
646150
646151 if (params.shrinkDict == 0) {
646152 free(candidateDictBuffer);
646153 return setDictSelection(largestDictbuffer, dictContentSize, totalCompressedSize);
646154 }
646155
646156 largestDict = dictContentSize;
646157 largestCompressed = totalCompressedSize;
646158 dictContentSize = ZDICT_DICTSIZE_MIN;
646159
646160 /* Largest dict is initially at least ZDICT_DICTSIZE_MIN */
646161 while (dictContentSize < largestDict) {
646162 memcpy(candidateDictBuffer, largestDictbuffer, largestDict);
646163 dictContentSize = ZDICT_finalizeDictionary(
646164 candidateDictBuffer, dictBufferCapacity, customDictContentEnd - dictContentSize, dictContentSize,
646165 samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
646166
646167 if (ZDICT_isError(dictContentSize)) {
646168 free(largestDictbuffer);
646169 free(candidateDictBuffer);
646170 return COVER_dictSelectionError(dictContentSize);
646171
646172 }
646173
646174 totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
646175 samplesBuffer, offsets,
646176 nbCheckSamples, nbSamples,
646177 candidateDictBuffer, dictContentSize);
646178
646179 if (ZSTD_isError(totalCompressedSize)) {
646180 free(largestDictbuffer);
646181 free(candidateDictBuffer);
646182 return COVER_dictSelectionError(totalCompressedSize);
646183 }
646184
646185 if ((double)totalCompressedSize <= (double)largestCompressed * regressionTolerance) {
646186 free(largestDictbuffer);
646187 return setDictSelection( candidateDictBuffer, dictContentSize, totalCompressedSize );
646188 }
struct duckdb_zstd::COVER_dictSelection COVER_dictSelection_t
size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters, const size_t *samplesSizes, const BYTE *samples, size_t *offsets, size_t nbTrainSamples, size_t nbSamples, BYTE *const dict, size_t dictBufferCapacity)
Definition duckdb.cpp:645922
COVER_dictSelection_t COVER_selectDict(BYTE *customDictContent, size_t dictBufferCapacity, size_t dictContentSize, const BYTE *samplesBuffer, const size_t *samplesSizes, unsigned nbFinalizeSamples, size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t *offsets, size_t totalCompressedSize)
Definition duckdb.cpp:646103
COVER_dictSelection_t COVER_dictSelectionError(size_t error)
Definition duckdb.cpp:646091

◆ COVER_map_clear()

void duckdb_zstd::COVER_map_clear ( COVER_map_t * map)
static

Clear the map.

◆ COVER_map_init()

int duckdb_zstd::COVER_map_init ( COVER_map_t * map,
U32 size )
static

Initializes a map of the given size. Returns 1 on success and 0 on failure. The map must be destroyed with COVER_map_destroy(). The map is only guaranteed to be large enough to hold size elements.

645252 {
645253 map->sizeLog = ZSTD_highbit32(size) + 2;
645254 map->size = (U32)1 << map->sizeLog;
645255 map->sizeMask = map->size - 1;
645256 map->data = (COVER_map_pair_t *)malloc(map->size * sizeof(COVER_map_pair_t));
645257 if (!map->data) {

◆ COVER_map_hash()

U32 duckdb_zstd::COVER_map_hash ( COVER_map_t * map,
U32 key )
static

◆ COVER_map_index()

U32 duckdb_zstd::COVER_map_index ( COVER_map_t * map,
U32 key )
static

Helper function that returns the index that a key should be placed into.

645270 {
645271 return (key * COVER_prime4bytes) >> (32 - map->sizeLog);
645272}
645273
645277static U32 COVER_map_index(COVER_map_t *map, U32 key) {
645278 const U32 hash = COVER_map_hash(map, key);
645279 U32 i;
645280 for (i = hash;; i = (i + 1) & map->sizeMask) {
645281 COVER_map_pair_t *pos = &map->data[i];
645282 if (pos->value == MAP_EMPTY_VALUE) {
static const U32 COVER_prime4bytes
Definition duckdb.cpp:645262
static U32 COVER_map_index(COVER_map_t *map, U32 key)
Definition duckdb.cpp:645270

◆ COVER_map_at()

U32 * duckdb_zstd::COVER_map_at ( COVER_map_t * map,
U32 key )
static

Returns the pointer to the value for key. If key is not in the map, it is inserted and the value is set to 0. The map must not be full.

645296 {

◆ COVER_map_remove()

void duckdb_zstd::COVER_map_remove ( COVER_map_t * map,
U32 key )
static

Deletes key from the map if present.

645308 {
645309 U32 i = COVER_map_index(map, key);
645310 COVER_map_pair_t *del = &map->data[i];
645311 U32 shift = 1;
645312 if (del->value == MAP_EMPTY_VALUE) {
645313 return;
645314 }
645315 for (i = (i + 1) & map->sizeMask;; i = (i + 1) & map->sizeMask) {
645316 COVER_map_pair_t *const pos = &map->data[i];
645317 /* If the position is empty we are done */
645318 if (pos->value == MAP_EMPTY_VALUE) {
645319 del->value = MAP_EMPTY_VALUE;
645320 return;
645321 }
645322 /* If pos can be moved to del do so */
645323 if (((i - COVER_map_hash(map, pos->key)) & map->sizeMask) >= shift) {
645324 del->key = pos->key;
645325 del->value = pos->value;

◆ COVER_map_destroy()

void duckdb_zstd::COVER_map_destroy ( COVER_map_t * map)
static

Destroys a map that is inited with COVER_map_init().

◆ COVER_cmp()

int duckdb_zstd::COVER_cmp ( COVER_ctx_t * ctx,
const void * lp,
const void * rp )
static

Returns -1 if the dmer at lp is less than the dmer at rp. Return 0 if the dmers at lp and rp are equal. Returns 1 if the dmer at lp is greater than the dmer at rp.

◆ COVER_cmp8()

int duckdb_zstd::COVER_cmp8 ( COVER_ctx_t * ctx,
const void * lp,
const void * rp )
static

Faster version for d <= 8.

645395 {
645396 U64 const mask = (ctx->d == 8) ? (U64)-1 : (((U64)1 << (8 * ctx->d)) - 1);

◆ COVER_strict_cmp()

int WIN_CDECL duckdb_zstd::COVER_strict_cmp ( const void * lp,
const void * rp )
static

Same as COVER_cmp() except ties are broken by pointer value NOTE: g_coverCtx must be set to call this function. A global is required because qsort doesn't take an opaque pointer.

◆ COVER_strict_cmp8()

int WIN_CDECL duckdb_zstd::COVER_strict_cmp8 ( const void * lp,
const void * rp )
static

Faster version for d <= 8.

645413 : 1;
645414 }
645415 return result;
645416}

◆ COVER_lower_bound()

const size_t * duckdb_zstd::COVER_lower_bound ( const size_t * first,
const size_t * last,
size_t value )
static

Returns the first pointer in [first, last) whose element does not compare less than value. If no such element exists it returns last.

645433 {
645434 size_t count = (size_t)(last - first);
645435 assert(last >= first);
645436 while (count != 0) {
645437 size_t step = count / 2;
645438 const size_t *ptr = first;
645439 ptr += step;
645440 if (*ptr < value) {
645441 first = ++ptr;

◆ COVER_groupBy()

void duckdb_zstd::COVER_groupBy ( const void * data,
size_t count,
size_t size,
COVER_ctx_t * ctx,
int(* cmp )(COVER_ctx_t *, const void *, const void *),
void(* grp )(COVER_ctx_t *, const void *, const void *) )
static

Generic groupBy function. Groups an array sorted by cmp into groups with equivalent values. Calls grp for each group.

645458 {
645459 const BYTE *ptr = (const BYTE *)data;
645460 size_t num = 0;
645461 while (num < count) {
645462 const BYTE *grpEnd = ptr + size;
645463 ++num;
645464 while (num < count && cmp(ctx, ptr, grpEnd) == 0) {

◆ COVER_group()

void duckdb_zstd::COVER_group ( COVER_ctx_t * ctx,
const void * group,
const void * groupEnd )
static

Called on each group of positions with the same dmer. Counts the frequency of each dmer and saves it in the suffix array. Fills ctx->dmerAt.

645483 {
645484 /* The group consists of all the positions with the same first d bytes. */
645485 const U32 *grpPtr = (const U32 *)group;
645486 const U32 *grpEnd = (const U32 *)groupEnd;
645487 /* The dmerId is how we will reference this dmer.
645488 * This allows us to map the whole dmer space to a much smaller space, the
645489 * size of the suffix array.
645490 */
645491 const U32 dmerId = (U32)(grpPtr - ctx->suffix);
645492 /* Count the number of samples this dmer shows up in */
645493 U32 freq = 0;
645494 /* Details */
645495 const size_t *curOffsetPtr = ctx->offsets;
645496 const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
645497 /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
645498 * different sample than the last.
645499 */
645500 size_t curSampleEnd = ctx->offsets[0];
645501 for (; grpPtr != grpEnd; ++grpPtr) {
645502 /* Save the dmerId for this position so we can get back to it. */
645503 ctx->dmerAt[*grpPtr] = dmerId;
645504 /* Dictionaries only help for the first reference to the dmer.
645505 * After that zstd can reference the match from the previous reference.
645506 * So only count each dmer once for each sample it is in.
645507 */
645508 if (*grpPtr < curSampleEnd) {
645509 continue;
645510 }
645511 freq += 1;
645512 /* Binary search to find the end of the sample *grpPtr is in.
645513 * In the common case that grpPtr + 1 == grpEnd we can skip the binary
645514 * search because the loop is over.
645515 */
645516 if (grpPtr + 1 != grpEnd) {
645517 const size_t *sampleEndPtr =
645518 COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
645519 curSampleEnd = *sampleEndPtr;
645520 curOffsetPtr = sampleEndPtr + 1;
645521 }
645522 }
static const size_t * COVER_lower_bound(const size_t *first, const size_t *last, size_t value)
Definition duckdb.cpp:645425

◆ COVER_selectSegment()

COVER_segment_t duckdb_zstd::COVER_selectSegment ( const COVER_ctx_t * ctx,
U32 * freqs,
COVER_map_t * activeDmers,
U32 begin,
U32 end,
ZDICT_cover_params_t parameters )
static

Selects the best segment in an epoch. Segments of are scored according to the function:

Let F(d) be the frequency of dmer d. Let S_i be the dmer at position i of segment S which has length k.

Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})

Once the dmer d is in the dictionary we set F(d) = 0.

645539 {k-d+1})
645540 *
645541 * Once the dmer d is in the dictionary we set F(d) = 0.
645542 */
645543static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
645544 COVER_map_t *activeDmers, U32 begin,
645545 U32 end,
645546 ZDICT_cover_params_t parameters) {
645547 /* Constants */
645548 const U32 k = parameters.k;
645549 const U32 d = parameters.d;
645550 const U32 dmersInK = k - d + 1;
645551 /* Try each segment (activeSegment) and save the best (bestSegment) */
645552 COVER_segment_t bestSegment = {0, 0, 0};
645553 COVER_segment_t activeSegment;
645554 /* Reset the activeDmers in the segment */
645555 COVER_map_clear(activeDmers);
645556 /* The activeSegment starts at the beginning of the epoch. */
645557 activeSegment.begin = begin;
645558 activeSegment.end = begin;
645559 activeSegment.score = 0;
645560 /* Slide the activeSegment through the whole epoch.
645561 * Save the best segment in bestSegment.
645562 */
645563 while (activeSegment.end < end) {
645564 /* The dmerId for the dmer at the next position */
645565 U32 newDmer = ctx->dmerAt[activeSegment.end];
645566 /* The entry in activeDmers for this dmerId */
645567 U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
645568 /* If the dmer isn't already present in the segment add its score. */
645569 if (*newDmerOcc == 0) {
645570 /* The paper suggest using the L-0.5 norm, but experiments show that it
645571 * doesn't help.
645572 */
645573 activeSegment.score += freqs[newDmer];
645574 }
645575 /* Add the dmer to the segment */
645576 activeSegment.end += 1;
645577 *newDmerOcc += 1;
645578
645579 /* If the window is now too large, drop the first position */
645580 if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
645581 U32 delDmer = ctx->dmerAt[activeSegment.begin];
645582 U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
645583 activeSegment.begin += 1;
645584 *delDmerOcc -= 1;
645585 /* If this is the last occurrence of the dmer, subtract its score */
645586 if (*delDmerOcc == 0) {
645587 COVER_map_remove(activeDmers, delDmer);
645588 activeSegment.score -= freqs[delDmer];
645589 }
645590 }
645591
645592 /* If this segment is the best so far save it */
645593 if (activeSegment.score > bestSegment.score) {
645594 bestSegment = activeSegment;
645595 }
645596 }
645597 {
645598 /* Trim off the zero frequency head and tail from the segment. */
645599 U32 newBegin = bestSegment.end;
645600 U32 newEnd = bestSegment.begin;
645601 U32 pos;
645602 for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
645603 U32 freq = freqs[ctx->dmerAt[pos]];
645604 if (freq != 0) {
645605 newBegin = MIN(newBegin, pos);
645606 newEnd = pos + 1;
645607 }
645608 }
645609 bestSegment.begin = newBegin;
645610 bestSegment.end = newEnd;
645611 }
645612 {
645613 /* Zero out the frequency of each dmer covered by the chosen segment. */
static void COVER_map_remove(COVER_map_t *map, U32 key)
Definition duckdb.cpp:645301
static void COVER_map_clear(COVER_map_t *map)
Definition duckdb.cpp:645235
static U32 * COVER_map_at(COVER_map_t *map, U32 key)
Definition duckdb.cpp:645289
static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs, COVER_map_t *activeDmers, U32 begin, U32 end, ZDICT_cover_params_t parameters)
Definition duckdb.cpp:645536
Definition duckdb.cpp:645040

◆ COVER_checkParameters()

int duckdb_zstd::COVER_checkParameters ( ZDICT_cover_params_t parameters,
size_t maxDictSize )
static

Check the validity of the parameters. Returns non-zero if the parameters are valid and 0 otherwise.

645627 {
645628 /* k and d are required parameters */
645629 if (parameters.d == 0 || parameters.k == 0) {
645630 return 0;
645631 }
645632 /* k <= maxDictSize */
645633 if (parameters.k > maxDictSize) {
645634 return 0;
645635 }
645636 /* d <= k */
645637 if (parameters.d > parameters.k) {
645638 return 0;

◆ COVER_ctx_destroy()

void duckdb_zstd::COVER_ctx_destroy ( COVER_ctx_t * ctx)
static

Clean up a context initialized with COVER_ctx_init().

645650 {
645651 if (!ctx) {
645652 return;
645653 }
645654 if (ctx->suffix) {
645655 free(ctx->suffix);
645656 ctx->suffix = NULL;
645657 }
645658 if (ctx->freqs) {
645659 free(ctx->freqs);
645660 ctx->freqs = NULL;
645661 }
645662 if (ctx->dmerAt) {
645663 free(ctx->dmerAt);

◆ COVER_ctx_init()

size_t duckdb_zstd::COVER_ctx_init ( COVER_ctx_t * ctx,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
unsigned d,
double splitPoint )
static

Prepare a context for dictionary building. The context is only dependent on the parameter d and can be used multiple times. Returns 0 on success or error code on error. The context must be destroyed with COVER_ctx_destroy().

645682{
645683 const BYTE *const samples = (const BYTE *)samplesBuffer;
645684 const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
645685 /* Split samples into testing and training sets */
645686 const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
645687 const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
645688 const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
645689 const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
645690
645691 (void) testSamplesSize;
645692
645693 /* Checks */
645694 if (totalSamplesSize < MAX(d, sizeof(U64)) ||
645695 totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
645696 DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
645697 (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
645698 return ERROR(srcSize_wrong);
645699 }
645700 /* Check if there are at least 5 training samples */
645701 if (nbTrainSamples < 5) {
645702 DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
645703 return ERROR(srcSize_wrong);
645704 }
645705 /* Check if there's testing sample */
645706 if (nbTestSamples < 1) {
645707 DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
645708 return ERROR(srcSize_wrong);
645709 }
645710 /* Zero the context */
645711 memset(ctx, 0, sizeof(*ctx));
645712 DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
645713 (unsigned)trainingSamplesSize);
645714 DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
645715 (unsigned)testSamplesSize);
645716 ctx->samples = samples;
645717 ctx->samplesSizes = samplesSizes;
645718 ctx->nbSamples = nbSamples;
645719 ctx->nbTrainSamples = nbTrainSamples;
645720 ctx->nbTestSamples = nbTestSamples;
645721 /* Partial suffix array */
645722 ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
645723 ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
645724 /* Maps index to the dmerID */
645725 ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
645726 /* The offsets of each file */
645727 ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
645728 if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
645729 DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
645730 COVER_ctx_destroy(ctx);
645731 return ERROR(memory_allocation);
645732 }
645733 ctx->freqs = NULL;
645734 ctx->d = d;
645735
645736 /* Fill offsets from the samplesSizes */
645737 {
645738 U32 i;
645739 ctx->offsets[0] = 0;
645740 for (i = 1; i <= nbSamples; ++i) {
645741 ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
645742 }
645743 }
645744 DISPLAYLEVEL(2, "Constructing partial suffix array\n");
645745 {
645746 /* suffix is a partial suffix array.
645747 * It only sorts suffixes by their first parameters.d bytes.
645748 * The sort is stable, so each dmer group is sorted by position in input.
645749 */
645750 U32 i;
645751 for (i = 0; i < ctx->suffixSize; ++i) {
645752 ctx->suffix[i] = i;
645753 }
645754 /* qsort doesn't take an opaque pointer, so pass as a global.
645755 * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is.
645756 */
645757 g_coverCtx = ctx;
645758#if defined(__OpenBSD__)
645759 mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32),
645760 (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
645761#else
645762 qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
645763 (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
645764#endif
645765 }
645766 DISPLAYLEVEL(2, "Computing frequencies\n");
645767 /* For each dmer group (group of positions with the same first d bytes):
645768 * 1. For each position we set dmerAt[position] = dmerID. The dmerID is
645769 * (groupBeginPtr - suffix). This allows us to go from position to
645770 * dmerID so we can look up values in freq.
645771 * 2. We calculate how many samples the dmer occurs in and save it in
645772 * freqs[dmerId].
#define COVER_MAX_SAMPLES_SIZE
Definition duckdb.cpp:645170
static int WIN_CDECL COVER_strict_cmp(const void *lp, const void *rp)
Definition duckdb.cpp:645403
static int WIN_CDECL COVER_strict_cmp8(const void *lp, const void *rp)
Definition duckdb.cpp:645413
size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples)
Definition duckdb.cpp:645366

◆ COVER_buildDictionary()

size_t duckdb_zstd::COVER_buildDictionary ( const COVER_ctx_t * ctx,
U32 * freqs,
COVER_map_t * activeDmers,
void * dictBuffer,
size_t dictBufferCapacity,
ZDICT_cover_params_t parameters )
static

Given the prepared context build the dictionary.

645820 {
645821 BYTE *const dict = (BYTE *)dictBuffer;
645822 size_t tail = dictBufferCapacity;
645823 /* Divide the data into epochs. We will select one segment from each epoch. */
645825 (U32)dictBufferCapacity, (U32)ctx->suffixSize, parameters.k, 4);
645826 const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3));
645827 size_t zeroScoreRun = 0;
645828 size_t epoch;
645829 DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
645830 (U32)epochs.num, (U32)epochs.size);
645831 /* Loop through the epochs until there are no more segments or the dictionary
645832 * is full.
645833 */
645834 for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
645835 const U32 epochBegin = (U32)(epoch * epochs.size);
645836 const U32 epochEnd = epochBegin + epochs.size;
645837 size_t segmentSize;
645838 /* Select a segment */
645840 ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
645841 /* If the segment covers no dmers, then we are out of content.
645842 * There may be new content in other epochs, for continue for some time.
645843 */
645844 if (segment.score == 0) {
645845 if (++zeroScoreRun >= maxZeroScoreRun) {
645846 break;
645847 }
645848 continue;
645849 }
645850 zeroScoreRun = 0;
645851 /* Trim the segment if necessary and if it is too small then we are done */
645852 segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
645853 if (segmentSize < parameters.d) {
645854 break;
645855 }
645856 /* We fill the dictionary from the back to allow the best segments to be
645857 * referenced with the smallest offsets.
645858 */
645859 tail -= segmentSize;
645860 memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize, U32 nbDmers, U32 k, U32 passes)
Definition duckdb.cpp:645790

◆ setDictSelection()

COVER_dictSelection_t duckdb_zstd::setDictSelection ( BYTE * buf,
size_t s,
size_t csz )
static
646082 {
646083 ZSTD_pthread_cond_broadcast(&best->cond);
646084 }
646085 ZSTD_pthread_mutex_unlock(&best->mutex);
646086 }
646087}
646088
646089static COVER_dictSelection_t setDictSelection(BYTE* buf, size_t s, size_t csz)

◆ COVER_tryParameters()

void duckdb_zstd::COVER_tryParameters ( void * opaque)
static

Tries a set of parameters and updates the COVER_best_t with the results. This function is thread safe if zstd is compiled with multithreaded support. It takes its parameters as an OWNING opaque pointer to support threading.

646213{
646214 /* Save parameters as local variables */
646216 const COVER_ctx_t *const ctx = data->ctx;
646217 const ZDICT_cover_params_t parameters = data->parameters;
646218 size_t dictBufferCapacity = data->dictBufferCapacity;
646219 size_t totalCompressedSize = ERROR(GENERIC);
646220 /* Allocate space for hash table, dict, and freqs */
646221 COVER_map_t activeDmers;
646222 BYTE* const dict = (BYTE*)malloc(dictBufferCapacity);
646223 COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
646224 U32* const freqs = (U32*)malloc(ctx->suffixSize * sizeof(U32));
646225 if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
646226 DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
646227 goto _cleanup;
646228 }
646229 if (!dict || !freqs) {
646230 DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
646231 goto _cleanup;
646232 }
646233 /* Copy the frequencies because we need to modify them */
646234 memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
646235 /* Build the dictionary */
646236 {
646237 const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
646238 dictBufferCapacity, parameters);
646239 selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
646240 ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
646241 totalCompressedSize);
646242
646243 if (COVER_dictSelectionIsError(selection)) {
646244 DISPLAYLEVEL(1, "Failed to select dictionary\n");
646245 goto _cleanup;
646246 }
646247 }
646248_cleanup:
unsigned COVER_dictSelectionIsError(COVER_dictSelection_t selection)
Definition duckdb.cpp:646095

◆ divsufsort()

int duckdb_zstd::divsufsort ( const unsigned char * T,
int * SA,
int n,
int openMP )

Constructs the suffix array of a given string.

Parameters
T[0..n-1] The input string.
SA[0..n-1] The output array of suffixes.
nThe length of the given string.
openMPenables OpenMP optimization.
Returns
0 if no error occurred, -1 or -2 otherwise.
648325 {
648326 int *bucket_A, *bucket_B;
648327 int m;
648328 int err = 0;
648329
648330 /* Check arguments. */
648331 if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; }
648332 else if(n == 0) { return 0; }
648333 else if(n == 1) { SA[0] = 0; return 0; }
648334 else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; }
648335
648336 bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int));
648337 bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int));
648338
648339 /* Suffixsort. */
648340 if((bucket_A != NULL) && (bucket_B != NULL)) {
648341 m = sort_typeBstar(T, SA, bucket_A, bucket_B, n, openMP);
648342 construct_SA(T, SA, bucket_A, bucket_B, n, m);
648343 } else {
648344 err = -2;

◆ divbwt()

int duckdb_zstd::divbwt ( const unsigned char * T,
unsigned char * U,
int * A,
int n,
unsigned char * num_indexes,
int * indexes,
int openMP )

Constructs the burrows-wheeler transformed string of a given string.

Parameters
T[0..n-1] The input string.
U[0..n-1] The output string. (can be T)
A[0..n-1] The temporary array. (can be NULL)
nThe length of the given string.
num_indexesThe length of secondary indexes array. (can be NULL)
indexesThe secondary indexes array. (can be NULL)
openMPenables OpenMP optimization.
Returns
The primary index if no error occurred, -1 or -2 otherwise.
648354 {
648355 int *B;
648356 int *bucket_A, *bucket_B;
648357 int m, pidx, i;
648358
648359 /* Check arguments. */
648360 if((T == NULL) || (U == NULL) || (n < 0)) { return -1; }
648361 else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; }
648362
648363 if((B = A) == NULL) { B = (int *)malloc((size_t)(n + 1) * sizeof(int)); }
648364 bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int));
648365 bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int));
648366
648367 /* Burrows-Wheeler Transform. */
648368 if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) {
648369 m = sort_typeBstar(T, B, bucket_A, bucket_B, n, openMP);
648370
648371 if (num_indexes == NULL || indexes == NULL) {
648372 pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m);
648373 } else {
648374 pidx = construct_BWT_indexes(T, B, bucket_A, bucket_B, n, m, num_indexes, indexes);
648375 }
648376
648377 /* Copy to output string. */
648378 U[0] = T[n - 1];
648379 for(i = 0; i < pidx; ++i) { U[i + 1] = (unsigned char)B[i]; }
648380 for(i += 1; i < n; ++i) { U[i] = (unsigned char)B[i]; }
648381 pidx += 1;
648382 } else {
648383 pidx = -2;
648384 }

◆ ss_ilg()

INLINE int duckdb_zstd::ss_ilg ( int n)
static
646633 {
646634#if SS_BLOCKSIZE == 0
646635 return (n & 0xffff0000) ?
646636 ((n & 0xff000000) ?
646637 24 + lg_table[(n >> 24) & 0xff] :
646638 16 + lg_table[(n >> 16) & 0xff]) :
646639 ((n & 0x0000ff00) ?
646640 8 + lg_table[(n >> 8) & 0xff] :
646641 0 + lg_table[(n >> 0) & 0xff]);
646642#elif SS_BLOCKSIZE < 256

◆ ss_isqrt()

INLINE int duckdb_zstd::ss_isqrt ( int x)
static
646676 {
646677 int y, e;
646678
646679 if(x >= (SS_BLOCKSIZE * SS_BLOCKSIZE)) { return SS_BLOCKSIZE; }
646680 e = (x & 0xffff0000) ?
646681 ((x & 0xff000000) ?
646682 24 + lg_table[(x >> 24) & 0xff] :
646683 16 + lg_table[(x >> 16) & 0xff]) :
646684 ((x & 0x0000ff00) ?
646685 8 + lg_table[(x >> 8) & 0xff] :
646686 0 + lg_table[(x >> 0) & 0xff]);
646687
646688 if(e >= 16) {
646689 y = sqq_table[x >> ((e - 6) - (e & 1))] << ((e >> 1) - 7);
646690 if(e >= 24) { y = (y + 1 + x / y) >> 1; }
646691 y = (y + 1 + x / y) >> 1;
646692 } else if(e >= 8) {

◆ ss_compare()

INLINE int duckdb_zstd::ss_compare ( const unsigned char * T,
const int * p1,
const int * p2,
int depth )
static
646711 {
646712 const unsigned char *U1, *U2, *U1n, *U2n;
646713
646714 for(U1 = T + depth + *p1,
646715 U2 = T + depth + *p2,
646716 U1n = T + *(p1 + 1) + 2,
646717 U2n = T + *(p2 + 1) + 2;
646718 (U1 < U1n) && (U2 < U2n) && (*U1 == *U2);
cv::Point2i p1

◆ ss_insertionsort()

void duckdb_zstd::ss_insertionsort ( const unsigned char * T,
const int * PA,
int * first,
int * last,
int depth )
static
646736 {
646737 int *i, *j;
646738 int t;
646739 int r;
646740
646741 for(i = last - 2; first <= i; --i) {
646742 for(t = *i, j = i + 1; 0 < (r = ss_compare(T, PA + t, PA + *j, depth));) {

◆ ss_fixdown()

INLINE void duckdb_zstd::ss_fixdown ( const unsigned char * Td,
const int * PA,
int * SA,
int i,
int size )
static
646761 {
646762 int j, k;
646763 int v;
646764 int c, d, e;
646765

◆ ss_heapsort()

void duckdb_zstd::ss_heapsort ( const unsigned char * Td,
const int * PA,
int * SA,
int size )
static
646777 {
646778 int i, m;
646779 int t;
646780
646781 m = size;
646782 if((size % 2) == 0) {
646783 m--;
646784 if(Td[PA[SA[m / 2]]] < Td[PA[SA[m]]]) { SWAP(SA[m], SA[m / 2]); }
646785 }
646786
646787 for(i = m / 2 - 1; 0 <= i; --i) { ss_fixdown(Td, PA, SA, i, m); }

◆ ss_median3()

INLINE int * duckdb_zstd::ss_median3 ( const unsigned char * Td,
const int * PA,
int * v1,
int * v2,
int * v3 )
static
646803 {
646804 int *t;

◆ ss_median5()

INLINE int * duckdb_zstd::ss_median5 ( const unsigned char * Td,
const int * PA,
int * v1,
int * v2,
int * v3,
int * v4,
int * v5 )
static
646817 {
646818 int *t;
646819 if(Td[PA[*v2]] > Td[PA[*v3]]) { SWAP(v2, v3); }

◆ ss_pivot()

INLINE int * duckdb_zstd::ss_pivot ( const unsigned char * Td,
const int * PA,
int * first,
int * last )
static
646824 { return v4; }
646825 return v3;
646826}
646827
646828/* Returns the pivot element. */
646829static INLINE
646830int *
646831ss_pivot(const unsigned char *Td, const int *PA, int *first, int *last) {
646832 int *middle;
646833 int t;
646834
646835 t = last - first;
646836 middle = first + t / 2;
646837
646838 if(t <= 512) {
646839 if(t <= 32) {
646840 return ss_median3(Td, PA, first, middle, last - 1);
646841 } else {
646842 t >>= 2;
646843 return ss_median5(Td, PA, first, first + t, middle, last - 1 - t, last - 1);
646844 }

◆ ss_partition()

INLINE int * duckdb_zstd::ss_partition ( const int * PA,
int * first,
int * last,
int depth )
static
646860 {
646861 int *a, *b;
646862 int t;
646863 for(a = first - 1, b = last;;) {
646864 for(; (++a < b) && ((PA[*a] + depth) >= (PA[*a + 1] + 1));) { *a = ~*a; }
646865 for(; (a < --b) && ((PA[*b] + depth) < (PA[*b + 1] + 1));) { }
646866 if(b <= a) { break; }

◆ ss_mintrosort()

void duckdb_zstd::ss_mintrosort ( const unsigned char * T,
const int * PA,
int * first,
int * last,
int depth )
static
646871 { *first = ~*first; }
646872 return a;
646873}
646874
646875/* Multikey introsort for medium size groups. */
646876static
646877void
646878ss_mintrosort(const unsigned char *T, const int *PA,
646879 int *first, int *last,
646880 int depth) {
646881#define STACK_SIZE SS_MISORT_STACKSIZE
646882 struct { int *a, *b, c; int d; } stack[STACK_SIZE];
646883 const unsigned char *Td;
646884 int *a, *b, *c, *d, *e, *f;
646885 int s, t;
646886 int ssize;
646887 int limit;
646888 int v, x = 0;
646889
646890 for(ssize = 0, limit = ss_ilg(last - first);;) {
646891
646892 if((last - first) <= SS_INSERTIONSORT_THRESHOLD) {
646893#if 1 < SS_INSERTIONSORT_THRESHOLD
646894 if(1 < (last - first)) { ss_insertionsort(T, PA, first, last, depth); }
646895#endif
646896 STACK_POP(first, last, depth, limit);
646897 continue;
646898 }
646899
646900 Td = T + depth;
646901 if(limit-- == 0) { ss_heapsort(Td, PA, first, last - first); }
646902 if(limit < 0) {
646903 for(a = first + 1, v = Td[PA[*first]]; a < last; ++a) {
646904 if((x = Td[PA[*a]]) != v) {
646905 if(1 < (a - first)) { break; }
646906 v = x;
646907 first = a;
646908 }
646909 }
646910 if(Td[PA[*first] - 1] < v) {
646911 first = ss_partition(PA, first, a, depth);
646912 }
646913 if((a - first) <= (last - a)) {
646914 if(1 < (a - first)) {
646915 STACK_PUSH(a, last, depth, -1);
646916 last = a, depth += 1, limit = ss_ilg(a - first);
646917 } else {
646918 first = a, limit = -1;
646919 }
646920 } else {
646921 if(1 < (last - a)) {
646922 STACK_PUSH(first, a, depth + 1, ss_ilg(a - first));
646923 first = a, limit = -1;
646924 } else {
646925 last = a, depth += 1, limit = ss_ilg(a - first);
646926 }
646927 }
646928 continue;
646929 }
646930
646931 /* choose pivot */
646932 a = ss_pivot(Td, PA, first, last);
646933 v = Td[PA[*a]];
646934 SWAP(*first, *a);
646935
646936 /* partition */
646937 for(b = first; (++b < last) && ((x = Td[PA[*b]]) == v);) { }
646938 if(((a = b) < last) && (x < v)) {
646939 for(; (++b < last) && ((x = Td[PA[*b]]) <= v);) {
646940 if(x == v) { SWAP(*b, *a); ++a; }
646941 }
646942 }
646943 for(c = last; (b < --c) && ((x = Td[PA[*c]]) == v);) { }
646944 if((b < (d = c)) && (x > v)) {
646945 for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) {
646946 if(x == v) { SWAP(*c, *d); --d; }
646947 }
646948 }
646949 for(; b < c;) {
646950 SWAP(*b, *c);
646951 for(; (++b < c) && ((x = Td[PA[*b]]) <= v);) {
646952 if(x == v) { SWAP(*b, *a); ++a; }
646953 }
646954 for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) {
646955 if(x == v) { SWAP(*c, *d); --d; }
646956 }
646957 }
646958
646959 if(a <= d) {
646960 c = b - 1;
646961
646962 if((s = a - first) > (t = b - a)) { s = t; }
646963 for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
646964 if((s = d - c) > (t = last - d - 1)) { s = t; }
646965 for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
646966
646967 a = first + (b - a), c = last - (d - c);
646968 b = (v <= Td[PA[*a] - 1]) ? a : ss_partition(PA, a, c, depth);
646969
646970 if((a - first) <= (last - c)) {
646971 if((last - c) <= (c - b)) {
646972 STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
646973 STACK_PUSH(c, last, depth, limit);
646974 last = a;
646975 } else if((a - first) <= (c - b)) {
646976 STACK_PUSH(c, last, depth, limit);
646977 STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
646978 last = a;
646979 } else {
646980 STACK_PUSH(c, last, depth, limit);
646981 STACK_PUSH(first, a, depth, limit);
646982 first = b, last = c, depth += 1, limit = ss_ilg(c - b);
646983 }
646984 } else {
646985 if((a - first) <= (c - b)) {
646986 STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
646987 STACK_PUSH(first, a, depth, limit);
646988 first = c;
646989 } else if((last - c) <= (c - b)) {
646990 STACK_PUSH(first, a, depth, limit);
646991 STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
646992 first = c;
646993 } else {
646994 STACK_PUSH(first, a, depth, limit);
646995 STACK_PUSH(c, last, depth, limit);
646996 first = b, last = c, depth += 1, limit = ss_ilg(c - b);
646997 }
646998 }
646999 } else {
647000 limit += 1;
647001 if(Td[PA[*first] - 1] < v) {
647002 first = ss_partition(PA, first, last, depth);

◆ ss_blockswap()

INLINE void duckdb_zstd::ss_blockswap ( int * a,
int * b,
int n )
static

◆ ss_rotate()

INLINE void duckdb_zstd::ss_rotate ( int * first,
int * middle,
int * last )
static
647022 {
647023 t = *a, *a = *b, *b = t;
647024 }
647025}
647026
647027static INLINE
647028void
647029ss_rotate(int *first, int *middle, int *last) {
647030 int *a, *b, t;
647031 int l, r;
647032 l = middle - first, r = last - middle;
647033 for(; (0 < l) && (0 < r);) {
647034 if(l == r) { ss_blockswap(first, middle, l); break; }
647035 if(l < r) {
647036 a = last - 1, b = middle - 1;
647037 t = *a;
647038 do {
647039 *a-- = *b, *b-- = *a;
647040 if(b < first) {
647041 *a = t;
647042 last = a;
647043 if((r -= l + 1) <= l) { break; }
647044 a -= 1, b = middle - 1;
647045 t = *a;
647046 }
647047 } while(1);
647048 } else {
647049 a = first, b = middle;
647050 t = *a;
647051 do {
647052 *a++ = *b, *b++ = *a;
647053 if(last <= b) {
647054 *a = t;
647055 first = a + 1;
647056 if((l -= r + 1) <= r) { break; }

◆ ss_inplacemerge()

void duckdb_zstd::ss_inplacemerge ( const unsigned char * T,
const int * PA,
int * first,
int * middle,
int * last,
int depth )
static
647072 {
647073 const int *p;
647074 int *a, *b;
647075 int len, half;
647076 int q, r;
647077 int x;
647078
647079 for(;;) {
647080 if(*(last - 1) < 0) { x = 1; p = PA + ~*(last - 1); }
647081 else { x = 0; p = PA + *(last - 1); }
647082 for(a = first, len = middle - first, half = len >> 1, r = -1;
647083 0 < len;
647084 len = half, half >>= 1) {
647085 b = a + half;
647086 q = ss_compare(T, PA + ((0 <= *b) ? *b : ~*b), p, depth);
647087 if(q < 0) {
647088 a = b + 1;
647089 half -= (len & 1) ^ 1;
647090 } else {
647091 r = q;
647092 }
647093 }
647094 if(a < middle) {
647095 if(r == 0) { *a = ~*a; }
647096 ss_rotate(a, middle, last);
647097 last -= middle - a;
647098 middle = a;

◆ ss_mergeforward()

void duckdb_zstd::ss_mergeforward ( const unsigned char * T,
const int * PA,
int * first,
int * middle,
int * last,
int * buf,
int depth )
static
647115 {
647116 int *a, *b, *c, *bufend;
647117 int t;
647118 int r;
647119
647120 bufend = buf + (middle - first) - 1;
647121 ss_blockswap(buf, first, middle - first);
647122
647123 for(t = *(a = first), b = buf, c = middle;;) {
647124 r = ss_compare(T, PA + *b, PA + *c, depth);
647125 if(r < 0) {
647126 do {
647127 *a++ = *b;
647128 if(bufend <= b) { *bufend = t; return; }
647129 *b++ = *a;
647130 } while(*b < 0);
647131 } else if(r > 0) {
647132 do {
647133 *a++ = *c, *c++ = *a;
647134 if(last <= c) {
647135 while(b < bufend) { *a++ = *b, *b++ = *a; }
647136 *a = *b, *b = t;
647137 return;
647138 }
647139 } while(*c < 0);
647140 } else {
647141 *c = ~*c;
647142 do {
647143 *a++ = *b;
647144 if(bufend <= b) { *bufend = t; return; }
647145 *b++ = *a;
647146 } while(*b < 0);
647147
647148 do {
647149 *a++ = *c, *c++ = *a;
647150 if(last <= c) {
647151 while(b < bufend) { *a++ = *b, *b++ = *a; }

◆ ss_mergebackward()

void duckdb_zstd::ss_mergebackward ( const unsigned char * T,
const int * PA,
int * first,
int * middle,
int * last,
int * buf,
int depth )
static
647165 {
647166 const int *p1, *p2;
647167 int *a, *b, *c, *bufend;
647168 int t;
647169 int r;
647170 int x;
647171
647172 bufend = buf + (last - middle) - 1;
647173 ss_blockswap(buf, middle, last - middle);
647174
647175 x = 0;
647176 if(*bufend < 0) { p1 = PA + ~*bufend; x |= 1; }
647177 else { p1 = PA + *bufend; }
647178 if(*(middle - 1) < 0) { p2 = PA + ~*(middle - 1); x |= 2; }
647179 else { p2 = PA + *(middle - 1); }
647180 for(t = *(a = last - 1), b = bufend, c = middle - 1;;) {
647181 r = ss_compare(T, p1, p2, depth);
647182 if(0 < r) {
647183 if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; }
647184 *a-- = *b;
647185 if(b <= buf) { *buf = t; break; }
647186 *b-- = *a;
647187 if(*b < 0) { p1 = PA + ~*b; x |= 1; }
647188 else { p1 = PA + *b; }
647189 } else if(r < 0) {
647190 if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; }
647191 *a-- = *c, *c-- = *a;
647192 if(c < first) {
647193 while(buf < b) { *a-- = *b, *b-- = *a; }
647194 *a = *b, *b = t;
647195 break;
647196 }
647197 if(*c < 0) { p2 = PA + ~*c; x |= 2; }
647198 else { p2 = PA + *c; }
647199 } else {
647200 if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; }
647201 *a-- = ~*b;
647202 if(b <= buf) { *buf = t; break; }
647203 *b-- = *a;
647204 if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; }
647205 *a-- = *c, *c-- = *a;
647206 if(c < first) {
647207 while(buf < b) { *a-- = *b, *b-- = *a; }
647208 *a = *b, *b = t;
647209 break;
647210 }

◆ ss_swapmerge()

void duckdb_zstd::ss_swapmerge ( const unsigned char * T,
const int * PA,
int * first,
int * middle,
int * last,
int * buf,
int bufsize,
int depth )
static
647224 {
647225#define STACK_SIZE SS_SMERGE_STACKSIZE
647226#define GETIDX(a) ((0 <= (a)) ? (a) : (~(a)))
647227#define MERGE_CHECK(a, b, c)\
647228 do {\
647229 if(((c) & 1) ||\
647230 (((c) & 2) && (ss_compare(T, PA + GETIDX(*((a) - 1)), PA + *(a), depth) == 0))) {\
647231 *(a) = ~*(a);\
647232 }\
647233 if(((c) & 4) && ((ss_compare(T, PA + GETIDX(*((b) - 1)), PA + *(b), depth) == 0))) {\
647234 *(b) = ~*(b);\
647235 }\
647236 } while(0)
647237 struct { int *a, *b, *c; int d; } stack[STACK_SIZE];
647238 int *l, *r, *lm, *rm;
647239 int m, len, half;
647240 int ssize;
647241 int check, next;
647242
647243 for(check = 0, ssize = 0;;) {
647244 if((last - middle) <= bufsize) {
647245 if((first < middle) && (middle < last)) {
647246 ss_mergebackward(T, PA, first, middle, last, buf, depth);
647247 }
647248 MERGE_CHECK(first, last, check);
647249 STACK_POP(first, middle, last, check);
647250 continue;
647251 }
647252
647253 if((middle - first) <= bufsize) {
647254 if(first < middle) {
647255 ss_mergeforward(T, PA, first, middle, last, buf, depth);
647256 }
647257 MERGE_CHECK(first, last, check);
647258 STACK_POP(first, middle, last, check);
647259 continue;
647260 }
647261
647262 for(m = 0, len = MIN(middle - first, last - middle), half = len >> 1;
647263 0 < len;
647264 len = half, half >>= 1) {
647265 if(ss_compare(T, PA + GETIDX(*(middle + m + half)),
647266 PA + GETIDX(*(middle - m - half - 1)), depth) < 0) {
647267 m += half + 1;
647268 half -= (len & 1) ^ 1;
647269 }
647270 }
647271
647272 if(0 < m) {
647273 lm = middle - m, rm = middle + m;
647274 ss_blockswap(lm, middle, m);
647275 l = r = middle, next = 0;
647276 if(rm < last) {
647277 if(*rm < 0) {
647278 *rm = ~*rm;
647279 if(first < lm) { for(; *--l < 0;) { } next |= 4; }
647280 next |= 1;
647281 } else if(first < lm) {
647282 for(; *r < 0; ++r) { }
647283 next |= 2;
647284 }
647285 }
647286
647287 if((l - first) <= (last - r)) {
647288 STACK_PUSH(r, rm, last, (next & 3) | (check & 4));
647289 middle = lm, last = l, check = (check & 3) | (next & 4);
647290 } else {
647291 if((next & 2) && (r == middle)) { next ^= 6; }
647292 STACK_PUSH(first, lm, l, (check & 3) | (next & 4));
647293 first = r, middle = rm, check = (next & 3) | (check & 4);
647294 }
647295 } else {
647296 if(ss_compare(T, PA + GETIDX(*(middle - 1)), PA + *middle, depth) == 0) {
647297 *middle = ~*middle;

◆ sssort()

void duckdb_zstd::sssort ( const unsigned char * T,
const int * PA,
int * first,
int * last,
int * buf,
int bufsize,
int depth,
int n,
int lastsuffix )
static
647317 {
647318 int *a;
647319#if SS_BLOCKSIZE != 0
647320 int *b, *middle, *curbuf;
647321 int j, k, curbufsize, limit;
647322#endif
647323 int i;
647324
647325 if(lastsuffix != 0) { ++first; }
647326
647327#if SS_BLOCKSIZE == 0
647328 ss_mintrosort(T, PA, first, last, depth);
647329#else
647330 if((bufsize < SS_BLOCKSIZE) &&
647331 (bufsize < (last - first)) &&
647332 (bufsize < (limit = ss_isqrt(last - first)))) {
647333 if(SS_BLOCKSIZE < limit) { limit = SS_BLOCKSIZE; }
647334 buf = middle = last - limit, bufsize = limit;
647335 } else {
647336 middle = last, limit = 0;
647337 }
647338 for(a = first, i = 0; SS_BLOCKSIZE < (middle - a); a += SS_BLOCKSIZE, ++i) {
647339#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
647340 ss_mintrosort(T, PA, a, a + SS_BLOCKSIZE, depth);
647341#elif 1 < SS_BLOCKSIZE
647342 ss_insertionsort(T, PA, a, a + SS_BLOCKSIZE, depth);
647343#endif
647344 curbufsize = last - (a + SS_BLOCKSIZE);
647345 curbuf = a + SS_BLOCKSIZE;
647346 if(curbufsize <= bufsize) { curbufsize = bufsize, curbuf = buf; }
647347 for(b = a, k = SS_BLOCKSIZE, j = i; j & 1; b -= k, k <<= 1, j >>= 1) {
647348 ss_swapmerge(T, PA, b - k, b, b + k, curbuf, curbufsize, depth);
647349 }
647350 }
647351#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
647352 ss_mintrosort(T, PA, a, middle, depth);
647353#elif 1 < SS_BLOCKSIZE
647354 ss_insertionsort(T, PA, a, middle, depth);
647355#endif
647356 for(k = SS_BLOCKSIZE; i != 0; k <<= 1, i >>= 1) {
647357 if(i & 1) {
647358 ss_swapmerge(T, PA, a - k, a, middle, buf, bufsize, depth);
647359 a -= k;
647360 }
647361 }
647362 if(limit != 0) {
647363#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
647364 ss_mintrosort(T, PA, middle, last, depth);
647365#elif 1 < SS_BLOCKSIZE
647366 ss_insertionsort(T, PA, middle, last, depth);
647367#endif
647368 ss_inplacemerge(T, PA, first, middle, last, depth);
647369 }
647370#endif
647371
647372 if(lastsuffix != 0) {
647373 /* Insert last type B* suffix. */
647374 int PAi[2]; PAi[0] = PA[*(first - 1)], PAi[1] = n - 2;
647375 for(a = first, i = *(first - 1);

◆ tr_ilg()

INLINE int duckdb_zstd::tr_ilg ( int n)
static
647389 {
647390 return (n & 0xffff0000) ?

◆ tr_insertionsort()

void duckdb_zstd::tr_insertionsort ( const int * ISAd,
int * first,
int * last )
static
647405 {
647406 int *a, *b;
647407 int t, r;
647408
647409 for(a = first + 1; a < last; ++a) {
647410 for(t = *a, b = a - 1; 0 > (r = ISAd[t] - ISAd[*b]);) {

◆ tr_fixdown()

INLINE void duckdb_zstd::tr_fixdown ( const int * ISAd,
int * SA,
int i,
int size )
static
647424 {
647425 int j, k;
647426 int v;
647427 int c, d, e;
647428

◆ tr_heapsort()

void duckdb_zstd::tr_heapsort ( const int * ISAd,
int * SA,
int size )
static
647440 {
647441 int i, m;
647442 int t;
647443
647444 m = size;
647445 if((size % 2) == 0) {
647446 m--;
647447 if(ISAd[SA[m / 2]] < ISAd[SA[m]]) { SWAP(SA[m], SA[m / 2]); }
647448 }
647449
647450 for(i = m / 2 - 1; 0 <= i; --i) { tr_fixdown(ISAd, SA, i, m); }

◆ tr_median3()

INLINE int * duckdb_zstd::tr_median3 ( const int * ISAd,
int * v1,
int * v2,
int * v3 )
static
647465 {
647466 int *t;

◆ tr_median5()

INLINE int * duckdb_zstd::tr_median5 ( const int * ISAd,
int * v1,
int * v2,
int * v3,
int * v4,
int * v5 )
static
647479 {
647480 int *t;
647481 if(ISAd[*v2] > ISAd[*v3]) { SWAP(v2, v3); }

◆ tr_pivot()

INLINE int * duckdb_zstd::tr_pivot ( const int * ISAd,
int * first,
int * last )
static
647486 { return v4; }
647487 return v3;
647488}
647489
647490/* Returns the pivot element. */
647491static INLINE
647492int *
647493tr_pivot(const int *ISAd, int *first, int *last) {
647494 int *middle;
647495 int t;
647496
647497 t = last - first;
647498 middle = first + t / 2;
647499
647500 if(t <= 512) {
647501 if(t <= 32) {
647502 return tr_median3(ISAd, first, middle, last - 1);
647503 } else {
647504 t >>= 2;
647505 return tr_median5(ISAd, first, first + t, middle, last - 1 - t, last - 1);
647506 }

◆ trbudget_init()

INLINE void duckdb_zstd::trbudget_init ( trbudget_t * budget,
int chance,
int incval )
static

◆ trbudget_check()

INLINE int duckdb_zstd::trbudget_check ( trbudget_t * budget,
int size )
static
647528 {
647529 budget->chance = chance;
647530 budget->remain = budget->incval = incval;
647531}
647532
647533static INLINE
647534int

◆ tr_partition()

INLINE void duckdb_zstd::tr_partition ( const int * ISAd,
int * first,
int * middle,
int * last,
int ** pa,
int ** pb,
int v )
static
647550 {
647551 int *a, *b, *c, *d, *e, *f;
647552 int t, s;
647553 int x = 0;
647554
647555 for(b = middle - 1; (++b < last) && ((x = ISAd[*b]) == v);) { }
647556 if(((a = b) < last) && (x < v)) {
647557 for(; (++b < last) && ((x = ISAd[*b]) <= v);) {
647558 if(x == v) { SWAP(*b, *a); ++a; }
647559 }
647560 }
647561 for(c = last; (b < --c) && ((x = ISAd[*c]) == v);) { }
647562 if((b < (d = c)) && (x > v)) {
647563 for(; (b < --c) && ((x = ISAd[*c]) >= v);) {
647564 if(x == v) { SWAP(*c, *d); --d; }
647565 }
647566 }
647567 for(; b < c;) {
647568 SWAP(*b, *c);
647569 for(; (++b < c) && ((x = ISAd[*b]) <= v);) {
647570 if(x == v) { SWAP(*b, *a); ++a; }
647571 }
647572 for(; (b < --c) && ((x = ISAd[*c]) >= v);) {
647573 if(x == v) { SWAP(*c, *d); --d; }
647574 }
647575 }
647576
647577 if(a <= d) {
647578 c = b - 1;
647579 if((s = a - first) > (t = b - a)) { s = t; }

◆ tr_copy()

void duckdb_zstd::tr_copy ( int * ISA,
const int * SA,
int * first,
int * a,
int * b,
int * last,
int depth )
static
647592 {
647593 /* sort suffixes of middle partition
647594 by using sorted order of suffixes of left and right partition. */
647595 int *c, *d, *e;
647596 int s, v;
647597
647598 v = b - SA - 1;
647599 for(c = first, d = a - 1; c <= d; ++c) {
647600 if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
647601 *++d = s;
647602 ISA[s] = d - SA;
647603 }
647604 }

◆ tr_partialcopy()

void duckdb_zstd::tr_partialcopy ( int * ISA,
const int * SA,
int * first,
int * a,
int * b,
int * last,
int depth )
static
647617 {
647618 int *c, *d, *e;
647619 int s, v;
647620 int rank, lastrank, newrank = -1;
647621
647622 v = b - SA - 1;
647623 lastrank = -1;
647624 for(c = first, d = a - 1; c <= d; ++c) {
647625 if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
647626 *++d = s;
647627 rank = ISA[s + depth];
647628 if(lastrank != rank) { lastrank = rank; newrank = d - SA; }
647629 ISA[s] = newrank;
647630 }
647631 }
647632
647633 lastrank = -1;
647634 for(e = d; first <= e; --e) {
647635 rank = ISA[*e];
647636 if(lastrank != rank) { lastrank = rank; newrank = e - SA; }
647637 if(newrank != rank) { ISA[*e] = newrank; }
647638 }
647639
647640 lastrank = -1;
647641 for(c = last - 1, e = d + 1, d = b; e < d; --c) {
647642 if((0 <= (s = *c - depth)) && (ISA[s] == v)) {

◆ tr_introsort()

void duckdb_zstd::tr_introsort ( int * ISA,
const int * ISAd,
int * SA,
int * first,
int * last,
trbudget_t * budget )
static
647655 {
647656#define STACK_SIZE TR_STACKSIZE
647657 struct { const int *a; int *b, *c; int d, e; }stack[STACK_SIZE];
647658 int *a, *b, *c;
647659 int t;
647660 int v, x = 0;
647661 int incr = ISAd - ISA;
647662 int limit, next;
647663 int ssize, trlink = -1;
647664
647665 for(ssize = 0, limit = tr_ilg(last - first);;) {
647666
647667 if(limit < 0) {
647668 if(limit == -1) {
647669 /* tandem repeat partition */
647670 tr_partition(ISAd - incr, first, first, last, &a, &b, last - SA - 1);
647671
647672 /* update ranks */
647673 if(a < last) {
647674 for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; }
647675 }
647676 if(b < last) {
647677 for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; }
647678 }
647679
647680 /* push */
647681 if(1 < (b - a)) {
647682 STACK_PUSH5(NULL, a, b, 0, 0);
647683 STACK_PUSH5(ISAd - incr, first, last, -2, trlink);
647684 trlink = ssize - 2;
647685 }
647686 if((a - first) <= (last - b)) {
647687 if(1 < (a - first)) {
647688 STACK_PUSH5(ISAd, b, last, tr_ilg(last - b), trlink);
647689 last = a, limit = tr_ilg(a - first);
647690 } else if(1 < (last - b)) {
647691 first = b, limit = tr_ilg(last - b);
647692 } else {
647693 STACK_POP5(ISAd, first, last, limit, trlink);
647694 }
647695 } else {
647696 if(1 < (last - b)) {
647697 STACK_PUSH5(ISAd, first, a, tr_ilg(a - first), trlink);
647698 first = b, limit = tr_ilg(last - b);
647699 } else if(1 < (a - first)) {
647700 last = a, limit = tr_ilg(a - first);
647701 } else {
647702 STACK_POP5(ISAd, first, last, limit, trlink);
647703 }
647704 }
647705 } else if(limit == -2) {
647706 /* tandem repeat copy */
647707 a = stack[--ssize].b, b = stack[ssize].c;
647708 if(stack[ssize].d == 0) {
647709 tr_copy(ISA, SA, first, a, b, last, ISAd - ISA);
647710 } else {
647711 if(0 <= trlink) { stack[trlink].d = -1; }
647712 tr_partialcopy(ISA, SA, first, a, b, last, ISAd - ISA);
647713 }
647714 STACK_POP5(ISAd, first, last, limit, trlink);
647715 } else {
647716 /* sorted partition */
647717 if(0 <= *first) {
647718 a = first;
647719 do { ISA[*a] = a - SA; } while((++a < last) && (0 <= *a));
647720 first = a;
647721 }
647722 if(first < last) {
647723 a = first; do { *a = ~*a; } while(*++a < 0);
647724 next = (ISA[*a] != ISAd[*a]) ? tr_ilg(a - first + 1) : -1;
647725 if(++a < last) { for(b = first, v = a - SA - 1; b < a; ++b) { ISA[*b] = v; } }
647726
647727 /* push */
647728 if(trbudget_check(budget, a - first)) {
647729 if((a - first) <= (last - a)) {
647730 STACK_PUSH5(ISAd, a, last, -3, trlink);
647731 ISAd += incr, last = a, limit = next;
647732 } else {
647733 if(1 < (last - a)) {
647734 STACK_PUSH5(ISAd + incr, first, a, next, trlink);
647735 first = a, limit = -3;
647736 } else {
647737 ISAd += incr, last = a, limit = next;
647738 }
647739 }
647740 } else {
647741 if(0 <= trlink) { stack[trlink].d = -1; }
647742 if(1 < (last - a)) {
647743 first = a, limit = -3;
647744 } else {
647745 STACK_POP5(ISAd, first, last, limit, trlink);
647746 }
647747 }
647748 } else {
647749 STACK_POP5(ISAd, first, last, limit, trlink);
647750 }
647751 }
647752 continue;
647753 }
647754
647755 if((last - first) <= TR_INSERTIONSORT_THRESHOLD) {
647756 tr_insertionsort(ISAd, first, last);
647757 limit = -3;
647758 continue;
647759 }
647760
647761 if(limit-- == 0) {
647762 tr_heapsort(ISAd, first, last - first);
647763 for(a = last - 1; first < a; a = b) {
647764 for(x = ISAd[*a], b = a - 1; (first <= b) && (ISAd[*b] == x); --b) { *b = ~*b; }
647765 }
647766 limit = -3;
647767 continue;
647768 }
647769
647770 /* choose pivot */
647771 a = tr_pivot(ISAd, first, last);
647772 SWAP(*first, *a);
647773 v = ISAd[*first];
647774
647775 /* partition */
647776 tr_partition(ISAd, first, first + 1, last, &a, &b, v);
647777 if((last - first) != (b - a)) {
647778 next = (ISA[*a] != v) ? tr_ilg(b - a) : -1;
647779
647780 /* update ranks */
647781 for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; }
647782 if(b < last) { for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } }
647783
647784 /* push */
647785 if((1 < (b - a)) && (trbudget_check(budget, b - a))) {
647786 if((a - first) <= (last - b)) {
647787 if((last - b) <= (b - a)) {
647788 if(1 < (a - first)) {
647789 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647790 STACK_PUSH5(ISAd, b, last, limit, trlink);
647791 last = a;
647792 } else if(1 < (last - b)) {
647793 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647794 first = b;
647795 } else {
647796 ISAd += incr, first = a, last = b, limit = next;
647797 }
647798 } else if((a - first) <= (b - a)) {
647799 if(1 < (a - first)) {
647800 STACK_PUSH5(ISAd, b, last, limit, trlink);
647801 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647802 last = a;
647803 } else {
647804 STACK_PUSH5(ISAd, b, last, limit, trlink);
647805 ISAd += incr, first = a, last = b, limit = next;
647806 }
647807 } else {
647808 STACK_PUSH5(ISAd, b, last, limit, trlink);
647809 STACK_PUSH5(ISAd, first, a, limit, trlink);
647810 ISAd += incr, first = a, last = b, limit = next;
647811 }
647812 } else {
647813 if((a - first) <= (b - a)) {
647814 if(1 < (last - b)) {
647815 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647816 STACK_PUSH5(ISAd, first, a, limit, trlink);
647817 first = b;
647818 } else if(1 < (a - first)) {
647819 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647820 last = a;
647821 } else {
647822 ISAd += incr, first = a, last = b, limit = next;
647823 }
647824 } else if((last - b) <= (b - a)) {
647825 if(1 < (last - b)) {
647826 STACK_PUSH5(ISAd, first, a, limit, trlink);
647827 STACK_PUSH5(ISAd + incr, a, b, next, trlink);
647828 first = b;
647829 } else {
647830 STACK_PUSH5(ISAd, first, a, limit, trlink);
647831 ISAd += incr, first = a, last = b, limit = next;
647832 }
647833 } else {
647834 STACK_PUSH5(ISAd, first, a, limit, trlink);
647835 STACK_PUSH5(ISAd, b, last, limit, trlink);
647836 ISAd += incr, first = a, last = b, limit = next;
647837 }
647838 }
647839 } else {
647840 if((1 < (b - a)) && (0 <= trlink)) { stack[trlink].d = -1; }
647841 if((a - first) <= (last - b)) {
647842 if(1 < (a - first)) {
647843 STACK_PUSH5(ISAd, b, last, limit, trlink);
647844 last = a;
647845 } else if(1 < (last - b)) {
647846 first = b;
647847 } else {
647848 STACK_POP5(ISAd, first, last, limit, trlink);
647849 }
647850 } else {
647851 if(1 < (last - b)) {
647852 STACK_PUSH5(ISAd, first, a, limit, trlink);
647853 first = b;
647854 } else if(1 < (a - first)) {
647855 last = a;
647856 } else {
647857 STACK_POP5(ISAd, first, last, limit, trlink);
647858 }
647859 }
647860 }
647861 } else {
647862 if(trbudget_check(budget, last - first)) {
647863 limit = tr_ilg(last - first), ISAd += incr;
647864 } else {

◆ trsort()

void duckdb_zstd::trsort ( int * ISA,
int * SA,
int n,
int depth )
static
647880 {
647881 int *ISAd;
647882 int *first, *last;
647883 trbudget_t budget;
647884 int t, skip, unsorted;
647885
647886 trbudget_init(&budget, tr_ilg(n) * 2 / 3, n);
647887/* trbudget_init(&budget, tr_ilg(n) * 3 / 4, n); */
647888 for(ISAd = ISA + depth; -n < *SA; ISAd += ISAd - ISA) {
647889 first = SA;
647890 skip = 0;
647891 unsorted = 0;
647892 do {
647893 if((t = *first) < 0) { first -= t; skip += t; }
647894 else {
647895 if(skip != 0) { *(first + skip) = skip; skip = 0; }
647896 last = SA + ISA[t] + 1;
647897 if(1 < (last - first)) {
647898 budget.count = 0;
647899 tr_introsort(ISA, ISAd, SA, first, last, &budget);
647900 if(budget.count != 0) { unsorted += budget.count; }
647901 else { skip = first - last; }
647902 } else if((last - first) == 1) {
647903 skip = -1;
647904 }

◆ sort_typeBstar()

int duckdb_zstd::sort_typeBstar ( const unsigned char * T,
int * SA,
int * bucket_A,
int * bucket_B,
int n,
int openMP )
static
647921 {
647922 int *PAb, *ISAb, *buf;
647923#ifdef LIBBSC_OPENMP
647924 int *curbuf;
647925 int l;
647926#endif
647927 int i, j, k, t, m, bufsize;
647928 int c0, c1;
647929#ifdef LIBBSC_OPENMP
647930 int d0, d1;
647931#endif
647932 (void)openMP;
647933
647934 /* Initialize bucket arrays. */
647935 for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; }
647936 for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; }
647937
647938 /* Count the number of occurrences of the first one or two characters of each
647939 type A, B and B* suffix. Moreover, store the beginning position of all
647940 type B* suffixes into the array SA. */
647941 for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) {
647942 /* type A suffix. */
647943 do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1));
647944 if(0 <= i) {
647945 /* type B* suffix. */
647946 ++BUCKET_BSTAR(c0, c1);
647947 SA[--m] = i;
647948 /* type B suffix. */
647949 for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) {
647950 ++BUCKET_B(c0, c1);
647951 }
647952 }
647953 }
647954 m = n - m;
647955/*
647956note:
647957 A type B* suffix is lexicographically smaller than a type B suffix that
647958 begins with the same first two characters.
647959*/
647960
647961 /* Calculate the index of start/end point of each bucket. */
647962 for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) {
647963 t = i + BUCKET_A(c0);
647964 BUCKET_A(c0) = i + j; /* start point */
647965 i = t + BUCKET_B(c0, c0);
647966 for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) {
647967 j += BUCKET_BSTAR(c0, c1);
647968 BUCKET_BSTAR(c0, c1) = j; /* end point */
647969 i += BUCKET_B(c0, c1);
647970 }
647971 }
647972
647973 if(0 < m) {
647974 /* Sort the type B* suffixes by their first two characters. */
647975 PAb = SA + n - m; ISAb = SA + m;
647976 for(i = m - 2; 0 <= i; --i) {
647977 t = PAb[i], c0 = T[t], c1 = T[t + 1];
647978 SA[--BUCKET_BSTAR(c0, c1)] = i;
647979 }
647980 t = PAb[m - 1], c0 = T[t], c1 = T[t + 1];
647981 SA[--BUCKET_BSTAR(c0, c1)] = m - 1;
647982
647983 /* Sort the type B* substrings using sssort. */
647984#ifdef LIBBSC_OPENMP
647985 if (openMP)
647986 {
647987 buf = SA + m;
647988 c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m;
647989#pragma omp parallel default(shared) private(bufsize, curbuf, k, l, d0, d1)
647990 {
647991 bufsize = (n - (2 * m)) / omp_get_num_threads();
647992 curbuf = buf + omp_get_thread_num() * bufsize;
647993 k = 0;
647994 for(;;) {
647995 #pragma omp critical(sssort_lock)
647996 {
647997 if(0 < (l = j)) {
647998 d0 = c0, d1 = c1;
647999 do {
648000 k = BUCKET_BSTAR(d0, d1);
648001 if(--d1 <= d0) {
648002 d1 = ALPHABET_SIZE - 1;
648003 if(--d0 < 0) { break; }
648004 }
648005 } while(((l - k) <= 1) && (0 < (l = k)));
648006 c0 = d0, c1 = d1, j = k;
648007 }
648008 }
648009 if(l == 0) { break; }
648010 sssort(T, PAb, SA + k, SA + l,
648011 curbuf, bufsize, 2, n, *(SA + k) == (m - 1));
648012 }
648013 }
648014 }
648015 else
648016 {
648017 buf = SA + m, bufsize = n - (2 * m);
648018 for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
648019 for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
648020 i = BUCKET_BSTAR(c0, c1);
648021 if(1 < (j - i)) {
648022 sssort(T, PAb, SA + i, SA + j,
648023 buf, bufsize, 2, n, *(SA + i) == (m - 1));
648024 }
648025 }
648026 }
648027 }
648028#else
648029 buf = SA + m, bufsize = n - (2 * m);
648030 for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
648031 for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
648032 i = BUCKET_BSTAR(c0, c1);
648033 if(1 < (j - i)) {
648034 sssort(T, PAb, SA + i, SA + j,
648035 buf, bufsize, 2, n, *(SA + i) == (m - 1));
648036 }
648037 }
648038 }
648039#endif
648040
648041 /* Compute ranks of type B* substrings. */
648042 for(i = m - 1; 0 <= i; --i) {
648043 if(0 <= SA[i]) {
648044 j = i;
648045 do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i]));
648046 SA[i + 1] = i - j;
648047 if(i <= 0) { break; }
648048 }
648049 j = i;
648050 do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0);
648051 ISAb[SA[i]] = j;
648052 }
648053
648054 /* Construct the inverse suffix array of type B* suffixes using trsort. */
648055 trsort(ISAb, SA, m, 1);
648056
648057 /* Set the sorted order of type B* suffixes. */
648058 for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) {
648059 for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { }
648060 if(0 <= i) {
648061 t = i;
648062 for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { }
648063 SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t;
648064 }
648065 }
648066
648067 /* Calculate the index of start/end point of each bucket. */
648068 BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */
648069 for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) {
648070 i = BUCKET_A(c0 + 1) - 1;
648071 for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) {
648072 t = i - BUCKET_B(c0, c1);
648073 BUCKET_B(c0, c1) = i; /* end point */
648074
648075 /* Move all type B* suffixes to the correct position. */
648076 for(i = t, j = BUCKET_BSTAR(c0, c1);
648077 j <= k;
648078 --i, --k) { SA[i] = SA[k]; }
648079 }

◆ construct_SA()

void duckdb_zstd::construct_SA ( const unsigned char * T,
int * SA,
int * bucket_A,
int * bucket_B,
int n,
int m )
static
648093 {
648094 int *i, *j, *k;
648095 int s;
648096 int c0, c1, c2;
648097
648098 if(0 < m) {
648099 /* Construct the sorted order of type B suffixes by using
648100 the sorted order of type B* suffixes. */
648101 for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
648102 /* Scan the suffix array from right to left. */
648103 for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
648104 j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
648105 i <= j;
648106 --j) {
648107 if(0 < (s = *j)) {
648108 assert(T[s] == c1);
648109 assert(((s + 1) < n) && (T[s] <= T[s + 1]));
648110 assert(T[s - 1] <= T[s]);
648111 *j = ~s;
648112 c0 = T[--s];
648113 if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
648114 if(c0 != c2) {
648115 if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
648116 k = SA + BUCKET_B(c2 = c0, c1);
648117 }
648118 assert(k < j); assert(k != NULL);
648119 *k-- = s;
648120 } else {
648121 assert(((s == 0) && (T[s] == c1)) || (s < 0));
648122 *j = ~s;
648123 }
648124 }
648125 }
648126 }
648127
648128 /* Construct the suffix array by using
648129 the sorted order of type B suffixes. */
648130 k = SA + BUCKET_A(c2 = T[n - 1]);
648131 *k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1);
648132 /* Scan the suffix array from left to right. */
648133 for(i = SA, j = SA + n; i < j; ++i) {
648134 if(0 < (s = *i)) {
648135 assert(T[s - 1] >= T[s]);
648136 c0 = T[--s];
648137 if((s == 0) || (T[s - 1] < c0)) { s = ~s; }
648138 if(c0 != c2) {
648139 BUCKET_A(c2) = k - SA;
648140 k = SA + BUCKET_A(c2 = c0);
648141 }
648142 assert(i < k);

◆ construct_BWT()

int duckdb_zstd::construct_BWT ( const unsigned char * T,
int * SA,
int * bucket_A,
int * bucket_B,
int n,
int m )
static
648157 {
648158 int *i, *j, *k, *orig;
648159 int s;
648160 int c0, c1, c2;
648161
648162 if(0 < m) {
648163 /* Construct the sorted order of type B suffixes by using
648164 the sorted order of type B* suffixes. */
648165 for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
648166 /* Scan the suffix array from right to left. */
648167 for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
648168 j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
648169 i <= j;
648170 --j) {
648171 if(0 < (s = *j)) {
648172 assert(T[s] == c1);
648173 assert(((s + 1) < n) && (T[s] <= T[s + 1]));
648174 assert(T[s - 1] <= T[s]);
648175 c0 = T[--s];
648176 *j = ~((int)c0);
648177 if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
648178 if(c0 != c2) {
648179 if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
648180 k = SA + BUCKET_B(c2 = c0, c1);
648181 }
648182 assert(k < j); assert(k != NULL);
648183 *k-- = s;
648184 } else if(s != 0) {
648185 *j = ~s;
648186#ifndef NDEBUG
648187 } else {
648188 assert(T[s] == c1);
648189#endif
648190 }
648191 }
648192 }
648193 }
648194
648195 /* Construct the BWTed string by using
648196 the sorted order of type B suffixes. */
648197 k = SA + BUCKET_A(c2 = T[n - 1]);
648198 *k++ = (T[n - 2] < c2) ? ~((int)T[n - 2]) : (n - 1);
648199 /* Scan the suffix array from left to right. */
648200 for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
648201 if(0 < (s = *i)) {
648202 assert(T[s - 1] >= T[s]);
648203 c0 = T[--s];
648204 *i = c0;
648205 if((0 < s) && (T[s - 1] < c0)) { s = ~((int)T[s - 1]); }
648206 if(c0 != c2) {
648207 BUCKET_A(c2) = k - SA;
648208 k = SA + BUCKET_A(c2 = c0);
648209 }
648210 assert(i < k);
648211 *k++ = s;
648212 } else if(s != 0) {
648213 *i = ~s;

◆ construct_BWT_indexes()

int duckdb_zstd::construct_BWT_indexes ( const unsigned char * T,
int * SA,
int * bucket_A,
int * bucket_B,
int n,
int m,
unsigned char * num_indexes,
int * indexes )
static
648229 {
648230 int *i, *j, *k, *orig;
648231 int s;
648232 int c0, c1, c2;
648233
648234 int mod = n / 8;
648235 {
648236 mod |= mod >> 1; mod |= mod >> 2;
648237 mod |= mod >> 4; mod |= mod >> 8;
648238 mod |= mod >> 16; mod >>= 1;
648239
648240 *num_indexes = (unsigned char)((n - 1) / (mod + 1));
648241 }
648242
648243 if(0 < m) {
648244 /* Construct the sorted order of type B suffixes by using
648245 the sorted order of type B* suffixes. */
648246 for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
648247 /* Scan the suffix array from right to left. */
648248 for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
648249 j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
648250 i <= j;
648251 --j) {
648252 if(0 < (s = *j)) {
648253 assert(T[s] == c1);
648254 assert(((s + 1) < n) && (T[s] <= T[s + 1]));
648255 assert(T[s - 1] <= T[s]);
648256
648257 if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = j - SA;
648258
648259 c0 = T[--s];
648260 *j = ~((int)c0);
648261 if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
648262 if(c0 != c2) {
648263 if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
648264 k = SA + BUCKET_B(c2 = c0, c1);
648265 }
648266 assert(k < j); assert(k != NULL);
648267 *k-- = s;
648268 } else if(s != 0) {
648269 *j = ~s;
648270#ifndef NDEBUG
648271 } else {
648272 assert(T[s] == c1);
648273#endif
648274 }
648275 }
648276 }
648277 }
648278
648279 /* Construct the BWTed string by using
648280 the sorted order of type B suffixes. */
648281 k = SA + BUCKET_A(c2 = T[n - 1]);
648282 if (T[n - 2] < c2) {
648283 if (((n - 1) & mod) == 0) indexes[(n - 1) / (mod + 1) - 1] = k - SA;
648284 *k++ = ~((int)T[n - 2]);
648285 }
648286 else {
648287 *k++ = n - 1;
648288 }
648289
648290 /* Scan the suffix array from left to right. */
648291 for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
648292 if(0 < (s = *i)) {
648293 assert(T[s - 1] >= T[s]);
648294
648295 if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = i - SA;
648296
648297 c0 = T[--s];
648298 *i = c0;
648299 if(c0 != c2) {
648300 BUCKET_A(c2) = k - SA;
648301 k = SA + BUCKET_A(c2 = c0);
648302 }
648303 assert(i < k);
648304 if((0 < s) && (T[s - 1] < c0)) {
648305 if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = k - SA;
648306 *k++ = ~((int)T[s - 1]);
648307 } else
648308 *k++ = s;
648309 } else if(s != 0) {
648310 *i = ~s;

◆ FASTCOVER_hashPtrToIndex()

size_t duckdb_zstd::FASTCOVER_hashPtrToIndex ( const void * p,
U32 f,
unsigned d )
static

Hash the d-byte value pointed to by p and mod 2^f into the frequency vector

◆ FASTCOVER_selectSegment()

COVER_segment_t duckdb_zstd::FASTCOVER_selectSegment ( const FASTCOVER_ctx_t * ctx,
U32 * freqs,
U32 begin,
U32 end,
ZDICT_cover_params_t parameters,
U16 * segmentFreqs )
static

Selects the best segment in an epoch. Segments of are scored according to the function:

Let F(d) be the frequency of all dmers with hash value d. Let S_i be hash value of the dmer at position i of segment S which has length k.

Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})

Once the dmer with hash value d is in the dictionary we set F(d) = 0.

648555 {k-d+1})
648556 *
648557 * Once the dmer with hash value d is in the dictionary we set F(d) = 0.
648558 */
648559static COVER_segment_t FASTCOVER_selectSegment(const FASTCOVER_ctx_t *ctx,
648560 U32 *freqs, U32 begin, U32 end,
648561 ZDICT_cover_params_t parameters,
648562 U16* segmentFreqs) {
648563 /* Constants */
648564 const U32 k = parameters.k;
648565 const U32 d = parameters.d;
648566 const U32 f = ctx->f;
648567 const U32 dmersInK = k - d + 1;
648568
648569 /* Try each segment (activeSegment) and save the best (bestSegment) */
648570 COVER_segment_t bestSegment = {0, 0, 0};
648571 COVER_segment_t activeSegment;
648572
648573 /* Reset the activeDmers in the segment */
648574 /* The activeSegment starts at the beginning of the epoch. */
648575 activeSegment.begin = begin;
648576 activeSegment.end = begin;
648577 activeSegment.score = 0;
648578
648579 /* Slide the activeSegment through the whole epoch.
648580 * Save the best segment in bestSegment.
648581 */
648582 while (activeSegment.end < end) {
648583 /* Get hash value of current dmer */
648584 const size_t idx = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.end, f, d);
648585
648586 /* Add frequency of this index to score if this is the first occurrence of index in active segment */
648587 if (segmentFreqs[idx] == 0) {
648588 activeSegment.score += freqs[idx];
648589 }
648590 /* Increment end of segment and segmentFreqs*/
648591 activeSegment.end += 1;
648592 segmentFreqs[idx] += 1;
648593 /* If the window is now too large, drop the first position */
648594 if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
648595 /* Get hash value of the dmer to be eliminated from active segment */
648596 const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
648597 segmentFreqs[delIndex] -= 1;
648598 /* Subtract frequency of this index from score if this is the last occurrence of this index in active segment */
648599 if (segmentFreqs[delIndex] == 0) {
648600 activeSegment.score -= freqs[delIndex];
648601 }
648602 /* Increment start of segment */
648603 activeSegment.begin += 1;
648604 }
648605
648606 /* If this segment is the best so far save it */
648607 if (activeSegment.score > bestSegment.score) {
648608 bestSegment = activeSegment;
648609 }
648610 }
648611
648612 /* Zero out rest of segmentFreqs array */
648613 while (activeSegment.begin < end) {
648614 const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
648615 segmentFreqs[delIndex] -= 1;
648616 activeSegment.begin += 1;
648617 }
648618
648619 {
648620 /* Zero the frequency of hash value of each dmer covered by the chosen segment. */
648621 U32 pos;
648622 for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
static size_t FASTCOVER_hashPtrToIndex(const void *p, U32 f, unsigned d)
Definition duckdb.cpp:648488
static COVER_segment_t FASTCOVER_selectSegment(const FASTCOVER_ctx_t *ctx, U32 *freqs, U32 begin, U32 end, ZDICT_cover_params_t parameters, U16 *segmentFreqs)
Definition duckdb.cpp:648552

◆ FASTCOVER_checkParameters()

int duckdb_zstd::FASTCOVER_checkParameters ( ZDICT_cover_params_t parameters,
size_t maxDictSize,
unsigned f,
unsigned accel )
static
648634 {
648635 /* k, d, and f are required parameters */
648636 if (parameters.d == 0 || parameters.k == 0) {
648637 return 0;
648638 }
648639 /* d has to be 6 or 8 */
648640 if (parameters.d != 6 && parameters.d != 8) {
648641 return 0;
648642 }
648643 /* k <= maxDictSize */
648644 if (parameters.k > maxDictSize) {
648645 return 0;
648646 }
648647 /* d <= k */
648648 if (parameters.d > parameters.k) {
648649 return 0;
648650 }
648651 /* 0 < f <= FASTCOVER_MAX_F*/
648652 if (f > FASTCOVER_MAX_F || f == 0) {
648653 return 0;
648654 }
648655 /* 0 < splitPoint <= 1 */
648656 if (parameters.splitPoint <= 0 || parameters.splitPoint > 1) {
648657 return 0;

◆ FASTCOVER_ctx_destroy()

void duckdb_zstd::FASTCOVER_ctx_destroy ( FASTCOVER_ctx_t * ctx)
static

Clean up a context initialized with FASTCOVER_ctx_init().

648672{
648673 if (!ctx) return;

◆ FASTCOVER_computeFrequency()

void duckdb_zstd::FASTCOVER_computeFrequency ( U32 * freqs,
const FASTCOVER_ctx_t * ctx )
static

Calculate for frequency of hash value of each dmer in ctx->samples

648688{
648689 const unsigned f = ctx->f;
648690 const unsigned d = ctx->d;
648691 const unsigned skip = ctx->accelParams.skip;
648692 const unsigned readLength = MAX(d, 8);
648693 size_t i;
648694 assert(ctx->nbTrainSamples >= 5);
648695 assert(ctx->nbTrainSamples <= ctx->nbSamples);
648696 for (i = 0; i < ctx->nbTrainSamples; i++) {
648697 size_t start = ctx->offsets[i]; /* start of current dmer */
648698 size_t const currSampleEnd = ctx->offsets[i+1];

◆ FASTCOVER_ctx_init()

size_t duckdb_zstd::FASTCOVER_ctx_init ( FASTCOVER_ctx_t * ctx,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
unsigned d,
double splitPoint,
unsigned f,
FASTCOVER_accel_t accelParams )
static

Prepare a context for dictionary building. The context is only dependent on the parameter d and can be used multiple times. Returns 0 on success or error code on error. The context must be destroyed with FASTCOVER_ctx_destroy().

648721{
648722 const BYTE* const samples = (const BYTE*)samplesBuffer;
648723 const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
648724 /* Split samples into testing and training sets */
648725 const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
648726 const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
648727 const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
648728 const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
648729
648730 (void) testSamplesSize;
648731
648732 /* Checks */
648733 if (totalSamplesSize < MAX(d, sizeof(U64)) ||
648734 totalSamplesSize >= (size_t)FASTCOVER_MAX_SAMPLES_SIZE) {
648735 DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
648736 (unsigned)(totalSamplesSize >> 20), (FASTCOVER_MAX_SAMPLES_SIZE >> 20));
648737 return ERROR(srcSize_wrong);
648738 }
648739
648740 /* Check if there are at least 5 training samples */
648741 if (nbTrainSamples < 5) {
648742 DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid\n", nbTrainSamples);
648743 return ERROR(srcSize_wrong);
648744 }
648745
648746 /* Check if there's testing sample */
648747 if (nbTestSamples < 1) {
648748 DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.\n", nbTestSamples);
648749 return ERROR(srcSize_wrong);
648750 }
648751
648752 /* Zero the context */
648753 memset(ctx, 0, sizeof(*ctx));
648754 DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
648755 (unsigned)trainingSamplesSize);
648756 DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
648757 (unsigned)testSamplesSize);
648758
648759 ctx->samples = samples;
648760 ctx->samplesSizes = samplesSizes;
648761 ctx->nbSamples = nbSamples;
648762 ctx->nbTrainSamples = nbTrainSamples;
648763 ctx->nbTestSamples = nbTestSamples;
648764 ctx->nbDmers = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
648765 ctx->d = d;
648766 ctx->f = f;
648767 ctx->accelParams = accelParams;
648768
648769 /* The offsets of each file */
648770 ctx->offsets = (size_t*)calloc((nbSamples + 1), sizeof(size_t));
648771 if (ctx->offsets == NULL) {
648772 DISPLAYLEVEL(1, "Failed to allocate scratch buffers \n");
648774 return ERROR(memory_allocation);
648775 }
648776
648777 /* Fill offsets from the samplesSizes */
648778 { U32 i;
648779 ctx->offsets[0] = 0;
648780 assert(nbSamples >= 5);
648781 for (i = 1; i <= nbSamples; ++i) {
648782 ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
648783 }
648784 }
648785
648786 /* Initialize frequency array of size 2^f */
648787 ctx->freqs = (U32*)calloc(((U64)1 << f), sizeof(U32));
648788 if (ctx->freqs == NULL) {
648789 DISPLAYLEVEL(1, "Failed to allocate frequency table \n");
648791 return ERROR(memory_allocation);
#define FASTCOVER_MAX_SAMPLES_SIZE
Definition duckdb.cpp:648437

◆ FASTCOVER_buildDictionary()

size_t duckdb_zstd::FASTCOVER_buildDictionary ( const FASTCOVER_ctx_t * ctx,
U32 * freqs,
void * dictBuffer,
size_t dictBufferCapacity,
ZDICT_cover_params_t parameters,
U16 * segmentFreqs )
static

Given the prepared context build the dictionary.

648810{
648811 BYTE *const dict = (BYTE *)dictBuffer;
648812 size_t tail = dictBufferCapacity;
648813 /* Divide the data into epochs. We will select one segment from each epoch. */
648815 (U32)dictBufferCapacity, (U32)ctx->nbDmers, parameters.k, 1);
648816 const size_t maxZeroScoreRun = 10;
648817 size_t zeroScoreRun = 0;
648818 size_t epoch;
648819 DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
648820 (U32)epochs.num, (U32)epochs.size);
648821 /* Loop through the epochs until there are no more segments or the dictionary
648822 * is full.
648823 */
648824 for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
648825 const U32 epochBegin = (U32)(epoch * epochs.size);
648826 const U32 epochEnd = epochBegin + epochs.size;
648827 size_t segmentSize;
648828 /* Select a segment */
648830 ctx, freqs, epochBegin, epochEnd, parameters, segmentFreqs);
648831
648832 /* If the segment covers no dmers, then we are out of content.
648833 * There may be new content in other epochs, for continue for some time.
648834 */
648835 if (segment.score == 0) {
648836 if (++zeroScoreRun >= maxZeroScoreRun) {
648837 break;
648838 }
648839 continue;
648840 }
648841 zeroScoreRun = 0;
648842
648843 /* Trim the segment if necessary and if it is too small then we are done */
648844 segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
648845 if (segmentSize < parameters.d) {
648846 break;
648847 }
648848
648849 /* We fill the dictionary from the back to allow the best segments to be
648850 * referenced with the smallest offsets.
648851 */
648852 tail -= segmentSize;
648853 memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);

◆ FASTCOVER_tryParameters()

void duckdb_zstd::FASTCOVER_tryParameters ( void * opaque)
static

Tries a set of parameters and updates the COVER_best_t with the results. This function is thread safe if zstd is compiled with multithreaded support. It takes its parameters as an OWNING opaque pointer to support threading.

648879{
648880 /* Save parameters as local variables */
648882 const FASTCOVER_ctx_t *const ctx = data->ctx;
648883 const ZDICT_cover_params_t parameters = data->parameters;
648884 size_t dictBufferCapacity = data->dictBufferCapacity;
648885 size_t totalCompressedSize = ERROR(GENERIC);
648886 /* Initialize array to keep track of frequency of dmer within activeSegment */
648887 U16* segmentFreqs = (U16*)calloc(((U64)1 << ctx->f), sizeof(U16));
648888 /* Allocate space for hash table, dict, and freqs */
648889 BYTE *const dict = (BYTE*)malloc(dictBufferCapacity);
648890 COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
648891 U32* freqs = (U32*) malloc(((U64)1 << ctx->f) * sizeof(U32));
648892 if (!segmentFreqs || !dict || !freqs) {
648893 DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
648894 goto _cleanup;
648895 }
648896 /* Copy the frequencies because we need to modify them */
648897 memcpy(freqs, ctx->freqs, ((U64)1 << ctx->f) * sizeof(U32));
648898 /* Build the dictionary */
648899 { const size_t tail = FASTCOVER_buildDictionary(ctx, freqs, dict, dictBufferCapacity,
648900 parameters, segmentFreqs);
648901
648902 const unsigned nbFinalizeSamples = (unsigned)(ctx->nbTrainSamples * ctx->accelParams.finalize / 100);
648903 selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
648904 ctx->samples, ctx->samplesSizes, nbFinalizeSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
648905 totalCompressedSize);
648906
648907 if (COVER_dictSelectionIsError(selection)) {
648908 DISPLAYLEVEL(1, "Failed to select dictionary\n");
648909 goto _cleanup;
648910 }
648911 }
648912_cleanup:

◆ FASTCOVER_convertToCoverParams()

void duckdb_zstd::FASTCOVER_convertToCoverParams ( ZDICT_fastCover_params_t fastCoverParams,
ZDICT_cover_params_t * coverParams )
static
648925{
648926 coverParams->k = fastCoverParams.k;

◆ FASTCOVER_convertToFastCoverParams()

void duckdb_zstd::FASTCOVER_convertToFastCoverParams ( ZDICT_cover_params_t coverParams,
ZDICT_fastCover_params_t * fastCoverParams,
unsigned f,
unsigned accel )
static
648940{
648941 fastCoverParams->k = coverParams.k;
648942 fastCoverParams->d = coverParams.d;
648943 fastCoverParams->steps = coverParams.steps;

◆ ZDICT_clockSpan()

clock_t duckdb_zstd::ZDICT_clockSpan ( clock_t nPrevious)
static

◆ ZDICT_printHex()

void duckdb_zstd::ZDICT_printHex ( const void * ptr,
size_t length )
static
649264 { fprintf(stderr, __VA_ARGS__); fflush( stderr ); } while (0)
649265#undef DISPLAYLEVEL
649266#define DISPLAYLEVEL(l, ...) do { if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } } while (0) /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
649267
649268static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
649269
649270static void ZDICT_printHex(const void* ptr, size_t length)
649271{
649272 const BYTE* const b = (const BYTE*)ptr;

◆ ZDICT_count()

size_t duckdb_zstd::ZDICT_count ( const void * pIn,
const void * pMatch )
static

ZDICT_count() : Count the nb of common bytes between 2 pointers. Note : this function presumes end of buffer followed by noisy guard band.

649325{
649326 const char* const pStart = (const char*)pIn;
649327 for (;;) {
649328 size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
649329 if (!diff) {
649330 pIn = (const char*)pIn+sizeof(size_t);

◆ ZDICT_initDictItem()

void duckdb_zstd::ZDICT_initDictItem ( dictItem * d)
static
649340 {
649341 U32 pos;
649342 U32 length;
649343 U32 savings;
649344} dictItem;

◆ ZDICT_analyzePos()

dictItem duckdb_zstd::ZDICT_analyzePos ( BYTE * doneMarks,
const int * suffix,
U32 start,
const void * buffer,
U32 minRatio,
U32 notificationLevel )
static
649360{
649361 U32 lengthList[LLIMIT] = {0};
649362 U32 cumulLength[LLIMIT] = {0};
649363 U32 savings[LLIMIT] = {0};
649364 const BYTE* b = (const BYTE*)buffer;
649365 size_t maxLength = LLIMIT;
649366 size_t pos = (size_t)suffix[start];
649367 U32 end = start;
649368 dictItem solution;
649369
649370 /* init */
649371 memset(&solution, 0, sizeof(solution));
649372 doneMarks[pos] = 1;
649373
649374 /* trivial repetition cases */
649375 if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
649376 ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
649377 ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
649378 /* skip and mark segment */
649379 U16 const pattern16 = MEM_read16(b+pos+4);
649380 U32 u, patternEnd = 6;
649381 while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
649382 if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
649383 for (u=1; u<patternEnd; u++)
649384 doneMarks[pos+u] = 1;
649385 return solution;
649386 }
649387
649388 /* look forward */
649389 { size_t length;
649390 do {
649391 end++;
649392 length = ZDICT_count(b + pos, b + suffix[end]);
649393 } while (length >= MINMATCHLENGTH);
649394 }
649395
649396 /* look backward */
649397 { size_t length;
649398 do {
649399 length = ZDICT_count(b + pos, b + *(suffix+start-1));
649400 if (length >=MINMATCHLENGTH) start--;
649401 } while(length >= MINMATCHLENGTH);
649402 }
649403
649404 /* exit if not found a minimum nb of repetitions */
649405 if (end-start < minRatio) {
649406 U32 idx;
649407 for(idx=start; idx<end; idx++)
649408 doneMarks[suffix[idx]] = 1;
649409 return solution;
649410 }
649411
649412 { int i;
649413 U32 mml;
649414 U32 refinedStart = start;
649415 U32 refinedEnd = end;
649416
649417 DISPLAYLEVEL(4, "\n");
649418 DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
649419 DISPLAYLEVEL(4, "\n");
649420
649421 for (mml = MINMATCHLENGTH ; ; mml++) {
649422 BYTE currentChar = 0;
649423 U32 currentCount = 0;
649424 U32 currentID = refinedStart;
649425 U32 id;
649426 U32 selectedCount = 0;
649427 U32 selectedID = currentID;
649428 for (id =refinedStart; id < refinedEnd; id++) {
649429 if (b[suffix[id] + mml] != currentChar) {
649430 if (currentCount > selectedCount) {
649431 selectedCount = currentCount;
649432 selectedID = currentID;
649433 }
649434 currentID = id;
649435 currentChar = b[ suffix[id] + mml];
649436 currentCount = 0;
649437 }
649438 currentCount ++;
649439 }
649440 if (currentCount > selectedCount) { /* for last */
649441 selectedCount = currentCount;
649442 selectedID = currentID;
649443 }
649444
649445 if (selectedCount < minRatio)
649446 break;
649447 refinedStart = selectedID;
649448 refinedEnd = refinedStart + selectedCount;
649449 }
649450
649451 /* evaluate gain based on new dict */
649452 start = refinedStart;
649453 pos = suffix[refinedStart];
649454 end = start;
649455 memset(lengthList, 0, sizeof(lengthList));
649456
649457 /* look forward */
649458 { size_t length;
649459 do {
649460 end++;
649461 length = ZDICT_count(b + pos, b + suffix[end]);
649462 if (length >= LLIMIT) length = LLIMIT-1;
649463 lengthList[length]++;
649464 } while (length >=MINMATCHLENGTH);
649465 }
649466
649467 /* look backward */
649468 { size_t length = MINMATCHLENGTH;
649469 while ((length >= MINMATCHLENGTH) & (start > 0)) {
649470 length = ZDICT_count(b + pos, b + suffix[start - 1]);
649471 if (length >= LLIMIT) length = LLIMIT - 1;
649472 lengthList[length]++;
649473 if (length >= MINMATCHLENGTH) start--;
649474 }
649475 }
649476
649477 /* largest useful length */
649478 memset(cumulLength, 0, sizeof(cumulLength));
649479 cumulLength[maxLength-1] = lengthList[maxLength-1];
649480 for (i=(int)(maxLength-2); i>=0; i--)
649481 cumulLength[i] = cumulLength[i+1] + lengthList[i];
649482
649483 for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
649484 maxLength = i;
649485
649486 /* reduce maxLength in case of final into repetitive data */
649487 { U32 l = (U32)maxLength;
649488 BYTE const c = b[pos + maxLength-1];
649489 while (b[pos+l-2]==c) l--;
649490 maxLength = l;
649491 }
649492 if (maxLength < MINMATCHLENGTH) return solution; /* skip : no long-enough solution */
649493
649494 /* calculate savings */
649495 savings[5] = 0;
649496 for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
649497 savings[i] = savings[i-1] + (lengthList[i] * (i-3));
649498
649499 DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f) \n",
649500 (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / (double)maxLength);
649501
649502 solution.pos = (U32)pos;
649503 solution.length = (U32)maxLength;
649504 solution.savings = savings[maxLength];
649505
649506 /* mark positions done */
649507 { U32 id;
649508 for (id=start; id<end; id++) {
649509 U32 p, pEnd, length;
649510 U32 const testedPos = (U32)suffix[id];
649511 if (testedPos == pos)
649512 length = solution.length;
649513 else {
649514 length = (U32)ZDICT_count(b+pos, b+testedPos);
649515 if (length > solution.length) length = solution.length;
649516 }
static size_t ZDICT_count(const void *pIn, const void *pMatch)
Definition duckdb.cpp:649317
Definition duckdb.cpp:649333

◆ isIncluded()

int duckdb_zstd::isIncluded ( const void * in,
const void * container,
size_t length )
static
649527{
649528 const char* const ip = (const char*) in;
649529 const char* const into = (const char*) container;
649530 size_t u;

◆ ZDICT_tryMerge()

U32 duckdb_zstd::ZDICT_tryMerge ( dictItem * table,
dictItem elt,
U32 eltNbToSkip,
const void * buffer )
static

ZDICT_tryMerge() : check if dictItem can be merged, do it if possible

Returns
: id of destination elt, 0 if not merged
649544{
649545 const U32 tableSize = table->pos;
649546 const U32 eltEnd = elt.pos + elt.length;
649547 const char* const buf = (const char*) buffer;
649548
649549 /* tail overlap */
649550 U32 u; for (u=1; u<tableSize; u++) {
649551 if (u==eltNbToSkip) continue;
649552 if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) { /* overlap, existing > new */
649553 /* append */
649554 U32 const addedLength = table[u].pos - elt.pos;
649555 table[u].length += addedLength;
649556 table[u].pos = elt.pos;
649557 table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
649558 table[u].savings += elt.length / 8; /* rough approx bonus */
649559 elt = table[u];
649560 /* sort : improve rank */
649561 while ((u>1) && (table[u-1].savings < elt.savings))
649562 table[u] = table[u-1], u--;
649563 table[u] = elt;
649564 return u;
649565 } }
649566
649567 /* front overlap */
649568 for (u=1; u<tableSize; u++) {
649569 if (u==eltNbToSkip) continue;
649570
649571 if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) { /* overlap, existing < new */
649572 /* append */
649573 int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length);
649574 table[u].savings += elt.length / 8; /* rough approx bonus */
649575 if (addedLength > 0) { /* otherwise, elt fully included into existing */
649576 table[u].length += addedLength;
649577 table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
649578 }
649579 /* sort : improve rank */
649580 elt = table[u];
649581 while ((u>1) && (table[u-1].savings < elt.savings))
649582 table[u] = table[u-1], u--;
649583 table[u] = elt;
649584 return u;
649585 }
649586
649587 if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
649588 if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
649589 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
649590 table[u].pos = elt.pos;
649591 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
649592 table[u].length = MIN(elt.length, table[u].length + 1);

◆ ZDICT_removeDictItem()

void duckdb_zstd::ZDICT_removeDictItem ( dictItem * table,
U32 id )
static
649603{
649604 /* convention : table[0].pos stores nb of elts */

◆ ZDICT_insertDictItem()

void duckdb_zstd::ZDICT_insertDictItem ( dictItem * table,
U32 maxSize,
dictItem elt,
const void * buffer )
static
649615{
649616 /* merge if possible */
649617 U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
649618 if (mergeId) {
649619 U32 newMerge = 1;
649620 while (newMerge) {
649621 newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
649622 if (newMerge) ZDICT_removeDictItem(table, mergeId);
649623 mergeId = newMerge;
649624 }
649625 return;
649626 }
649627
649628 /* insert */
649629 { U32 current;
649630 U32 nextElt = table->pos;
649631 if (nextElt >= maxSize) nextElt = maxSize-1;
649632 current = nextElt-1;
649633 while (table[current].savings < elt.savings) {
static U32 ZDICT_tryMerge(dictItem *table, dictItem elt, U32 eltNbToSkip, const void *buffer)
Definition duckdb.cpp:649536

◆ ZDICT_dictSize()

U32 duckdb_zstd::ZDICT_dictSize ( const dictItem * dictList)
static

◆ ZDICT_trainBuffer_legacy()

size_t duckdb_zstd::ZDICT_trainBuffer_legacy ( dictItem * dictList,
U32 dictListSize,
const void *const buffer,
size_t bufferSize,
const size_t * fileSizes,
unsigned nbFiles,
unsigned minRatio,
U32 notificationLevel )
static
649656{
649657 int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
649658 int* const suffix = suffix0+1;
649659 U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
649660 BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks)); /* +16 for overflow security */
649661 U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
649662 size_t result = 0;
649663 clock_t displayClock = 0;
649664 clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
649665
649666# undef DISPLAYUPDATE
649667# define DISPLAYUPDATE(l, ...) \
649668 do { \
649669 if (notificationLevel>=l) { \
649670 if (ZDICT_clockSpan(displayClock) > refreshRate) { \
649671 displayClock = clock(); \
649672 DISPLAY(__VA_ARGS__); \
649673 } \
649674 if (notificationLevel>=4) fflush(stderr); \
649675 } \
649676 } while (0)
649677
649678 /* init */
649679 DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
649680 if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
649681 result = ERROR(memory_allocation);
649682 goto _cleanup;
649683 }
649684 if (minRatio < MINRATIO) minRatio = MINRATIO;
649685 memset(doneMarks, 0, bufferSize+16);
649686
649687 /* limit sample set size (divsufsort limitation)*/
649688 if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
649689 while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
649690
649691 /* sort */
649692 DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
649693 { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
649694 if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
649695 }
649696 suffix[bufferSize] = (int)bufferSize; /* leads into noise */
649697 suffix0[0] = (int)bufferSize; /* leads into noise */
649698 /* build reverse suffix sort */
649699 { size_t pos;
649700 for (pos=0; pos < bufferSize; pos++)
649701 reverseSuffix[suffix[pos]] = (U32)pos;
649702 /* note filePos tracks borders between samples.
649703 It's not used at this stage, but planned to become useful in a later update */
649704 filePos[0] = 0;
649705 for (pos=1; pos<nbFiles; pos++)
649706 filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
649707 }
649708
649709 DISPLAYLEVEL(2, "finding patterns ... \n");
649710 DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
649711
649712 { U32 cursor; for (cursor=0; cursor < bufferSize; ) {
649713 dictItem solution;
649714 if (doneMarks[cursor]) { cursor++; continue; }
649715 solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
649716 if (solution.length==0) { cursor++; continue; }
649717 ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
649718 cursor += solution.length;
649719 DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / (double)bufferSize * 100.0);
649720 } }
649721
int divsufsort(const unsigned char *T, int *SA, int n, int openMP)
Definition duckdb.cpp:648318

◆ ZDICT_fillNoise()

void duckdb_zstd::ZDICT_fillNoise ( void * buffer,
size_t length )
static
649732{
649733 unsigned const prime1 = 2654435761U;
649734 unsigned const prime2 = 2246822519U;

◆ ZDICT_countEStats()

void duckdb_zstd::ZDICT_countEStats ( EStats_ress_t esr,
const ZSTD_parameters * params,
unsigned * countLit,
unsigned * offsetcodeCount,
unsigned * matchlengthCount,
unsigned * litlengthCount,
U32 * repOffsets,
const void * src,
size_t srcSize,
U32 notificationLevel )
static
649757{
649758 size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
649759 size_t cSize;
649760
649761 if (srcSize > blockSizeMax) srcSize = blockSizeMax; /* protection vs large samples */
649762 { size_t const errorCode = ZSTD_compressBegin_usingCDict_deprecated(esr.zc, esr.dict);
649763 if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
649764
649765 }
649766 cSize = ZSTD_compressBlock_deprecated(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
649767 if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
649768
649769 if (cSize) { /* if == 0; block is not compressible */
649770 const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
649771
649772 /* literals stats */
649773 { const BYTE* bytePtr;
649774 for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
649775 countLit[*bytePtr]++;
649776 }
649777
649778 /* seqStats */
649779 { U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
649780 ZSTD_seqToCodes(seqStorePtr);
649781
649782 { const BYTE* codePtr = seqStorePtr->ofCode;
649783 U32 u;
649784 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
649785 }
649786
649787 { const BYTE* codePtr = seqStorePtr->mlCode;
649788 U32 u;
649789 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
649790 }
649791
649792 { const BYTE* codePtr = seqStorePtr->llCode;
649793 U32 u;
649794 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
649795 }
649796
649797 if (nbSeq >= 2) { /* rep offsets */
649798 const seqDef* const seq = seqStorePtr->sequencesStart;
649799 U32 offset1 = seq[0].offBase - ZSTD_REP_NUM;

◆ ZDICT_totalSampleSize()

size_t duckdb_zstd::ZDICT_totalSampleSize ( const size_t * fileSizes,
unsigned nbFiles )
static

◆ ZDICT_insertSortCount()

void duckdb_zstd::ZDICT_insertSortCount ( offsetCount_t table[ZSTD_REP_NUM+1],
U32 val,
U32 count )
static
649816 { U32 offset; U32 count; } offsetCount_t;
649817
649818static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
649819{
649820 U32 u;
649821 table[ZSTD_REP_NUM].offset = val;
649822 table[ZSTD_REP_NUM].count = count;
649823 for (u=ZSTD_REP_NUM; u>0; u--) {

◆ ZDICT_flatLit()

void duckdb_zstd::ZDICT_flatLit ( unsigned * countLit)
static

◆ ZDICT_analyzeEntropy()

size_t duckdb_zstd::ZDICT_analyzeEntropy ( void * dstBuffer,
size_t maxDstSize,
int compressionLevel,
const void * srcBuffer,
const size_t * fileSizes,
unsigned nbFiles,
const void * dictBuffer,
size_t dictBufferSize,
unsigned notificationLevel )
static
649851{
649852 unsigned countLit[256];
649853 HUF_CREATE_STATIC_CTABLE(hufTable, 255);
649854 unsigned offcodeCount[OFFCODE_MAX+1];
649855 short offcodeNCount[OFFCODE_MAX+1];
649856 U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
649857 unsigned matchLengthCount[MaxML+1];
649858 short matchLengthNCount[MaxML+1];
649859 unsigned litLengthCount[MaxLL+1];
649860 short litLengthNCount[MaxLL+1];
649861 U32 repOffset[MAXREPOFFSET];
649862 offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
649863 EStats_ress_t esr = { NULL, NULL, NULL };
649864 ZSTD_parameters params;
649865 U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
649866 size_t pos = 0, errorCode;
649867 size_t eSize = 0;
649868 size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
649869 size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
649870 BYTE* dstPtr = (BYTE*)dstBuffer;
649872
649873 /* init */
649874 DEBUGLOG(4, "ZDICT_analyzeEntropy");
649875 if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; } /* too large dictionary */
649876 for (u=0; u<256; u++) countLit[u] = 1; /* any character must be described */
649877 for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
649878 for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
649879 for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
649880 memset(repOffset, 0, sizeof(repOffset));
649881 repOffset[1] = repOffset[4] = repOffset[8] = 1;
649882 memset(bestRepOffset, 0, sizeof(bestRepOffset));
649883 if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
649884 params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
649885
649886 esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
649887 esr.zc = ZSTD_createCCtx();
649888 esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
649889 if (!esr.dict || !esr.zc || !esr.workPlace) {
649890 eSize = ERROR(memory_allocation);
649891 DISPLAYLEVEL(1, "Not enough memory \n");
649892 goto _cleanup;
649893 }
649894
649895 /* collect stats on all samples */
649896 for (u=0; u<nbFiles; u++) {
649897 ZDICT_countEStats(esr, &params,
649898 countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
649899 (const char*)srcBuffer + pos, fileSizes[u],
649900 notificationLevel);
649901 pos += fileSizes[u];
649902 }
649903
649904 if (notificationLevel >= 4) {
649905 /* writeStats */
649906 DISPLAYLEVEL(4, "Offset Code Frequencies : \n");
649907 for (u=0; u<=offcodeMax; u++) {
649908 DISPLAYLEVEL(4, "%2u :%7u \n", u, offcodeCount[u]);
649909 } }
649910
649911 /* analyze, build stats, starting with literals */
649912 { size_t maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
649913 if (HUF_isError(maxNbBits)) {
649914 eSize = maxNbBits;
649915 DISPLAYLEVEL(1, " HUF_buildCTable error \n");
649916 goto _cleanup;
649917 }
649918 if (maxNbBits==8) { /* not compressible : will fail on HUF_writeCTable() */
649919 DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
649920 ZDICT_flatLit(countLit); /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
649921 maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
649922 assert(maxNbBits==9);
649923 }
649924 huffLog = (U32)maxNbBits;
649925 }
649926
649927 /* looking for most common first offsets */
649928 { U32 offset;
649929 for (offset=1; offset<MAXREPOFFSET; offset++)
649930 ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
649931 }
649932 /* note : the result of this phase should be used to better appreciate the impact on statistics */
649933
649934 total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
649935 errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
649936 if (FSE_isError(errorCode)) {
649937 eSize = errorCode;
649938 DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
649939 goto _cleanup;
649940 }
649941 Offlog = (U32)errorCode;
649942
649943 total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
649944 errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
649945 if (FSE_isError(errorCode)) {
649946 eSize = errorCode;
649947 DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
649948 goto _cleanup;
649949 }
649950 mlLog = (U32)errorCode;
649951
649952 total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
649953 errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
649954 if (FSE_isError(errorCode)) {
649955 eSize = errorCode;
649956 DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
649957 goto _cleanup;
649958 }
649959 llLog = (U32)errorCode;
649960
649961 /* write result to buffer */
649962 { size_t const hhSize = HUF_writeCTable_wksp(dstPtr, maxDstSize, hufTable, 255, huffLog, wksp, sizeof(wksp));
649963 if (HUF_isError(hhSize)) {
649964 eSize = hhSize;
649965 DISPLAYLEVEL(1, "HUF_writeCTable error \n");
649966 goto _cleanup;
649967 }
649968 dstPtr += hhSize;
649969 maxDstSize -= hhSize;
649970 eSize += hhSize;
649971 }
649972
649973 { size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
649974 if (FSE_isError(ohSize)) {
649975 eSize = ohSize;
649976 DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
649977 goto _cleanup;
649978 }
649979 dstPtr += ohSize;
649980 maxDstSize -= ohSize;
649981 eSize += ohSize;
649982 }
649983
649984 { size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
649985 if (FSE_isError(mhSize)) {
649986 eSize = mhSize;
649987 DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
649988 goto _cleanup;
649989 }
649990 dstPtr += mhSize;
649991 maxDstSize -= mhSize;
649992 eSize += mhSize;
649993 }
649994
649995 { size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
649996 if (FSE_isError(lhSize)) {
649997 eSize = lhSize;
649998 DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
649999 goto _cleanup;
650000 }
650001 dstPtr += lhSize;
650002 maxDstSize -= lhSize;
650003 eSize += lhSize;
650004 }
650005
650006 if (maxDstSize<12) {
650007 eSize = ERROR(dstSize_tooSmall);
650008 DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
650009 goto _cleanup;
650010 }
650011# if 0
650012 MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
650013 MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
650014 MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
650015#else
650016 /* at this stage, we don't use the result of "most common first offset",
650017 * as the impact of statistics is not properly evaluated */
650018 MEM_writeLE32(dstPtr+0, repStartValue[0]);
650019 MEM_writeLE32(dstPtr+4, repStartValue[1]);
650020 MEM_writeLE32(dstPtr+8, repStartValue[2]);
650021#endif
650022 eSize += 12;
650023
#define HUF_CTABLE_WORKSPACE_SIZE_U32
Definition duckdb.cpp:610533
ZSTDLIB_STATIC_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize)
Definition duckdb.cpp:626965
Definition duckdb.cpp:649738
Definition duckdb.cpp:649809

◆ ZDICT_maxRep()

U32 duckdb_zstd::ZDICT_maxRep ( U32 const reps[ZSTD_REP_NUM])
static
Returns
the maximum repcode value

◆ ZDICT_addEntropyTablesFromBuffer_advanced()

size_t duckdb_zstd::ZDICT_addEntropyTablesFromBuffer_advanced ( void * dictBuffer,
size_t dictContentSize,
size_t dictBufferCapacity,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_params_t params )
static
650131{
650132 int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
650133 U32 const notificationLevel = params.notificationLevel;
650134 size_t hSize = 8;
650135
650136 /* calculate entropy tables */
650137 DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
650138 DISPLAYLEVEL(2, "statistics ... \n");
650139 { size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
650140 compressionLevel,
650141 samplesBuffer, samplesSizes, nbSamples,
650142 (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
650143 notificationLevel);
650144 if (ZDICT_isError(eSize)) return eSize;
650145 hSize += eSize;
650146 }
650147
650148 /* add dictionary header (after entropy tables) */
650149 MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
650150 { U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
650151 U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
650152 U32 const dictID = params.dictID ? params.dictID : compliantID;

◆ ZDICT_trainFromBuffer_unsafe_legacy()

size_t duckdb_zstd::ZDICT_trainFromBuffer_unsafe_legacy ( void * dictBuffer,
size_t maxDictSize,
const void * samplesBuffer,
const size_t * samplesSizes,
unsigned nbSamples,
ZDICT_legacy_params_t params )
static

ZDICT_trainFromBuffer_unsafe_legacy() : Warning : samplesBuffer must be followed by noisy guard band !!!

Returns
: size of dictionary, or an error code which can be tested with ZDICT_isError()
650169{
650170 U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
650171 dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
650172 unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
650173 unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
650174 size_t const targetDictSize = maxDictSize;
650175 size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
650176 size_t dictSize = 0;
650177 U32 const notificationLevel = params.zParams.notificationLevel;
650178
650179 /* checks */
650180 if (!dictList) return ERROR(memory_allocation);
650181 if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); } /* requested dictionary size is too small */
650182 if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); } /* not enough source to create dictionary */
650183
650184 /* init */
650185 ZDICT_initDictItem(dictList);
650186
650187 /* build dictionary */
650188 ZDICT_trainBuffer_legacy(dictList, dictListSize,
650189 samplesBuffer, samplesBuffSize,
650190 samplesSizes, nbSamples,
650191 minRep, notificationLevel);
650192
650193 /* display best matches */
650194 if (params.zParams.notificationLevel>= 3) {
650195 unsigned const nb = MIN(25, dictList[0].pos);
650196 unsigned const dictContentSize = ZDICT_dictSize(dictList);
650197 unsigned u;
650198
650199 (void) dictContentSize;
650200
650201 DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
650202 DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
650203 for (u=1; u<nb; u++) {
650204 unsigned const pos = dictList[u].pos;
650205 unsigned const length = dictList[u].length;
650206 U32 const printedLength = MIN(40, length);
650207 if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
650208 free(dictList);
650209 return ERROR(GENERIC); /* should never happen */
650210 }
650211 DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
650212 u, length, pos, (unsigned)dictList[u].savings);
650213 ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
650214 DISPLAYLEVEL(3, "| \n");
650215 } }
650216
650217
650218 /* create dictionary */
650219 { unsigned dictContentSize = ZDICT_dictSize(dictList);
650220 if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); } /* dictionary content too small */
650221 if (dictContentSize < targetDictSize/4) {
650222 DISPLAYLEVEL(2, "! warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
650223 if (samplesBuffSize < 10 * targetDictSize)
650224 DISPLAYLEVEL(2, "! consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
650225 if (minRep > MINRATIO) {
650226 DISPLAYLEVEL(2, "! consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
650227 DISPLAYLEVEL(2, "! note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
650228 }
650229 }
650230
650231 if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
650232 unsigned proposedSelectivity = selectivity-1;
650233 while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
650234 DISPLAYLEVEL(2, "! note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
650235 DISPLAYLEVEL(2, "! consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
650236 DISPLAYLEVEL(2, "! always test dictionary efficiency on real samples \n");
650237 }
650238
650239 /* limit dictionary size */
650240 { U32 const max = dictList->pos; /* convention : nb of useful elts within dictList */
650241 U32 currentSize = 0;
650242 U32 n; for (n=1; n<max; n++) {
650243 currentSize += dictList[n].length;
650244 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
650245 }
650246 dictList->pos = n;
650247 dictContentSize = currentSize;
650248 }
650249
650250 /* build dict content */
650251 { U32 u;
650252 BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
650253 for (u=1; u<dictList->pos; u++) {
650254 U32 l = dictList[u].length;
650255 ptr -= l;
650256 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); } /* should not happen */
650257 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
650258 } }
650259
650260 dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
650261 samplesBuffer, samplesSizes, nbSamples,

Variable Documentation

◆ ZSTD_defaultCMem

ZSTD_customMem const duckdb_zstd::ZSTD_defaultCMem = { NULL, NULL, NULL }
static

this constant defers to stdlib's functions

408930{ NULL, NULL, NULL };

◆ BIT_mask

const unsigned duckdb_zstd::BIT_mask[]
static
Initial value:
= {
0, 1, 3, 7, 0xF, 0x1F,
0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF,
0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF,
0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,
0x3FFFFFFF, 0x7FFFFFFF}
609639 {
609640 0, 1, 3, 7, 0xF, 0x1F,
609641 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF,
609642 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF,
609643 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
609644 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,

◆ repStartValue

UNUSED_ATTR const U32 duckdb_zstd::repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 }
static

◆ ZSTD_fcs_fieldSize

UNUSED_ATTR const size_t duckdb_zstd::ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 }
static

◆ ZSTD_did_fieldSize

UNUSED_ATTR const size_t duckdb_zstd::ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 }
static
613998{ 0, 2, 4, 8 };

◆ LL_bits

UNUSED_ATTR const U8 duckdb_zstd::LL_bits[MaxLL+1]
static
Initial value:
= {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 2, 2, 3, 3,
4, 6, 7, 8, 9,10,11,12,
13,14,15,16
}
614038 {
614039 0, 0, 0, 0, 0, 0, 0, 0,
614040 0, 0, 0, 0, 0, 0, 0, 0,
614041 1, 1, 1, 1, 2, 2, 3, 3,
614042 4, 6, 7, 8, 9,10,11,12,
614043 13,14,15,16

◆ LL_defaultNorm

UNUSED_ATTR const S16 duckdb_zstd::LL_defaultNorm[MaxLL+1]
static
Initial value:
= {
4, 3, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2,
2, 3, 2, 1, 1, 1, 1, 1,
-1,-1,-1,-1
}
614045 {
614046 4, 3, 2, 2, 2, 2, 2, 2,
614047 2, 2, 2, 2, 2, 1, 1, 1,
614048 2, 2, 2, 2, 2, 2, 2, 2,
614049 2, 3, 2, 1, 1, 1, 1, 1,
614050 -1,-1,-1,-1

◆ ML_bits

UNUSED_ATTR const U8 duckdb_zstd::ML_bits[MaxML+1]
static
Initial value:
= {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 2, 2, 3, 3,
4, 4, 5, 7, 8, 9,10,11,
12,13,14,15,16
}
614055 {
614056 0, 0, 0, 0, 0, 0, 0, 0,
614057 0, 0, 0, 0, 0, 0, 0, 0,
614058 0, 0, 0, 0, 0, 0, 0, 0,
614059 0, 0, 0, 0, 0, 0, 0, 0,
614060 1, 1, 1, 1, 2, 2, 3, 3,
614061 4, 4, 5, 7, 8, 9,10,11,
614062 12,13,14,15,16

◆ ML_defaultNorm

UNUSED_ATTR const S16 duckdb_zstd::ML_defaultNorm[MaxML+1]
static
Initial value:
= {
1, 4, 3, 2, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1,-1,-1,
-1,-1,-1,-1,-1
}
614064 {
614065 1, 4, 3, 2, 2, 2, 2, 2,
614066 2, 1, 1, 1, 1, 1, 1, 1,
614067 1, 1, 1, 1, 1, 1, 1, 1,
614068 1, 1, 1, 1, 1, 1, 1, 1,
614069 1, 1, 1, 1, 1, 1, 1, 1,
614070 1, 1, 1, 1, 1, 1,-1,-1,
614071 -1,-1,-1,-1,-1

◆ OF_defaultNorm

UNUSED_ATTR const S16 duckdb_zstd::OF_defaultNorm[DefaultMaxOff+1]
static
Initial value:
= {
1, 1, 1, 1, 1, 1, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
-1,-1,-1,-1,-1
}
614076 {
614077 1, 1, 1, 1, 1, 1, 2, 2,
614078 2, 1, 1, 1, 1, 1, 1, 1,
614079 1, 1, 1, 1, 1, 1, 1, 1,
614080 -1,-1,-1,-1,-1

◆ kNullRawSeqStore

UNUSED_ATTR const rawSeqStore_t duckdb_zstd::kNullRawSeqStore = {NULL, 0, 0, 0, 0}
static

◆ attachDictSizeCutoffs

const size_t duckdb_zstd::attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1]
static
Initial value:
= {
8 KB,
8 KB,
16 KB,
32 KB,
32 KB,
32 KB,
32 KB,
32 KB,
8 KB,
8 KB
}
621998 {
621999 8 KB, /* unused */
622000 8 KB, /* ZSTD_fast */
622001 16 KB, /* ZSTD_dfast */
622002 32 KB, /* ZSTD_greedy */

◆ ZSTD_defaultCParameters

const ZSTD_compressionParameters duckdb_zstd::ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1]
static
626717 {
626718{ /* "default" - for any srcSize > 256 KB */
626719 /* W, C, H, S, L, TL, strat */
626720 { 19, 12, 13, 1, 6, 1, ZSTD_fast }, /* base for negative levels */
626721 { 19, 13, 14, 1, 7, 0, ZSTD_fast }, /* level 1 */
626722 { 20, 15, 16, 1, 6, 0, ZSTD_fast }, /* level 2 */
626723 { 21, 16, 17, 1, 5, 0, ZSTD_dfast }, /* level 3 */
626724 { 21, 18, 18, 1, 5, 0, ZSTD_dfast }, /* level 4 */
626725 { 21, 18, 19, 3, 5, 2, ZSTD_greedy }, /* level 5 */
626726 { 21, 18, 19, 3, 5, 4, ZSTD_lazy }, /* level 6 */
626727 { 21, 19, 20, 4, 5, 8, ZSTD_lazy }, /* level 7 */
626728 { 21, 19, 20, 4, 5, 16, ZSTD_lazy2 }, /* level 8 */
626729 { 22, 20, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 9 */
626730 { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 10 */
626731 { 22, 21, 22, 6, 5, 16, ZSTD_lazy2 }, /* level 11 */
626732 { 22, 22, 23, 6, 5, 32, ZSTD_lazy2 }, /* level 12 */
626733 { 22, 22, 22, 4, 5, 32, ZSTD_btlazy2 }, /* level 13 */
626734 { 22, 22, 23, 5, 5, 32, ZSTD_btlazy2 }, /* level 14 */
626735 { 22, 23, 23, 6, 5, 32, ZSTD_btlazy2 }, /* level 15 */
626736 { 22, 22, 22, 5, 5, 48, ZSTD_btopt }, /* level 16 */
626737 { 23, 23, 22, 5, 4, 64, ZSTD_btopt }, /* level 17 */
626738 { 23, 23, 22, 6, 3, 64, ZSTD_btultra }, /* level 18 */
626739 { 23, 24, 22, 7, 3,256, ZSTD_btultra2}, /* level 19 */
626740 { 25, 25, 23, 7, 3,256, ZSTD_btultra2}, /* level 20 */
626741 { 26, 26, 24, 7, 3,512, ZSTD_btultra2}, /* level 21 */
626742 { 27, 27, 25, 9, 3,999, ZSTD_btultra2}, /* level 22 */
626743},
626744{ /* for srcSize <= 256 KB */
626745 /* W, C, H, S, L, T, strat */
626746 { 18, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
626747 { 18, 13, 14, 1, 6, 0, ZSTD_fast }, /* level 1 */
626748 { 18, 14, 14, 1, 5, 0, ZSTD_dfast }, /* level 2 */
626749 { 18, 16, 16, 1, 4, 0, ZSTD_dfast }, /* level 3 */
626750 { 18, 16, 17, 3, 5, 2, ZSTD_greedy }, /* level 4.*/
626751 { 18, 17, 18, 5, 5, 2, ZSTD_greedy }, /* level 5.*/
626752 { 18, 18, 19, 3, 5, 4, ZSTD_lazy }, /* level 6.*/
626753 { 18, 18, 19, 4, 4, 4, ZSTD_lazy }, /* level 7 */
626754 { 18, 18, 19, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
626755 { 18, 18, 19, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
626756 { 18, 18, 19, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
626757 { 18, 18, 19, 5, 4, 12, ZSTD_btlazy2 }, /* level 11.*/
626758 { 18, 19, 19, 7, 4, 12, ZSTD_btlazy2 }, /* level 12.*/
626759 { 18, 18, 19, 4, 4, 16, ZSTD_btopt }, /* level 13 */
626760 { 18, 18, 19, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
626761 { 18, 18, 19, 6, 3,128, ZSTD_btopt }, /* level 15.*/
626762 { 18, 19, 19, 6, 3,128, ZSTD_btultra }, /* level 16.*/
626763 { 18, 19, 19, 8, 3,256, ZSTD_btultra }, /* level 17.*/
626764 { 18, 19, 19, 6, 3,128, ZSTD_btultra2}, /* level 18.*/
626765 { 18, 19, 19, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
626766 { 18, 19, 19, 10, 3,512, ZSTD_btultra2}, /* level 20.*/
626767 { 18, 19, 19, 12, 3,512, ZSTD_btultra2}, /* level 21.*/
626768 { 18, 19, 19, 13, 3,999, ZSTD_btultra2}, /* level 22.*/
626769},
626770{ /* for srcSize <= 128 KB */
626771 /* W, C, H, S, L, T, strat */
626772 { 17, 12, 12, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
626773 { 17, 12, 13, 1, 6, 0, ZSTD_fast }, /* level 1 */
626774 { 17, 13, 15, 1, 5, 0, ZSTD_fast }, /* level 2 */
626775 { 17, 15, 16, 2, 5, 0, ZSTD_dfast }, /* level 3 */
626776 { 17, 17, 17, 2, 4, 0, ZSTD_dfast }, /* level 4 */
626777 { 17, 16, 17, 3, 4, 2, ZSTD_greedy }, /* level 5 */
626778 { 17, 16, 17, 3, 4, 4, ZSTD_lazy }, /* level 6 */
626779 { 17, 16, 17, 3, 4, 8, ZSTD_lazy2 }, /* level 7 */
626780 { 17, 16, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
626781 { 17, 16, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
626782 { 17, 16, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
626783 { 17, 17, 17, 5, 4, 8, ZSTD_btlazy2 }, /* level 11 */
626784 { 17, 18, 17, 7, 4, 12, ZSTD_btlazy2 }, /* level 12 */
626785 { 17, 18, 17, 3, 4, 12, ZSTD_btopt }, /* level 13.*/
626786 { 17, 18, 17, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
626787 { 17, 18, 17, 6, 3,256, ZSTD_btopt }, /* level 15.*/
626788 { 17, 18, 17, 6, 3,128, ZSTD_btultra }, /* level 16.*/
626789 { 17, 18, 17, 8, 3,256, ZSTD_btultra }, /* level 17.*/
626790 { 17, 18, 17, 10, 3,512, ZSTD_btultra }, /* level 18.*/
626791 { 17, 18, 17, 5, 3,256, ZSTD_btultra2}, /* level 19.*/
626792 { 17, 18, 17, 7, 3,512, ZSTD_btultra2}, /* level 20.*/
626793 { 17, 18, 17, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
626794 { 17, 18, 17, 11, 3,999, ZSTD_btultra2}, /* level 22.*/
626795},
626796{ /* for srcSize <= 16 KB */
626797 /* W, C, H, S, L, T, strat */
626798 { 14, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
626799 { 14, 14, 15, 1, 5, 0, ZSTD_fast }, /* level 1 */
626800 { 14, 14, 15, 1, 4, 0, ZSTD_fast }, /* level 2 */
626801 { 14, 14, 15, 2, 4, 0, ZSTD_dfast }, /* level 3 */
626802 { 14, 14, 14, 4, 4, 2, ZSTD_greedy }, /* level 4 */
626803 { 14, 14, 14, 3, 4, 4, ZSTD_lazy }, /* level 5.*/
626804 { 14, 14, 14, 4, 4, 8, ZSTD_lazy2 }, /* level 6 */
626805 { 14, 14, 14, 6, 4, 8, ZSTD_lazy2 }, /* level 7 */
626806 { 14, 14, 14, 8, 4, 8, ZSTD_lazy2 }, /* level 8.*/
626807 { 14, 15, 14, 5, 4, 8, ZSTD_btlazy2 }, /* level 9.*/
626808 { 14, 15, 14, 9, 4, 8, ZSTD_btlazy2 }, /* level 10.*/
626809 { 14, 15, 14, 3, 4, 12, ZSTD_btopt }, /* level 11.*/
626810 { 14, 15, 14, 4, 3, 24, ZSTD_btopt }, /* level 12.*/
626811 { 14, 15, 14, 5, 3, 32, ZSTD_btultra }, /* level 13.*/
626812 { 14, 15, 15, 6, 3, 64, ZSTD_btultra }, /* level 14.*/
626813 { 14, 15, 15, 7, 3,256, ZSTD_btultra }, /* level 15.*/
626814 { 14, 15, 15, 5, 3, 48, ZSTD_btultra2}, /* level 16.*/
626815 { 14, 15, 15, 6, 3,128, ZSTD_btultra2}, /* level 17.*/

◆ kInverseProbabilityLog256

unsigned const duckdb_zstd::kInverseProbabilityLog256[256]
static
Initial value:
= {
0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,
1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,
874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,
724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,
618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,
535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,
468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,
411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,
362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,
318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,
279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,
244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,
212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,
182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,
155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,
130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,
106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85,
83, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64,
62, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44,
42, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25,
23, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7,
5, 4, 2, 1,
}

-log2(x / 256) lookup table for x in [0, 256). If x == 0: Return 0 Else: Return floor(-log2(x / 256) * 256)

627275 {
627276
627282static unsigned const kInverseProbabilityLog256[256] = {
627283 0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,
627284 1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,
627285 874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,
627286 724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,
627287 618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,
627288 535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,
627289 468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,
627290 411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,
627291 362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,
627292 318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,
627293 279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,
627294 244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,
627295 212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,
627296 182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,
627297 155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,
627298 130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,
static unsigned const kInverseProbabilityLog256[256]
Definition duckdb.cpp:627275

◆ ZSTD_ldm_gearTab

UNUSED_ATTR const U64 duckdb_zstd::ZSTD_ldm_gearTab[256]
static
632431 {
632432
632433static UNUSED_ATTR const U64 ZSTD_ldm_gearTab[256] = {
632434 0xf5b8f72c5f77775c, 0x84935f266b7ac412, 0xb647ada9ca730ccc,
632435 0xb065bb4b114fb1de, 0x34584e7e8c3a9fd0, 0x4e97e17c6ae26b05,
632436 0x3a03d743bc99a604, 0xcecd042422c4044f, 0x76de76c58524259e,
632437 0x9c8528f65badeaca, 0x86563706e2097529, 0x2902475fa375d889,
632438 0xafb32a9739a5ebe6, 0xce2714da3883e639, 0x21eaf821722e69e,
632439 0x37b628620b628, 0x49a8d455d88caf5, 0x8556d711e6958140,
632440 0x4f7ae74fc605c1f, 0x829f0c3468bd3a20, 0x4ffdc885c625179e,
632441 0x8473de048a3daf1b, 0x51008822b05646b2, 0x69d75d12b2d1cc5f,
632442 0x8c9d4a19159154bc, 0xc3cc10f4abbd4003, 0xd06ddc1cecb97391,
632443 0xbe48e6e7ed80302e, 0x3481db31cee03547, 0xacc3f67cdaa1d210,
632444 0x65cb771d8c7f96cc, 0x8eb27177055723dd, 0xc789950d44cd94be,
632445 0x934feadc3700b12b, 0x5e485f11edbdf182, 0x1e2e2a46fd64767a,
632446 0x2969ca71d82efa7c, 0x9d46e9935ebbba2e, 0xe056b67e05e6822b,
632447 0x94d73f55739d03a0, 0xcd7010bdb69b5a03, 0x455ef9fcd79b82f4,
632448 0x869cb54a8749c161, 0x38d1a4fa6185d225, 0xb475166f94bbe9bb,
632449 0xa4143548720959f1, 0x7aed4780ba6b26ba, 0xd0ce264439e02312,
632450 0x84366d746078d508, 0xa8ce973c72ed17be, 0x21c323a29a430b01,
632451 0x9962d617e3af80ee, 0xab0ce91d9c8cf75b, 0x530e8ee6d19a4dbc,
632452 0x2ef68c0cf53f5d72, 0xc03a681640a85506, 0x496e4e9f9c310967,
632453 0x78580472b59b14a0, 0x273824c23b388577, 0x66bf923ad45cb553,
632454 0x47ae1a5a2492ba86, 0x35e304569e229659, 0x4765182a46870b6f,
632455 0x6cbab625e9099412, 0xddac9a2e598522c1, 0x7172086e666624f2,
632456 0xdf5003ca503b7837, 0x88c0c1db78563d09, 0x58d51865acfc289d,
632457 0x177671aec65224f1, 0xfb79d8a241e967d7, 0x2be1e101cad9a49a,
632458 0x6625682f6e29186b, 0x399553457ac06e50, 0x35dffb4c23abb74,
632459 0x429db2591f54aade, 0xc52802a8037d1009, 0x6acb27381f0b25f3,
632460 0xf45e2551ee4f823b, 0x8b0ea2d99580c2f7, 0x3bed519cbcb4e1e1,
632461 0xff452823dbb010a, 0x9d42ed614f3dd267, 0x5b9313c06257c57b,
632462 0xa114b8008b5e1442, 0xc1fe311c11c13d4b, 0x66e8763ea34c5568,
632463 0x8b982af1c262f05d, 0xee8876faaa75fbb7, 0x8a62a4d0d172bb2a,
632464 0xc13d94a3b7449a97, 0x6dbbba9dc15d037c, 0xc786101f1d92e0f1,
632465 0xd78681a907a0b79b, 0xf61aaf2962c9abb9, 0x2cfd16fcd3cb7ad9,
632466 0x868c5b6744624d21, 0x25e650899c74ddd7, 0xba042af4a7c37463,
632467 0x4eb1a539465a3eca, 0xbe09dbf03b05d5ca, 0x774e5a362b5472ba,
632468 0x47a1221229d183cd, 0x504b0ca18ef5a2df, 0xdffbdfbde2456eb9,
632469 0x46cd2b2fbee34634, 0xf2aef8fe819d98c3, 0x357f5276d4599d61,
632470 0x24a5483879c453e3, 0x88026889192b4b9, 0x28da96671782dbec,
632471 0x4ef37c40588e9aaa, 0x8837b90651bc9fb3, 0xc164f741d3f0e5d6,
632472 0xbc135a0a704b70ba, 0x69cd868f7622ada, 0xbc37ba89e0b9c0ab,
632473 0x47c14a01323552f6, 0x4f00794bacee98bb, 0x7107de7d637a69d5,
632474 0x88af793bb6f2255e, 0xf3c6466b8799b598, 0xc288c616aa7f3b59,
632475 0x81ca63cf42fca3fd, 0x88d85ace36a2674b, 0xd056bd3792389e7,
632476 0xe55c396c4e9dd32d, 0xbefb504571e6c0a6, 0x96ab32115e91e8cc,
632477 0xbf8acb18de8f38d1, 0x66dae58801672606, 0x833b6017872317fb,
632478 0xb87c16f2d1c92864, 0xdb766a74e58b669c, 0x89659f85c61417be,
632479 0xc8daad856011ea0c, 0x76a4b565b6fe7eae, 0xa469d085f6237312,
632480 0xaaf0365683a3e96c, 0x4dbb746f8424f7b8, 0x638755af4e4acc1,
632481 0x3d7807f5bde64486, 0x17be6d8f5bbb7639, 0x903f0cd44dc35dc,
632482 0x67b672eafdf1196c, 0xa676ff93ed4c82f1, 0x521d1004c5053d9d,
632483 0x37ba9ad09ccc9202, 0x84e54d297aacfb51, 0xa0b4b776a143445,
632484 0x820d471e20b348e, 0x1874383cb83d46dc, 0x97edeec7a1efe11c,
632485 0xb330e50b1bdc42aa, 0x1dd91955ce70e032, 0xa514cdb88f2939d5,
632486 0x2791233fd90db9d3, 0x7b670a4cc50f7a9b, 0x77c07d2a05c6dfa5,
632487 0xe3778b6646d0a6fa, 0xb39c8eda47b56749, 0x933ed448addbef28,
632488 0xaf846af6ab7d0bf4, 0xe5af208eb666e49, 0x5e6622f73534cd6a,
632489 0x297daeca42ef5b6e, 0x862daef3d35539a6, 0xe68722498f8e1ea9,
632490 0x981c53093dc0d572, 0xfa09b0bfbf86fbf5, 0x30b1e96166219f15,
632491 0x70e7d466bdc4fb83, 0x5a66736e35f2a8e9, 0xcddb59d2b7c1baef,
632492 0xd6c7d247d26d8996, 0xea4e39eac8de1ba3, 0x539c8bb19fa3aff2,
632493 0x9f90e4c5fd508d8, 0xa34e5956fbaf3385, 0x2e2f8e151d3ef375,
632494 0x173691e9b83faec1, 0xb85a8d56bf016379, 0x8382381267408ae3,
632495 0xb90f901bbdc0096d, 0x7c6ad32933bcec65, 0x76bb5e2f2c8ad595,
632496 0x390f851a6cf46d28, 0xc3e6064da1c2da72, 0xc52a0c101cfa5389,
632497 0xd78eaf84a3fbc530, 0x3781b9e2288b997e, 0x73c2f6dea83d05c4,
632498 0x4228e364c5b5ed7, 0x9d7a3edf0da43911, 0x8edcfeda24686756,
632499 0x5e7667a7b7a9b3a1, 0x4c4f389fa143791d, 0xb08bc1023da7cddc,
632500 0x7ab4be3ae529b1cc, 0x754e6132dbe74ff9, 0x71635442a839df45,
632501 0x2f6fb1643fbe52de, 0x961e0a42cf7a8177, 0xf3b45d83d89ef2ea,
632502 0xee3de4cf4a6e3e9b, 0xcd6848542c3295e7, 0xe4cee1664c78662f,
632503 0x9947548b474c68c4, 0x25d73777a5ed8b0b, 0xc915b1d636b7fc,
632504 0x21c2ba75d9b0d2da, 0x5f6b5dcf608a64a1, 0xdcf333255ff9570c,
632505 0x633b922418ced4ee, 0xc136dde0b004b34a, 0x58cc83b05d4b2f5a,
632506 0x5eb424dda28e42d2, 0x62df47369739cd98, 0xb4e0b42485e4ce17,
632507 0x16e1f0c1f9a8d1e7, 0x8ec3916707560ebf, 0x62ba6e2df2cc9db3,
632508 0xcbf9f4ff77d83a16, 0x78d9d7d07d2bbcc4, 0xef554ce1e02c41f4,
632509 0x8d7581127eccf94d, 0xa9b53336cb3c8a05, 0x38c42c0bf45c4f91,
632510 0x640893cdf4488863, 0x80ec34bc575ea568, 0x39f324f5b48eaa40,
632511 0xe9d9ed1f8eff527f, 0x9224fc058cc5a214, 0xbaba00b04cfe7741,
632512 0x309a9f120fcf52af, 0xa558f3ec65626212, 0x424bec8b7adabe2f,
632513 0x41622513a6aea433, 0xb88da2d5324ca798, 0xd287733b245528a4,

◆ g_nullBuffer

const buffer_t duckdb_zstd::g_nullBuffer = { NULL, 0 }
static

◆ kNullRange

const range_t duckdb_zstd::kNullRange = { NULL, 0 }
static

◆ kNullRoundBuff

const roundBuff_t duckdb_zstd::kNullRoundBuff = {NULL, 0, 0}
static

◆ algoTime

const algo_time_t duckdb_zstd::algoTime[16][2]
static
Initial value:
=
{
{{0,0}, {1,1}},
{{0,0}, {1,1}},
{{ 150,216}, { 381,119}},
{{ 170,205}, { 514,112}},
{{ 177,199}, { 539,110}},
{{ 197,194}, { 644,107}},
{{ 221,192}, { 735,107}},
{{ 256,189}, { 881,106}},
{{ 359,188}, {1167,109}},
{{ 582,187}, {1570,114}},
{{ 688,187}, {1712,122}},
{{ 825,186}, {1965,136}},
{{ 976,185}, {2131,150}},
{{1180,186}, {2070,175}},
{{1377,185}, {1731,202}},
{{1412,185}, {1695,202}},
}
638496 { U32 tableTime; U32 decode256Time; } algo_time_t;
638497static const algo_time_t algoTime[16 /* Quantization */][2 /* single, double */] =
638498{
638499 /* single, double, quad */
638500 {{0,0}, {1,1}}, /* Q==0 : impossible */
638501 {{0,0}, {1,1}}, /* Q==1 : impossible */
638502 {{ 150,216}, { 381,119}}, /* Q == 2 : 12-18% */
638503 {{ 170,205}, { 514,112}}, /* Q == 3 : 18-25% */
638504 {{ 177,199}, { 539,110}}, /* Q == 4 : 25-32% */
638505 {{ 197,194}, { 644,107}}, /* Q == 5 : 32-38% */
638506 {{ 221,192}, { 735,107}}, /* Q == 6 : 38-44% */
638507 {{ 256,189}, { 881,106}}, /* Q == 7 : 44-50% */
638508 {{ 359,188}, {1167,109}}, /* Q == 8 : 50-56% */
638509 {{ 582,187}, {1570,114}}, /* Q == 9 : 56-62% */

◆ LL_base

UNUSED_ATTR const U32 duckdb_zstd::LL_base[MaxLL+1]
static
Initial value:
= {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 18, 20, 22, 24, 28, 32, 40,
48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
0x2000, 0x4000, 0x8000, 0x10000 }
638712 {
638713
638714/*-*******************************************************
638715 * Constants

◆ OF_base

UNUSED_ATTR const U32 duckdb_zstd::OF_base[MaxOff+1]
static
Initial value:
= {
0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD }
638717 {
638718 0, 1, 2, 3, 4, 5, 6, 7,
638719 8, 9, 10, 11, 12, 13, 14, 15,
638720 16, 18, 20, 22, 24, 28, 32, 40,
638721 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,

◆ OF_bits

UNUSED_ATTR const U8 duckdb_zstd::OF_bits[MaxOff+1]
static
Initial value:
= {
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, 25, 26, 27, 28, 29, 30, 31 }
638724 {
638725 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
638726 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
638727 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,

◆ ML_base

UNUSED_ATTR const U32 duckdb_zstd::ML_base[MaxML+1]
static
Initial value:
= {
3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34,
35, 37, 39, 41, 43, 47, 51, 59,
67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
0x1003, 0x2003, 0x4003, 0x8003, 0x10003 }
638730 {
638731 0, 1, 2, 3, 4, 5, 6, 7,
638732 8, 9, 10, 11, 12, 13, 14, 15,
638733 16, 17, 18, 19, 20, 21, 22, 23,
638734 24, 25, 26, 27, 28, 29, 30, 31 };
638735
638736static UNUSED_ATTR const U32 ML_base[MaxML+1] = {

◆ LL_defaultDTable

const ZSTD_seqSymbol duckdb_zstd::LL_defaultDTable[(1<< LL_DEFAULTNORMLOG)+1]
static
642079 :
642080 * - start from default distributions, present in /lib/common/zstd_internal.h
642081 * - generate tables normally, using ZSTD_buildFSETable()
642082 * - printout the content of tables
642083 * - pretify output, report below, test with fuzzer to ensure it's correct */
642084
642085/* Default FSE distribution table for Literal Lengths */
642086static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
642087 { 1, 1, 1, LL_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
642088 /* nextState, nbAddBits, nbBits, baseVal */
642089 { 0, 0, 4, 0}, { 16, 0, 4, 0},
642090 { 32, 0, 5, 1}, { 0, 0, 5, 3},
642091 { 0, 0, 5, 4}, { 0, 0, 5, 6},
642092 { 0, 0, 5, 7}, { 0, 0, 5, 9},
642093 { 0, 0, 5, 10}, { 0, 0, 5, 12},
642094 { 0, 0, 6, 14}, { 0, 1, 5, 16},
642095 { 0, 1, 5, 20}, { 0, 1, 5, 22},
642096 { 0, 2, 5, 28}, { 0, 3, 5, 32},
642097 { 0, 4, 5, 48}, { 32, 6, 5, 64},
642098 { 0, 7, 5, 128}, { 0, 8, 6, 256},
642099 { 0, 10, 6, 1024}, { 0, 12, 6, 4096},
642100 { 32, 0, 4, 0}, { 0, 0, 4, 1},
642101 { 0, 0, 5, 2}, { 32, 0, 5, 4},
642102 { 0, 0, 5, 5}, { 32, 0, 5, 7},
642103 { 0, 0, 5, 8}, { 32, 0, 5, 10},
642104 { 0, 0, 5, 11}, { 0, 0, 6, 13},
642105 { 32, 1, 5, 16}, { 0, 1, 5, 18},
642106 { 32, 1, 5, 22}, { 0, 2, 5, 24},
642107 { 32, 3, 5, 32}, { 0, 3, 5, 40},
642108 { 0, 6, 4, 64}, { 16, 6, 4, 64},
642109 { 32, 7, 5, 128}, { 0, 9, 6, 512},
642110 { 0, 11, 6, 2048}, { 48, 0, 4, 0},
642111 { 16, 0, 4, 1}, { 32, 0, 5, 2},
642112 { 32, 0, 5, 3}, { 32, 0, 5, 5},
642113 { 32, 0, 5, 6}, { 32, 0, 5, 8},
642114 { 32, 0, 5, 9}, { 32, 0, 5, 11},

◆ OF_defaultDTable

const ZSTD_seqSymbol duckdb_zstd::OF_defaultDTable[(1<< OF_DEFAULTNORMLOG)+1]
static
Initial value:
= {
{ 1, 1, 1, OF_DEFAULTNORMLOG},
{ 0, 0, 5, 0}, { 0, 6, 4, 61},
{ 0, 9, 5, 509}, { 0, 15, 5,32765},
{ 0, 21, 5,2097149}, { 0, 3, 5, 5},
{ 0, 7, 4, 125}, { 0, 12, 5, 4093},
{ 0, 18, 5,262141}, { 0, 23, 5,8388605},
{ 0, 5, 5, 29}, { 0, 8, 4, 253},
{ 0, 14, 5,16381}, { 0, 20, 5,1048573},
{ 0, 2, 5, 1}, { 16, 7, 4, 125},
{ 0, 11, 5, 2045}, { 0, 17, 5,131069},
{ 0, 22, 5,4194301}, { 0, 4, 5, 13},
{ 16, 8, 4, 253}, { 0, 13, 5, 8189},
{ 0, 19, 5,524285}, { 0, 1, 5, 1},
{ 16, 6, 4, 61}, { 0, 10, 5, 1021},
{ 0, 16, 5,65533}, { 0, 28, 5,268435453},
{ 0, 27, 5,134217725}, { 0, 26, 5,67108861},
{ 0, 25, 5,33554429}, { 0, 24, 5,16777213},
}
642117 { 32, 2, 5, 24}, { 32, 2, 5, 28},
642118 { 32, 3, 5, 40}, { 32, 4, 5, 48},
642119 { 0, 16, 6,65536}, { 0, 15, 6,32768},
642120 { 0, 14, 6,16384}, { 0, 13, 6, 8192},
642121}; /* LL_defaultDTable */
642122
642123/* Default FSE distribution table for Offset Codes */
642124static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
642125 { 1, 1, 1, OF_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
642126 /* nextState, nbAddBits, nbBits, baseVal */
642127 { 0, 0, 5, 0}, { 0, 6, 4, 61},
642128 { 0, 9, 5, 509}, { 0, 15, 5,32765},
642129 { 0, 21, 5,2097149}, { 0, 3, 5, 5},
642130 { 0, 7, 4, 125}, { 0, 12, 5, 4093},
642131 { 0, 18, 5,262141}, { 0, 23, 5,8388605},
642132 { 0, 5, 5, 29}, { 0, 8, 4, 253},
642133 { 0, 14, 5,16381}, { 0, 20, 5,1048573},
642134 { 0, 2, 5, 1}, { 16, 7, 4, 125},
642135 { 0, 11, 5, 2045}, { 0, 17, 5,131069},
642136 { 0, 22, 5,4194301}, { 0, 4, 5, 13},

◆ ML_defaultDTable

const ZSTD_seqSymbol duckdb_zstd::ML_defaultDTable[(1<< ML_DEFAULTNORMLOG)+1]
static
642140 { 0, 16, 5,65533}, { 0, 28, 5,268435453},
642141 { 0, 27, 5,134217725}, { 0, 26, 5,67108861},
642142 { 0, 25, 5,33554429}, { 0, 24, 5,16777213},
642143}; /* OF_defaultDTable */
642144
642145
642146/* Default FSE distribution table for Match Lengths */
642147static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
642148 { 1, 1, 1, ML_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
642149 /* nextState, nbAddBits, nbBits, baseVal */
642150 { 0, 0, 6, 3}, { 0, 0, 4, 4},
642151 { 32, 0, 5, 5}, { 0, 0, 5, 6},
642152 { 0, 0, 5, 8}, { 0, 0, 5, 9},
642153 { 0, 0, 5, 11}, { 0, 0, 6, 13},
642154 { 0, 0, 6, 16}, { 0, 0, 6, 19},
642155 { 0, 0, 6, 22}, { 0, 0, 6, 25},
642156 { 0, 0, 6, 28}, { 0, 0, 6, 31},
642157 { 0, 0, 6, 34}, { 0, 1, 6, 37},
642158 { 0, 1, 6, 41}, { 0, 2, 6, 47},
642159 { 0, 3, 6, 59}, { 0, 4, 6, 83},
642160 { 0, 7, 6, 131}, { 0, 9, 6, 515},
642161 { 16, 0, 4, 4}, { 0, 0, 4, 5},
642162 { 32, 0, 5, 6}, { 0, 0, 5, 7},
642163 { 32, 0, 5, 9}, { 0, 0, 5, 10},
642164 { 0, 0, 6, 12}, { 0, 0, 6, 15},
642165 { 0, 0, 6, 18}, { 0, 0, 6, 21},
642166 { 0, 0, 6, 24}, { 0, 0, 6, 27},
642167 { 0, 0, 6, 30}, { 0, 0, 6, 33},
642168 { 0, 1, 6, 35}, { 0, 1, 6, 39},
642169 { 0, 2, 6, 43}, { 0, 3, 6, 51},
642170 { 0, 4, 6, 67}, { 0, 5, 6, 99},
642171 { 0, 8, 6, 259}, { 32, 0, 4, 4},
642172 { 48, 0, 4, 4}, { 16, 0, 4, 5},
642173 { 32, 0, 5, 7}, { 32, 0, 5, 8},
642174 { 32, 0, 5, 10}, { 32, 0, 5, 11},
642175 { 0, 0, 6, 14}, { 0, 0, 6, 17},

◆ COVER_prime4bytes

const U32 duckdb_zstd::COVER_prime4bytes = 2654435761U
static

Internal hash function

◆ lg_table

const int duckdb_zstd::lg_table[256]
static
Initial value:
= {
-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
}
646614 {
646615
646616/*- Private Functions -*/
646617
646618static const int lg_table[256]= {
646619 -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
646620 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,

◆ sqq_table

const int duckdb_zstd::sqq_table[256]
static
Initial value:
= {
0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, 59, 61,
64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84, 86, 87, 89,
90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104, 106, 107, 108, 109,
110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155,
156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180,
181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191,
192, 192, 193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201,
202, 203, 203, 204, 204, 205, 206, 206, 207, 208, 208, 209, 209, 210, 211, 211,
212, 212, 213, 214, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 221,
221, 222, 222, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230,
230, 231, 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238,
239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247,
247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255
}
646655 {
646656 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, 59, 61,
646657 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84, 86, 87, 89,
646658 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104, 106, 107, 108, 109,
646659110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
646660128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
646661143, 144, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155,
646662156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
646663169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180,
646664181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191,
646665192, 192, 193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201,

◆ FASTCOVER_defaultAccelParameters

const FASTCOVER_accel_t duckdb_zstd::FASTCOVER_defaultAccelParameters[FASTCOVER_MAX_ACCEL+1]
static
Initial value:
= {
{ 100, 0 },
{ 100, 0 },
{ 50, 1 },
{ 34, 2 },
{ 25, 3 },
{ 20, 4 },
{ 17, 5 },
{ 14, 6 },
{ 13, 7 },
{ 11, 8 },
{ 10, 9 },
}
648506 {
648507 unsigned finalize; /* Percentage of training samples used for ZDICT_finalizeDictionary */
648508 unsigned skip; /* Number of dmer skipped between each dmer counted in computeFrequency */
648509} FASTCOVER_accel_t;
648510
648511
648512static const FASTCOVER_accel_t FASTCOVER_defaultAccelParameters[FASTCOVER_MAX_ACCEL+1] = {
648513 { 100, 0 }, /* accel = 0, should not happen because accel = 0 defaults to accel = 1 */
648514 { 100, 0 }, /* accel = 1 */
648515 { 50, 1 }, /* accel = 2 */
648516 { 34, 2 }, /* accel = 3 */
648517 { 25, 3 }, /* accel = 4 */