ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_internal.h
Go to the documentation of this file.
1/* SPDX-License-Identifier: BSD-3-Clause */
2/*
3 * ZXC - High-performance lossless compression
4 *
5 * Copyright (c) Bertrand Lebonnois and contributors.
6 */
7
25
26#ifndef ZXC_INTERNAL_H
27#define ZXC_INTERNAL_H
28
29#if !defined(__cplusplus) && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L)
30#error "libzxc requires C11 or later (MSVC: /std:c11)"
31#endif
32
33#include "zxc_deps.h" /* libc deps: <assert.h>, <limits.h>, <stdint.h>, <stdlib.h>, <string.h>,
34 and the ZXC_MALLOC / ZXC_ALIGNED_MALLOC macros.
35 Vendor this file to retarget non-libc environments. */
36
41#include "rapidhash.h"
42#include "zxc_build.h"
43
44#ifdef __cplusplus
45extern "C" {
46#endif
47
53
62#if !defined(__cplusplus) && !defined(__STDC_NO_ATOMICS__)
63#include <stdatomic.h>
64#define ZXC_ATOMIC _Atomic
65#define ZXC_USE_C11_ATOMICS 1
66#else
67#define ZXC_ATOMIC volatile
68#define ZXC_USE_C11_ATOMICS 0
69#endif /* end of Atomic Qualifier */
71
99#ifndef ZXC_DISABLE_SIMD
100#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)
101#include <immintrin.h>
102#include <nmmintrin.h>
103#if defined(__AVX512F__) && defined(__AVX512BW__)
104#ifndef ZXC_USE_AVX512
105#define ZXC_USE_AVX512
106#endif
107#endif
108#if defined(__AVX2__)
109#ifndef ZXC_USE_AVX2
110#define ZXC_USE_AVX2
111#endif
112#endif
113#if defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
114#ifndef ZXC_USE_SSE2
115#define ZXC_USE_SSE2
116#endif
117#endif
118#elif (defined(__ARM_NEON) || defined(__ARM_NEON__) || defined(_M_ARM64) || \
119 defined(ZXC_USE_NEON32) || defined(ZXC_USE_NEON64))
120#if !defined(_MSC_VER)
121#include <arm_acle.h>
122#endif
123#include <arm_neon.h>
124#if defined(__aarch64__) || defined(_M_ARM64)
125#ifndef ZXC_USE_NEON64
126#define ZXC_USE_NEON64
127#endif
128#else
129#ifndef ZXC_USE_NEON32
130#define ZXC_USE_NEON32
131#endif
132#endif
133#endif
134#endif /* ZXC_DISABLE_SIMD */ /* end of SIMD Intrinsics */
136
143
144#if defined(__GNUC__) || defined(__clang__)
149#define LIKELY(x) (__builtin_expect(!!(x), 1))
150
155#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
156
160#define RESTRICT __restrict__
161
166#define ZXC_PREFETCH_READ(ptr) __builtin_prefetch((const void*)(ptr), 0, 3)
167
171#define ZXC_MEMCPY(dst, src, n) __builtin_memcpy(dst, src, n)
172
176#define ZXC_MEMSET(dst, val, n) __builtin_memset(dst, val, n)
177
182#define ZXC_ALIGN(x) __attribute__((aligned(x)))
183
187#define ZXC_ALWAYS_INLINE inline __attribute__((always_inline))
188
192#define ZXC_NOINLINE __attribute__((__noinline__))
193
200#define ZXC_COLD __attribute__((cold))
201
202#elif defined(_MSC_VER)
203#include <intrin.h>
204#if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)
205#include <xmmintrin.h>
206#define ZXC_PREFETCH_READ(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
207#else
208#define ZXC_PREFETCH_READ(ptr) __prefetch((const void*)(ptr))
209#endif
210#define LIKELY(x) (x)
211#define UNLIKELY(x) (x)
212#define RESTRICT __restrict
213#pragma intrinsic(memcpy, memset)
214#define ZXC_MEMCPY(dst, src, n) memcpy(dst, src, n)
215#define ZXC_MEMSET(dst, val, n) memset(dst, val, n)
216
221#define ZXC_ALIGN(x) __declspec(align(x))
222
226#define ZXC_ALWAYS_INLINE __forceinline
227
231#define ZXC_NOINLINE __declspec(noinline)
233#define ZXC_COLD
234#pragma intrinsic(_BitScanReverse)
235#else
236#define LIKELY(x) (x)
237#define UNLIKELY(x) (x)
238#define RESTRICT
239#define ZXC_PREFETCH_READ(ptr)
240#define ZXC_MEMCPY(dst, src, n) memcpy(dst, src, n)
241#define ZXC_MEMSET(dst, val, n) memset(dst, val, n)
242
246#define ZXC_ALWAYS_INLINE inline
247
251#define ZXC_NOINLINE
252#define ZXC_COLD
253
258#define ZXC_ALIGN(x) _Alignas(x)
259#endif /* end of Compiler Abstractions */
261
262// Heap allocator and cache-line-aligned allocator macros are now defined
263// in @c zxc_deps.h (included at the top of this header), so non-libc
264// targets can override them by vendoring that single file.
265
273#ifndef ZXC_LITTLE_ENDIAN
274#if defined(_WIN32) || defined(__LITTLE_ENDIAN__) || \
275 (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
276#define ZXC_LITTLE_ENDIAN
277#elif defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
278#define ZXC_BIG_ENDIAN
279#else
280#warning "Endianness not detected, defaulting to little-endian"
281#define ZXC_LITTLE_ENDIAN
282#endif
283#endif /* end of Endianness Detection */
285
291#ifdef ZXC_BIG_ENDIAN
292#if defined(__GNUC__) || defined(__clang__)
293#define ZXC_BSWAP16(x) __builtin_bswap16(x)
294#define ZXC_BSWAP32(x) __builtin_bswap32(x)
295#define ZXC_BSWAP64(x) __builtin_bswap64(x)
296#elif defined(_MSC_VER)
297#define ZXC_BSWAP16(x) _byteswap_ushort(x)
298#define ZXC_BSWAP32(x) _byteswap_ulong(x)
299#define ZXC_BSWAP64(x) _byteswap_uint64(x)
300#else
301#define ZXC_BSWAP16(x) ((uint16_t)(((x) >> 8) | ((x) << 8)))
302#define ZXC_BSWAP32(x) \
303 ((uint32_t)(((x) >> 24) | (((x) >> 8) & 0xFF00) | (((x) << 8) & 0xFF0000) | ((x) << 24)))
304#define ZXC_BSWAP64(x) \
305 ((uint64_t)(((uint64_t)ZXC_BSWAP32((uint32_t)(x)) << 32) | ZXC_BSWAP32((uint32_t)((x) >> 32))))
306#endif
307#endif /* end of Byte-Swap Helpers */
309
316
319static inline int zxc_magic_prefix_ok(const uint8_t* p, const size_t n) {
320 static const uint8_t magic[4] = {(uint8_t)ZXC_MAGIC_WORD, (uint8_t)(ZXC_MAGIC_WORD >> 8),
321 (uint8_t)(ZXC_MAGIC_WORD >> 16),
322 (uint8_t)(ZXC_MAGIC_WORD >> 24)};
323 for (size_t i = 0; i < n && i < sizeof(magic); i++)
324 if (p[i] != magic[i]) return 0;
325 return 1;
326}
327
329#define ZXC_FILE_FORMAT_VERSION 9
330
332#define ZXC_PAD_SIZE 32
346#define ZXC_BLOCK_LIT_SLACK 32
362#define ZXC_DECOMPRESS_TAIL_PAD (4 * ZXC_PAK_MAX_INLINE_OUT_PER_SEQ + ZXC_PAD_SIZE) /* 2084 */
368#define ZXC_MT_BATCH_BYTES ((size_t)256 * 1024)
370#define ZXC_CACHE_LINE_SIZE 64
372#define ZXC_ALIGNMENT_MASK ((size_t)ZXC_CACHE_LINE_SIZE - 1)
374#define ZXC_ALIGN_CL(x) (((x) + ZXC_ALIGNMENT_MASK) & ~(size_t)ZXC_ALIGNMENT_MASK)
375static_assert((ZXC_CACHE_LINE_SIZE & ZXC_ALIGNMENT_MASK) == 0,
376 "ZXC_CACHE_LINE_SIZE must be a power of two");
377
383#define ZXC_BITMAP_WORDS(n_bits) (((n_bits) + 63) / 64)
384
386#define ZXC_FILE_FLAG_HAS_CHECKSUM 0x80U
388#define ZXC_FILE_FLAG_HAS_DICTIONARY 0x40U
391#define ZXC_FILE_FLAG_HAS_SEEK_TABLE 0x20U
393#define ZXC_FILE_FLAG_RESERVED 0x10U
395#define ZXC_FILE_CHECKSUM_ALGO_MASK 0x0FU
399 "a file flag overlaps the checksum algorithm id");
400
406#define ZXC_DICT_VERSION 2
409#define ZXC_DICT_KGRAM_LEN ZXC_LZ_MIN_MATCH_LEN
411#define ZXC_DICT_SEGMENT_MAX 4096
413#define ZXC_DICT_HASH_BITS 16
415#define ZXC_DICT_MAX_SEGMENTS (1U << 16)
419#define ZXC_DICT_SAMPLE_TARGET (1U << 19)
421#define ZXC_DICT_HASH_SIZE (1U << ZXC_DICT_HASH_BITS)
423#define ZXC_DICT_HUF_TRAIN_BLOCK 4096U
426#define ZXC_DICT_HUF_SAMPLE_BUDGET (8U << 20)
427
429#define ZXC_BLOCK_HEADER_SIZE 8
431#define ZXC_BLOCK_CHECKSUM_SIZE 4
433#define ZXC_SPL_HEADER_BINARY_SIZE 12
435#define ZXC_PAK_HEADER_BINARY_SIZE 12
437#define ZXC_SPL_DESC_MAX_SIZE (2 * sizeof(uint32_t))
438
447#define ZXC_BLOCK_FORMAT_OVERHEAD 68
448static_assert(ZXC_BLOCK_FORMAT_OVERHEAD >=
450 "ZXC_BLOCK_FORMAT_OVERHEAD must cover sub-header, descriptors and slack");
451
453#define ZXC_CHECKSUM_RAPIDHASH 0
454
464#define ZXC_SEEK_GROUP 64U
466#define ZXC_SEEK_ANCHOR_SIZE 8U
468#define ZXC_SEEK_SIZE_ENTRY 4U
470#define ZXC_SEEK_GROUP_BYTES (ZXC_SEEK_ANCHOR_SIZE + ZXC_SEEK_GROUP * ZXC_SEEK_SIZE_ENTRY)
471
473static ZXC_ALWAYS_INLINE uint64_t zxc_seek_group_count(const uint64_t nblocks) {
474 return (nblocks + ZXC_SEEK_GROUP - 1) / ZXC_SEEK_GROUP;
475}
476
478static ZXC_ALWAYS_INLINE uint32_t zxc_seek_group_len(const uint64_t nblocks, const uint64_t g) {
479 const uint64_t left = nblocks - g * ZXC_SEEK_GROUP;
480 return left < ZXC_SEEK_GROUP ? (uint32_t)left : ZXC_SEEK_GROUP;
481}
482
484static ZXC_ALWAYS_INLINE uint64_t zxc_seek_table_bytes(const uint64_t nblocks) {
486}
487
490static ZXC_ALWAYS_INLINE uint32_t zxc_seek_size_field(const uint64_t table_bytes) {
491#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM64) || defined(_M_ARM64EC))
492 // MSVC 19.51 ARM64 /O2 sees the table size as 4U and compiles this fold into
493 // `ror w, #30` on the low half of u, dropping the high word: tables of 4 GiB
494 // and more get a wrong field. A volatile copy hides that shape. Once per table.
495 const volatile uint64_t t = table_bytes;
496 return (uint32_t)(t ^ (t >> 32));
497#else
498 return (uint32_t)(table_bytes ^ (table_bytes >> 32));
499#endif
500}
501 /* end of Seekable Format Constants */
503
508#define ZXC_TOKEN_LIT_BITS 4
510#define ZXC_TOKEN_ML_BITS 4
512#define ZXC_TOKEN_LL_MASK ((1U << ZXC_TOKEN_LIT_BITS) - 1)
514#define ZXC_TOKEN_ML_MASK ((1U << ZXC_TOKEN_ML_BITS) - 1)
515static_assert(ZXC_TOKEN_LIT_BITS == 4 && ZXC_TOKEN_ML_BITS == 4,
516 "the SPL decoder reads its tokens as two nibbles");
518
523#define ZXC_SEQ_LL_BITS 8
525#define ZXC_SEQ_ML_BITS 8
527#define ZXC_SEQ_OFF_BITS 16
529#define ZXC_SEQ_LL_MASK ((1U << ZXC_SEQ_LL_BITS) - 1)
531#define ZXC_SEQ_ML_MASK ((1U << ZXC_SEQ_ML_BITS) - 1)
533#define ZXC_SEQ_OFF_MASK ((1U << ZXC_SEQ_OFF_BITS) - 1)
535#define ZXC_SEQ_LL_SHIFT (ZXC_SEQ_ML_BITS + ZXC_SEQ_OFF_BITS)
537#define ZXC_SEQ_ML_SHIFT ZXC_SEQ_OFF_BITS
538static_assert(ZXC_SEQ_LL_BITS + ZXC_SEQ_ML_BITS + ZXC_SEQ_OFF_BITS == 32,
539 "a PAK sequence is one 32-bit word");
541
545#define ZXC_LIT_RLE_FLAG 0x80U
547#define ZXC_LIT_LEN_MASK (ZXC_LIT_RLE_FLAG - 1)
549#define ZXC_LIT_RUN_MAX (ZXC_LIT_LEN_MASK + 1U) /* 128 */
551#define ZXC_LIT_RLE_RUN_MIN 4U
553#define ZXC_LIT_RLE_RUN_MAX (ZXC_LIT_LEN_MASK + ZXC_LIT_RLE_RUN_MIN) /* 131 */
555
568#define ZXC_LZ_HASH_BITS 15
570#define ZXC_LZ_HASH_SIZE (1U << ZXC_LZ_HASH_BITS)
572#define ZXC_LZ_WINDOW_SIZE (1U << 16)
574#define ZXC_LZ_WINDOW_MASK (ZXC_LZ_WINDOW_SIZE - 1U)
576#define ZXC_LZ_MIN_MATCH_LEN 5
585#define ZXC_MAX_VARINT_VALUE ((uint32_t)(ZXC_BLOCK_SIZE_MAX - 1U))
587#define ZXC_VARINT_INVALID (2U * ZXC_BLOCK_SIZE_MAX)
590#define ZXC_VARINT_1B_LIMIT (1U << 7)
591#define ZXC_VARINT_2B_LIMIT (1U << 14)
592#define ZXC_VARINT_3B_LIMIT (1U << 21)
594static_assert(ZXC_MAX_VARINT_VALUE < ZXC_VARINT_3B_LIMIT, "varint values must fit the 3-byte form");
598 "ZXC_BLOCK_SIZE_DEFAULT must be a power of two within the block size range");
599static_assert((ZXC_LZ_WINDOW_SIZE & ZXC_LZ_WINDOW_MASK) == 0,
600 "ZXC_LZ_WINDOW_SIZE must be a power of two (ring mask)");
601static_assert(ZXC_LZ_WINDOW_SIZE <= (1U << ZXC_SEQ_OFF_BITS),
602 "chain_table holds window positions in 16 bits");
603
620static ZXC_ALWAYS_INLINE uint32_t zxc_read_varint(const uint8_t** ptr, const uint8_t* end) {
621 const uint8_t* p = *ptr;
622 if (UNLIKELY(p >= end)) return ZXC_VARINT_INVALID;
623
624 const uint32_t b0 = p[0];
625
626 // 1 Byte: 0xxxxxxx (7 bits) -> val < 128 (2^7)
627 if (LIKELY(b0 < 0x80)) {
628 *ptr = p + 1;
629 return b0;
630 }
631
632 // 2 Bytes: 10xxxxxx xxxxxxxx (14 bits) -> val < 16384 (2^14)
633 if (LIKELY(b0 < 0xC0)) {
634 if (UNLIKELY(p + 1 >= end)) {
635 *ptr = end;
636 return ZXC_VARINT_INVALID;
637 }
638 *ptr = p + 2;
639 return (b0 & 0x3F) | ((uint32_t)p[1] << 6);
640 }
641
642 // 3 Bytes: 110xxxxx xxxxxxxx xxxxxxxx (21 bits) -> val < 2^21. The longest
643 // a legitimate varint can be: values are (ll - MASK) or (ml - MASK), always
644 // strictly below block_size_max = 2^21.
645 if (LIKELY(b0 < 0xE0)) {
646 if (UNLIKELY(p + 2 >= end)) {
647 *ptr = end;
648 return ZXC_VARINT_INVALID;
649 }
650 *ptr = p + 3;
651 return (b0 & 0x1F) | ((uint32_t)p[1] << 5) | ((uint32_t)p[2] << 13);
652 }
653
654 // extra encoding: out-of-spec for the current format, reject.
655 *ptr = end;
656 return ZXC_VARINT_INVALID;
657}
658
664#define ZXC_SPL_MAX_INLINE_OUT_PER_SEQ ((ZXC_TOKEN_LL_MASK - 1U) + ZXC_SPL_MAX_INLINE_ML) /* 33 */
667#define ZXC_SPL_INLINE_ML_CODE (ZXC_TOKEN_ML_MASK - 1U) /* 14 */
673#define ZXC_SPL_MAX_INLINE_ML (ZXC_SPL_INLINE_ML_CODE + ZXC_LZ_MIN_MATCH_LEN) /* 19 */
674#define ZXC_PAK_MAX_INLINE_OUT_PER_SEQ \
675 ((ZXC_SEQ_LL_MASK - 1U) + (ZXC_SEQ_ML_MASK - 1U) + ZXC_LZ_MIN_MATCH_LEN) /* 513 */
677#define ZXC_LZ_OFFSET_BIAS 1
679#define ZXC_LZ_MAX_DIST (ZXC_LZ_WINDOW_SIZE - 1)
680static_assert(ZXC_SPL_MAX_INLINE_ML <= ZXC_PAD_SIZE, "an inline SPL match is one 32-byte store");
682 "a biased offset must fit the 16-bit wire field");
683static_assert(ZXC_DECOMPRESS_TAIL_PAD == 2084,
684 "ZXC_DECOMPRESS_TAIL_PAD feeds the public bounds: change it on purpose only");
686 "ZXC_DECOMPRESS_TAIL_PAD must also hold the SPL 4x loop margin");
688 "an invalid varint must exceed every output capacity");
689static_assert(ZXC_DICT_SIZE_MAX <= ZXC_LZ_MAX_DIST, "a dictionary must stay within offset reach");
690
698#define ZXC_LZ_MINDIST 32
699
705#define ZXC_LZ_MINDIST_PROBE_PER_KB 1024
706#define ZXC_LZ_MINDIST_PROBE_MIN 16
707#define ZXC_LZ_MINDIST_PROBE_MAX 64
708
715#define ZXC_LZ_MINDIST_MAX_SHORT_PCT 20
718#define ZXC_LZ_SEARCH_MARGIN (sizeof(uint64_t))
720
727#define ZXC_OPT_MATCH_COST_BASE ((uint32_t)(3U * CHAR_BIT))
730#define ZXC_OPT_LONG_MATCH_SKIP ((size_t)256)
731static_assert(ZXC_OPT_LONG_MATCH_SKIP <=
732 ZXC_LZ_MIN_MATCH_LEN + ZXC_TOKEN_ML_MASK + ZXC_VARINT_2B_LIMIT,
733 "covered positions relax only the first two match cost classes");
738#define ZXC_OPT_LIT_SAMPLE_MIN 1024
740#define ZXC_OPT_LIT_SAMPLE_TARGET 4096
741
743
750#define ZXC_HASH_GOLDEN64 0x9E3779B97F4A7C15ULL
752#define ZXC_HASH_XORSHIFT64 0x2545F4914F6CDD1DULL
754#define ZXC_HASH_MULT32 0x2D35182DU
756#define ZXC_HASH_MULT64 0xD2D84A61D2D84A61ULL
758
779#define ZXC_HUF_MAX_CODE_LEN_ULTRA 11
784#define ZXC_HUF_MAX_CODE_LEN_DENSITY 8
786#define ZXC_HUF_NUM_SYMBOLS 256
788 "the decoder accepts code lengths up to ZXC_HUF_MAX_CODE_LEN_ULTRA only");
790 "code lengths are packed one nibble per symbol");
791
793#define ZXC_PIVCO_MAX_NODES (2 * ZXC_HUF_NUM_SYMBOLS - 1)
796#define ZXC_PIVCO_NODE_SLOTS (ZXC_PIVCO_MAX_NODES + 1)
800#define ZXC_PIVCO_UNPACK_FLAT_SIMD_MAX 6
801
803#define ZXC_PIVCO_COVERED 0xFFU
804
828
842
845#define ZXC_RLE_MARGIN_SHIFT 5
849#define ZXC_HUF_MARGIN_SHIFT 5
850
866#define ZXC_HUF_NUDGE_LAMBDA_Q8 26
869#define ZXC_HUF_NUDGE_BITS_PERMIL 1015
872#define ZXC_HUF_NUDGE_MERGE_Q8 230
877#define ZXC_HUF_NUDGE_DEEP_FLAT_PENALTY 24
881#define ZXC_HUF_NUDGE_LEVEL_COST 64
883
903#define ZXC_SS_TAX(n, prem_q8) (((size_t)(n) * (size_t)(prem_q8)) >> 8)
918static inline int zxc_ss_prem_rle_q8(const int level) {
919 return (level >= ZXC_LEVEL_DENSITY) ? 1 : (256 >> ZXC_RLE_MARGIN_SHIFT);
920}
921
937static inline int zxc_ss_prem_huf_q8(const int level) {
938 return (level >= ZXC_LEVEL_DENSITY) ? 4 : (256 >> ZXC_HUF_MARGIN_SHIFT);
939}
940
952#define ZXC_HUF_MIN_LITERALS 139
954
960typedef struct {
961 int n_threads;
962 int level;
963 size_t block_size;
964 int checksum_enabled;
965 int seekable;
966 const void* dict;
967 size_t dict_size;
968 const void* dict_huf;
969 zxc_progress_callback_t progress_cb;
970 void* user_data;
972
974typedef struct {
975 int n_threads;
976 int checksum_enabled;
977 const void* dict;
978 size_t dict_size;
979 const void* dict_huf;
980 zxc_progress_callback_t progress_cb;
981 void* user_data;
983
989#define ZXC_OPTS_DICT_SIZE(o) (((o) && (o)->dict) ? (o)->dict_size : (size_t)0)
991#define ZXC_OPTS_DICT_HUF(o) \
992 (((o) && (o)->dict && (o)->dict_size > 0) ? (const uint8_t*)(o)->dict_huf : NULL)
993
994#define ZXC_OPTS_LEVEL(o, dflt) (((o) && (o)->level != 0) ? (o)->level : (dflt))
996#define ZXC_OPTS_BLOCK_SIZE(o, dflt) (((o) && (o)->block_size > 0) ? (o)->block_size : (dflt))
1008#define ZXC_SPL_MATCH_SPLIT_CTX_BITS 8
1011#define ZXC_SPL_MATCH_SPLIT_MIN_MISPREDICT_PCT 80
1015static_assert(ZXC_SPL_MATCH_SPLIT_CTX_BITS <= CHAR_BIT,
1016 "a context is recorded in one byte of buf_split");
1018
1024static inline int zxc_huf_enc_max_code_len(const int level) {
1026}
1027
1034typedef struct {
1035 uint32_t weight;
1036 int16_t left;
1037 int16_t right;
1038 int16_t sym;
1040
1042typedef struct {
1043 int8_t lvl;
1044 int16_t idx;
1046
1048typedef struct {
1049 uint32_t w;
1050 int16_t sym;
1052
1055#define ZXC_HUF_PM_LEVEL_BOUND (2 * ZXC_HUF_NUM_SYMBOLS)
1056
1061#define ZXC_HUF_BUILD_SCRATCH_SIZE \
1062 ((size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * (size_t)ZXC_HUF_PM_LEVEL_BOUND * \
1063 sizeof(zxc_huf_pm_item_t) + \
1064 8U + (size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * sizeof(int) + 8U + \
1065 (size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * (size_t)ZXC_HUF_PM_LEVEL_BOUND * \
1066 sizeof(zxc_huf_pm_frame_t))
1067
1070#define ZXC_HUF_NUDGE_DP_M 64
1071
1088
1090#define ZXC_HUF_NUDGE_SCRATCH_OFF ZXC_ALIGN_CL(ZXC_HUF_BUILD_SCRATCH_SIZE)
1092#define ZXC_HUF_NUDGE_SCRATCH_SIZE (ZXC_HUF_NUDGE_SCRATCH_OFF + sizeof(zxc_huf_nudge_ws_t))
1093
1100static ZXC_ALWAYS_INLINE void zxc_opt_dp_sizes(const size_t chunk_size, size_t* RESTRICT sz_dp,
1101 size_t* RESTRICT sz_pl, size_t* RESTRICT sz_po,
1102 size_t* RESTRICT sz_bm) {
1103 *sz_dp = ZXC_ALIGN_CL((chunk_size + 1) * sizeof(uint32_t));
1104 *sz_pl = ZXC_ALIGN_CL((chunk_size + 1) * sizeof(uint16_t));
1105 *sz_po = ZXC_ALIGN_CL((chunk_size + 1) * sizeof(uint16_t));
1106 *sz_bm = ZXC_ALIGN_CL(ZXC_BITMAP_WORDS(chunk_size + 1) * sizeof(uint64_t));
1107}
1108
1112
1118static ZXC_ALWAYS_INLINE uint32_t zxc_log2_u32(const uint32_t v) {
1119#ifdef _MSC_VER
1120 unsigned long index;
1121 return (v == 0) ? 0 : (_BitScanReverse(&index, v) ? index : 0);
1122#else
1123 return (v == 0) ? 0 : (uint32_t)(31 - __builtin_clz(v));
1124#endif
1125}
1126
1132static ZXC_ALWAYS_INLINE size_t zxc_block_size_ceil(const size_t v) {
1133 uint64_t x = (uint64_t)v - 1;
1134 x |= x >> 1;
1135 x |= x >> 2;
1136 x |= x >> 4;
1137 x |= x >> 8;
1138 x |= x >> 16;
1139 x |= x >> 32;
1140 x++;
1141 const size_t bs = (size_t)x;
1142 return (bs < ZXC_BLOCK_SIZE_MIN) ? ZXC_BLOCK_SIZE_MIN : bs;
1143}
1144
1151static ZXC_ALWAYS_INLINE int zxc_validate_block_size(const size_t bs) {
1152 return bs >= ZXC_BLOCK_SIZE_MIN && bs <= ZXC_BLOCK_SIZE_MAX && (bs & (bs - 1)) == 0;
1153}
1154
1155 /* end of File Format Constants */
1157
1167typedef struct {
1171
1176
1182
1187
1192
1195 uint32_t step_base;
1196
1200 uint32_t step_shift;
1201
1205 uint32_t min_offset;
1206
1210 uint8_t split_max;
1212
1223 // The distance floor stops at level 5: the slow levels keep every distance.
1224 // Match splitting at levels 3-5 only: 1-2 are PAK, 6-7 keep every escape.
1225 // search_depth, sufficient_len, use_lazy, lazy_attempts, lazy_len_threshold, step_base,
1226 // step_shift, min_offset, split_max
1227 static const zxc_lz77_params_t table[7] = {
1228 {3, 16, 0, 0, 0, 4, 4, ZXC_LZ_MINDIST, 0}, // fallback
1229 {3, 16, 0, 0, 0, 4, 4, ZXC_LZ_MINDIST, 0}, // level 1
1230 {3, 18, 0, 0, 0, 3, 6, ZXC_LZ_MINDIST, 0}, // level 2
1231 {3, 16, 1, 4, 128, 1, 4, ZXC_LZ_MINDIST, 33}, // level 3
1232 {3, 18, 1, 4, 128, 1, 5, ZXC_LZ_MINDIST, 24}, // level 4
1233 {64, 256, 1, 16, 128, 1, 8, ZXC_LZ_MINDIST, 23}, // level 5
1234 {64, 256, 0, 0, 0, 1, 8, 1, 0} // level 6
1235 };
1236 return (level >= ZXC_LEVEL_ULTRA)
1237 ? (zxc_lz77_params_t){128, 256, 0, 0, 0, 1, 8, 1, 0}
1238 : table[level < ZXC_LEVEL_FASTEST ? ZXC_LEVEL_FASTEST : level];
1239}
1240
1257typedef enum {
1258 ZXC_BLOCK_RAW = 0,
1259 ZXC_BLOCK_SPL = 1,
1260 ZXC_BLOCK_PAK = 2,
1261 ZXC_BLOCK_SEK = 254,
1262 ZXC_BLOCK_EOF = 255
1264
1283typedef enum {
1284 ZXC_SECTION_ENCODING_RAW = 0,
1285 ZXC_SECTION_ENCODING_RLE = 1,
1286 ZXC_SECTION_ENCODING_HUFFMAN = 2,
1287 ZXC_SECTION_ENCODING_HUFFMAN_DICT = 3
1289
1313typedef struct {
1314 uint32_t n_sequences; // Number of sequences
1315 uint32_t n_literals; // Number of literals
1316 uint8_t enc_lit; // Literal stream encoding
1317 uint8_t enc_tok; // Token section encoding (SPL only)
1318 uint8_t enc_mlen; // Reserved (see above)
1319 uint8_t enc_off; // Offset stream width (SPL only; ignored on decode in PAK)
1321
1328
1338static ZXC_ALWAYS_INLINE uint16_t zxc_le16(const void* p) {
1339 uint16_t v;
1340 ZXC_MEMCPY(&v, p, sizeof(v));
1341#ifdef ZXC_BIG_ENDIAN
1342 return ZXC_BSWAP16(v);
1343#else
1344 return v;
1345#endif
1346}
1347
1357static ZXC_ALWAYS_INLINE uint32_t zxc_le32(const void* p) {
1358 uint32_t v;
1359 ZXC_MEMCPY(&v, p, sizeof(v));
1360#ifdef ZXC_BIG_ENDIAN
1361 return ZXC_BSWAP32(v);
1362#else
1363 return v;
1364#endif
1365}
1366
1379static ZXC_ALWAYS_INLINE int zxc_block_is_short_dist_bound(const uint8_t* const blk,
1380 const size_t size) {
1381 const size_t d_max = ZXC_LZ_MINDIST;
1382 // Too small to sample, and too small to gain: keep every distance.
1383 if (size < d_max + sizeof(uint32_t)) return 1;
1384
1385 size_t want = size / ZXC_LZ_MINDIST_PROBE_PER_KB;
1386 if (want < ZXC_LZ_MINDIST_PROBE_MIN) want = ZXC_LZ_MINDIST_PROBE_MIN;
1387 if (want > ZXC_LZ_MINDIST_PROBE_MAX) want = ZXC_LZ_MINDIST_PROBE_MAX;
1388 size_t stride = size / want;
1389 if (stride < d_max) stride = d_max;
1390
1391 const size_t planned = (size - sizeof(uint32_t) - d_max) / stride + 1;
1392 const size_t bar = (size_t)ZXC_LZ_MINDIST_MAX_SHORT_PCT * planned;
1393
1394 size_t samples = 0;
1395 size_t hits = 0;
1396 for (size_t i = d_max; i + sizeof(uint32_t) <= size; i += stride) {
1397 const uint32_t cur = zxc_le32(blk + i);
1398 samples++;
1399 for (size_t d = 1; d < d_max; d++) {
1400 if (zxc_le32(blk + i - d) == cur) {
1401 hits++;
1402 break;
1403 }
1404 }
1405 if (hits * 100U > bar) return 1; // can only rise
1406 if ((hits + (planned - samples)) * 100U <= bar) return 0; // out of reach
1407 }
1408 return hits * 100U > bar;
1409}
1410
1420static ZXC_ALWAYS_INLINE uint64_t zxc_le64(const void* p) {
1421 uint64_t v;
1422 ZXC_MEMCPY(&v, p, sizeof(v));
1423#ifdef ZXC_BIG_ENDIAN
1424 return ZXC_BSWAP64(v);
1425#else
1426 return v;
1427#endif
1428}
1429
1439static ZXC_ALWAYS_INLINE void zxc_store_le16(void* p, const uint16_t v) {
1440#ifdef ZXC_BIG_ENDIAN
1441 const uint16_t s = ZXC_BSWAP16(v);
1442 ZXC_MEMCPY(p, &s, sizeof(s));
1443#else
1444 ZXC_MEMCPY(p, &v, sizeof(v));
1445#endif
1446}
1447
1457static ZXC_ALWAYS_INLINE void zxc_store_le32(void* p, const uint32_t v) {
1458#ifdef ZXC_BIG_ENDIAN
1459 const uint32_t s = ZXC_BSWAP32(v);
1460 ZXC_MEMCPY(p, &s, sizeof(s));
1461#else
1462 ZXC_MEMCPY(p, &v, sizeof(v));
1463#endif
1464}
1465
1475static ZXC_ALWAYS_INLINE void zxc_store_le64(void* p, const uint64_t v) {
1476#ifdef ZXC_BIG_ENDIAN
1477 const uint64_t s = ZXC_BSWAP64(v);
1478 ZXC_MEMCPY(p, &s, sizeof(s));
1479#else
1480 ZXC_MEMCPY(p, &v, sizeof(v));
1481#endif
1482}
1483
1496static ZXC_ALWAYS_INLINE uint8_t zxc_hash8(const uint8_t* p) {
1497 const uint64_t h = (zxc_le64(p) ^ ZXC_HASH_GOLDEN64) * ZXC_HASH_GOLDEN64;
1498
1499 return (uint8_t)(h >> 56);
1500}
1501
1509static ZXC_ALWAYS_INLINE int zxc_block_header_ok(const uint8_t* p) {
1510 uint8_t temp[ZXC_BLOCK_HEADER_SIZE];
1511 ZXC_MEMCPY(temp, p, ZXC_BLOCK_HEADER_SIZE);
1512 temp[7] = 0; // The checksum covers the header with its own byte zeroed
1513 return p[7] == zxc_hash8(temp) && (p[1] | p[2]) == 0;
1514}
1515
1529static ZXC_ALWAYS_INLINE uint16_t zxc_hash16(const uint8_t* p) {
1530 const uint64_t h1 = (zxc_le64(p) ^ ZXC_HASH_MULT64) * ZXC_HASH_MULT64;
1531
1532 return (uint16_t)(((h1 + zxc_le64(p + 8) + ZXC_HASH_GOLDEN64) * ZXC_HASH_GOLDEN64) >> 48);
1533}
1534
1541 zxc_store_le16(h + 14, 0);
1542 zxc_store_le16(h + 14, zxc_hash16(h));
1543}
1544
1554static ZXC_ALWAYS_INLINE void zxc_copy16(void* dst, const void* src) {
1555#if defined(ZXC_USE_AVX2) || defined(ZXC_USE_AVX512) || defined(ZXC_USE_SSE2)
1556 // x86 SSE2/AVX2/AVX512: Single 128-bit unaligned load/store
1557 _mm_storeu_si128((__m128i*)dst, _mm_loadu_si128((const __m128i*)src));
1558#elif defined(ZXC_USE_NEON64) || defined(ZXC_USE_NEON32)
1559 vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));
1560#else
1561 ZXC_MEMCPY(dst, src, 16);
1562#endif
1563}
1564
1573static ZXC_ALWAYS_INLINE void zxc_copy32(void* dst, const void* src) {
1574#if defined(ZXC_USE_AVX2) || defined(ZXC_USE_AVX512)
1575 // AVX2/AVX512: Single 256-bit (32 byte) unaligned load/store
1576 _mm256_storeu_si256((__m256i*)dst, _mm256_loadu_si256((const __m256i*)src));
1577#elif defined(ZXC_USE_SSE2)
1578 const __m128i a = _mm_loadu_si128((const __m128i*)src);
1579 const __m128i b = _mm_loadu_si128((const __m128i*)((const uint8_t*)src + 16));
1580 _mm_storeu_si128((__m128i*)dst, a);
1581 _mm_storeu_si128((__m128i*)((uint8_t*)dst + 16), b);
1582#elif defined(ZXC_USE_NEON64) || defined(ZXC_USE_NEON32)
1583 const uint8x16_t a = vld1q_u8((const uint8_t*)src);
1584 const uint8x16_t b = vld1q_u8((const uint8_t*)src + 16);
1585 vst1q_u8((uint8_t*)dst, a);
1586 vst1q_u8((uint8_t*)dst + 16, b);
1587#else
1588 ZXC_MEMCPY(dst, src, 32);
1589#endif
1590}
1591
1592// Portable De Bruijn ctz for compilers without a bit-scan builtin; x must be
1593// non-zero. Always compiled so the unit tests can check every bit position:
1594// no CI compiler reaches the #else branches that use them.
1595static ZXC_ALWAYS_INLINE int zxc_ctz32_debruijn(const uint32_t x) {
1596 static const int DeBruijn32[32] = {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20,
1597 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19,
1598 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
1599 return DeBruijn32[((uint32_t)((x & (0U - x)) * 0x077CB531U)) >> 27];
1600}
1601
1602static ZXC_ALWAYS_INLINE int zxc_ctz64_debruijn(const uint64_t x) {
1603 // Table and multiplier must come from the same sequence (0x03F79D71B4CB0A89).
1604 static const int Debruijn64[64] = {
1605 0, 1, 48, 2, 57, 49, 28, 3, 61, 58, 50, 42, 38, 29, 17, 4, 62, 55, 59, 36, 53, 51,
1606 43, 22, 45, 39, 33, 30, 24, 18, 12, 5, 63, 47, 56, 27, 60, 41, 37, 16, 54, 35, 52, 21,
1607 44, 32, 23, 11, 46, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6};
1608 return Debruijn64[((x & (0ULL - x)) * 0x03F79D71B4CB0A89ULL) >> 58];
1609}
1610
1620static ZXC_ALWAYS_INLINE int zxc_ctz32(const uint32_t x) {
1621 if (x == 0) return 32;
1622#if defined(__GNUC__) || defined(__clang__)
1623 return __builtin_ctz(x);
1624#elif defined(_MSC_VER)
1625 unsigned long r;
1626 _BitScanForward(&r, x);
1627 return (int)r;
1628#else
1629 return zxc_ctz32_debruijn(x);
1630#endif
1631}
1632
1642static ZXC_ALWAYS_INLINE int zxc_ctz64(const uint64_t x) {
1643 if (x == 0) return 64;
1644#if defined(__GNUC__) || defined(__clang__)
1645 return __builtin_ctzll(x);
1646#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
1647 unsigned long r;
1648 _BitScanForward64(&r, x);
1649 return (int)r;
1650#elif defined(_MSC_VER)
1651 // Use two 32-bit scans to avoid fragile 64-bit De Bruijn multiplication.
1652 unsigned long r;
1653 const uint32_t lo = (uint32_t)x;
1654 if (_BitScanForward(&r, lo)) return (int)r;
1655 _BitScanForward(&r, (uint32_t)(x >> 32));
1656 return 32 + (int)r;
1657#else
1658 return zxc_ctz64_debruijn(x);
1659#endif
1660}
1661
1664static ZXC_ALWAYS_INLINE uint64_t zxc_seek_block_count(const uint64_t total_decomp,
1665 const size_t block_size) {
1666 // A shift, block_size being a header power of two: no 64-bit division on 32-bit
1667 // hosts. Not (total + bs - 1) >> s, which wraps near 2^64 on a forged footer.
1668 if (UNLIKELY(!block_size)) return 0;
1669 const int s = zxc_ctz32((uint32_t)block_size);
1670 return (total_decomp >> s) + ((total_decomp & (block_size - 1)) != 0);
1671}
1672
1673// ============================================================================
1674// COMPRESSION CONTEXT & STRUCTS
1675// ============================================================================
1676
1677// INTERNAL API
1678// ------------
1679
1696static ZXC_ALWAYS_INLINE uint32_t zxc_checksum(const void* RESTRICT input, const size_t len,
1697 const uint64_t seed, const uint8_t hash_method) {
1698 (void)hash_method; /* single algorithm for now; extend when adding more */
1699 const uint64_t hash = rapidhash_withSeed(input, len, seed);
1700
1701 return (uint32_t)(hash ^ (hash >> (sizeof(uint32_t) * CHAR_BIT)));
1702}
1703
1716static ZXC_ALWAYS_INLINE uint64_t zxc_digest_combine(const uint64_t acc,
1717 const uint32_t block_checksum) {
1718 const uint64_t a = acc ^ ((uint64_t)block_checksum + 1U) * ZXC_HASH_GOLDEN64;
1719 const uint64_t b = ZXC_HASH_XORSHIFT64;
1720#if defined(__SIZEOF_INT128__)
1721 const __uint128_t r = (__uint128_t)a * b;
1722 return (uint64_t)r ^ (uint64_t)(r >> 64);
1723#else
1724 const uint64_t alo = (uint32_t)a, ahi = a >> 32, blo = (uint32_t)b, bhi = b >> 32;
1725 const uint64_t lolo = alo * blo, lohi = alo * bhi, hilo = ahi * blo, hihi = ahi * bhi;
1726 const uint64_t cross = (lolo >> 32) + (uint32_t)lohi + (uint32_t)hilo;
1727 const uint64_t hi = hihi + (lohi >> 32) + (hilo >> 32) + (cross >> 32);
1728 const uint64_t lo = (cross << 32) | (uint32_t)lolo;
1729 return lo ^ hi;
1730#endif
1731}
1732
1747int zxc_write_spl_header_and_desc(uint8_t* RESTRICT dst, const size_t rem,
1748 const zxc_gnr_header_t* RESTRICT gh, const uint32_t lit_comp,
1749 const uint32_t tok_comp);
1750
1764int zxc_read_spl_header_and_desc(const uint8_t* RESTRICT src, const size_t len,
1765 zxc_gnr_header_t* RESTRICT gh, uint32_t* RESTRICT lit_comp,
1766 uint32_t* RESTRICT tok_comp);
1767
1776int zxc_write_pak_header(uint8_t* RESTRICT dst, const size_t rem,
1777 const zxc_gnr_header_t* RESTRICT gh);
1778
1787int zxc_read_pak_header(const uint8_t* RESTRICT src, const size_t len,
1788 zxc_gnr_header_t* RESTRICT gh);
1789
1790// ============================================================================
1791// Huffman codec for the SPL literal stream (level >= 6).
1792//
1793// On-disk layout, decoder geometry and tunables: see
1794// @ref ZXC_HUF_MAX_CODE_LEN_ULTRA and the surrounding "Huffman Codec Constants"
1795// group above.
1796// ============================================================================
1797
1816int zxc_huf_build_code_lengths(const uint32_t* RESTRICT freq, uint8_t* RESTRICT code_len,
1817 void* RESTRICT scratch, int max_code_len);
1818
1850int zxc_huf_nudge_code_lengths(const uint32_t* RESTRICT freq, uint8_t* RESTRICT code_len,
1851 void* RESTRICT scratch, size_t scratch_cap, int max_code_len);
1852
1860void zxc_huf_nudge_cost(const uint8_t* RESTRICT code_len, const uint32_t* RESTRICT freq,
1861 uint64_t* RESTRICT bits, uint64_t* RESTRICT touches);
1862
1873void zxc_huf_pack_lengths(const uint8_t* RESTRICT code_len, uint8_t* RESTRICT out);
1874
1887int zxc_huf_unpack_lengths(const uint8_t* RESTRICT in, uint8_t* RESTRICT code_len);
1888
1889// --------------------------------------------------------------------------
1890// PivCo-Huffman section codec (enc 2/3)
1891//
1892// Layout from PivCo-Huffman by Marcin Zukowski
1893// (https://github.com/MarcinZukowski/pivco-huffman); implemented
1894// independently here. See zxc_huffman.c for the codec.
1895//
1896// Same code bits as canonical Huffman, reordered by tree LEVEL: for each
1897// internal node in BFS order, its branch bits (one per symbol routed through
1898// it, LSB-first, byte-aligned). No size fields - the decoder derives every run
1899// length from the root count and popcounts. Decoding is bottom-up level merges,
1900// shuffle-parallel and gather-free.
1901// --------------------------------------------------------------------------
1902
1904#define ZXC_PIVCO_SCRATCH_PAD 32
1905
1908size_t zxc_huf_calc_size(const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1909 int with_header);
1910
1912int zxc_huf_encode_section(const uint8_t* RESTRICT literals, size_t n_literals,
1913 const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1914 uint8_t* RESTRICT dst, size_t dst_cap);
1915
1918int zxc_huf_dict_tree_build(const uint8_t* RESTRICT packed_lengths, zxc_pivco_tree_t* RESTRICT tree,
1919 uint32_t* RESTRICT codes, uint8_t* RESTRICT code_len);
1920
1922size_t zxc_huf_calc_size_dict(const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1923 const zxc_pivco_tree_t* RESTRICT tree);
1924
1926int zxc_huf_encode_section_dict(const uint8_t* RESTRICT literals, size_t n_literals,
1927 const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1928 const zxc_pivco_tree_t* RESTRICT tree,
1929 const uint32_t* RESTRICT codes, uint8_t* RESTRICT dst,
1930 size_t dst_cap);
1931
1934int zxc_huf_decode_section(const uint8_t* RESTRICT payload, size_t payload_size,
1935 uint8_t* RESTRICT dst, size_t n, uint8_t* RESTRICT scratch);
1936
1938int zxc_huf_decode_section_dict(const uint8_t* RESTRICT payload, size_t payload_size,
1939 uint8_t* RESTRICT dst, size_t n,
1940 const zxc_pivco_tree_t* RESTRICT tree, uint8_t* RESTRICT scratch);
1941
1942// ---------------------------------------------------------------------------
1943// Compression / decompression context.
1944//
1945// The context owns the working buffers (hash table, sequence buffers, scratch)
1946// that encoder and decoder reuse across blocks. It stays private - the public
1947// APIs already wrap it opaquely - so the layout can evolve (cache-line
1948// placement, extra scratch arenas) without breaking the ABI.
1949// ---------------------------------------------------------------------------
1950
1967typedef struct {
1968 // Hot zone: random access / high frequency.
1969 // Kept at the start to ensure they reside in the first cache line (64 bytes).
1970 uint32_t* hash_table;
1971 uint8_t* hash_tags;
1972 uint16_t* chain_table;
1974 uint32_t epoch;
1975
1976 // Warm zone: sequential access per sequence.
1977 uint32_t* buf_sequences;
1978 uint8_t* buf_tokens;
1979 uint16_t* buf_offsets;
1980 uint8_t* buf_extras;
1981 uint8_t* buf_split;
1983 uint8_t* literals;
1984
1985 // Cold zone: configuration / scratch / resizeable.
1986 uint8_t* lit_buffer;
1988 uint8_t* work_buf;
1990 uint8_t* tok_buffer;
1995 uint8_t* pivco_scratch;
2001 uint8_t* opt_scratch;
2008 size_t dict_size;
2009 uint8_t* dict_buffer;
2017 uint32_t* lit_freq_acc;
2020
2021 // Block-size derived parameters (computed once at init).
2022 size_t chunk_size;
2023 uint32_t offset_bits;
2024 uint32_t offset_mask;
2025 uint32_t max_epoch;
2026} zxc_cctx_t;
2027
2047int zxc_cctx_init(zxc_cctx_t* ctx, const size_t chunk_size, const int mode, const int level,
2048 const int checksum_enabled, const size_t dict_size);
2049
2061int zxc_cctx_attach_dict_huf(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT lengths);
2062
2078size_t zxc_cctx_compute_workspace_size(const size_t chunk_size, const int mode, const int level,
2079 const size_t dict_size);
2080
2113int zxc_cctx_init_in_workspace(zxc_cctx_t* RESTRICT ctx, void* RESTRICT workspace,
2114 const size_t workspace_size, const size_t chunk_size, const int mode,
2115 const int level, const int checksum_enabled, const size_t dict_size,
2116 const int defer_entropy_scratch);
2117
2129
2138void zxc_cctx_free(zxc_cctx_t* ctx);
2139
2155int zxc_decompress_chunk_wrapper(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
2156 const size_t src_sz, uint8_t* RESTRICT dst, const size_t dst_cap,
2157 const uint64_t block_index);
2158int zxc_decompress_chunk_wrapper_dict(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
2159 const size_t src_sz, uint8_t* RESTRICT dst,
2160 const size_t dst_cap, const uint64_t block_index);
2162int zxc_decompress_chunk_wrapper_safe(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
2163 const size_t src_sz, uint8_t* RESTRICT dst,
2164 const size_t dst_cap, const uint64_t block_index);
2165
2180int zxc_compress_chunk_wrapper(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
2181 const size_t src_sz, uint8_t* RESTRICT dst, const size_t dst_cap,
2182 const uint64_t block_index);
2183
2185int64_t zxc_compress_block_at(zxc_cctx* cctx, const void* RESTRICT src, size_t src_size,
2186 void* RESTRICT dst, size_t dst_capacity, const zxc_cparams_t* opts,
2187 uint64_t block_index);
2188
2190const zxc_cparams_t* zxc_cctx_params(const zxc_cctx* cctx);
2191const zxc_dparams_t* zxc_dctx_params(const zxc_dctx* dctx);
2192
2193// ---------------------------------------------------------------------------
2194// Internal frame primitives.
2195//
2196// Read/write the ZXC file header, block header and footer. Kept internal:
2197// exposing them would freeze on-disk details (block_flags layout, footer
2198// composition) that stay free to evolve until the format is declared stable.
2199// ---------------------------------------------------------------------------
2200
2207typedef struct {
2208 uint8_t block_type;
2209 uint8_t block_flags;
2210 uint8_t reserved;
2212 uint32_t comp_size;
2214
2232int zxc_write_file_header(uint8_t* RESTRICT dst, const size_t dst_capacity, const size_t chunk_size,
2233 const int has_checksum, const int has_dict, const uint32_t dict_id,
2234 const int has_seek);
2235
2259int zxc_read_file_header(const uint8_t* RESTRICT src, const size_t src_size, size_t* out_block_size,
2260 int* out_has_checksum, int* out_has_dict, uint32_t* out_dict_id,
2261 int* out_has_seek);
2262
2265static inline int zxc_short_input_verdict(const uint8_t* p, const size_t n) {
2266 size_t chunk = 0;
2268 &chunk, NULL, NULL, NULL, NULL);
2269 return rc != ZXC_OK ? rc : ZXC_ERROR_SRC_TOO_SMALL;
2270}
2271
2272// ---------------------------------------------------------------------------
2273// Container scan: frames back to back, measured without decoding (FORMAT.md,
2274// Sec 2.1).
2275// ---------------------------------------------------------------------------
2276
2282typedef struct zxc_scan_src_s {
2285 int (*read_at)(const struct zxc_scan_src_s* src, uint64_t off, void* dst, size_t len);
2286 const uint8_t* data;
2287 void* ctx;
2288 uint64_t size;
2290
2292static ZXC_ALWAYS_INLINE zxc_scan_src_t zxc_scan_src_mem(const uint8_t* data, const size_t size) {
2293 zxc_scan_src_t src = {NULL, data, NULL, (uint64_t)size};
2294 return src;
2295}
2296
2298typedef struct {
2299 uint64_t dsize;
2300 uint64_t frames;
2303
2314int zxc_container_next(const zxc_scan_src_t* src, uint64_t pos);
2315
2328int zxc_scan_frame(const zxc_scan_src_t* src, uint64_t end, uint64_t* start, zxc_frame_info_t* info,
2329 size_t* footer_len, int* has_dict);
2330
2336int zxc_scan_whole_frame(const zxc_scan_src_t* src, zxc_frame_info_t* info, size_t* footer_len);
2337
2348int zxc_scan_container(const zxc_scan_src_t* src, size_t req_chunk, zxc_container_info_t* info);
2349
2364int zxc_write_block_header(uint8_t* RESTRICT dst, const size_t dst_capacity,
2365 const zxc_block_header_t* bh);
2366
2382int zxc_read_block_header(const uint8_t* RESTRICT src, const size_t src_size,
2383 zxc_block_header_t* bh);
2384
2394
2396static ZXC_ALWAYS_INLINE size_t zxc_uint_bytes(const uint64_t v) {
2397 size_t n = 1;
2398 while (n < sizeof(uint64_t) && (v >> (8 * n)) != 0) n++;
2399 return n;
2400}
2401
2403typedef struct {
2404 size_t skip;
2405 size_t nd;
2406 size_t nf;
2407 size_t len;
2410
2418 const uint64_t src_size,
2419 const int checksum_enabled) {
2421 l.skip = checksum_enabled ? (size_t)ZXC_FILE_DIGEST_SIZE : 0U;
2422 l.nd = zxc_uint_bytes(src_size);
2423 const uint64_t base = prefix + l.skip + l.nd + 1;
2424 l.nf = 1;
2425 while (zxc_uint_bytes(base + l.nf) > l.nf) l.nf++;
2426 l.compressed_size = base + l.nf;
2427 l.len = l.skip + l.nd + l.nf + 1;
2428 return l;
2429}
2430
2438int zxc_write_file_footer(uint8_t* RESTRICT dst, const size_t dst_capacity, const uint64_t prefix,
2439 const uint64_t src_size, const uint64_t digest,
2440 const int checksum_enabled);
2441
2456int zxc_check_file_footer(const uint8_t* footer, size_t avail, const zxc_footer_layout_t* l,
2457 uint64_t src_size, uint64_t* digest);
2458
2472int zxc_parse_file_footer(const uint8_t* end, size_t avail, uint64_t* src_size,
2473 uint64_t* compressed_size, size_t* sizes_len);
2474
2476#define ZXC_FOOTER_MAX_SIZE_WITH_DIGEST (ZXC_FILE_DIGEST_SIZE + ZXC_FILE_FOOTER_MAX_SIZE)
2477
2479#define ZXC_FRAME_MIN_SIZE (ZXC_FILE_HEADER_SIZE + ZXC_BLOCK_HEADER_SIZE + ZXC_FILE_FOOTER_MIN_SIZE)
2480
2484static inline size_t zxc_frame_tail_len(const uint64_t total) {
2485 const uint64_t body = total - (ZXC_FILE_HEADER_SIZE + ZXC_BLOCK_HEADER_SIZE);
2487}
2488
2502int zxc_read_frame_info(const uint8_t* header, const uint8_t* tail, size_t tail_len, uint64_t total,
2503 zxc_frame_info_t* info, size_t* footer_len, int* has_dict);
2504
2506static ZXC_ALWAYS_INLINE void zxc_frame_info_copy(zxc_frame_info_t* info, const size_t info_size,
2507 const zxc_frame_info_t* got) {
2508 ZXC_MEMCPY(info, got, info_size < sizeof(*got) ? info_size : sizeof(*got));
2509}
2510
2511
2527static ZXC_ALWAYS_INLINE int zxc_footer_dsize_plausible(const uint64_t dsize,
2528 const size_t chunk_size,
2529 const uint64_t comp_size) {
2530 return zxc_seek_block_count(dsize, chunk_size) <= comp_size / ZXC_BLOCK_HEADER_SIZE;
2531}
2532
2543int zxc_seek_table_header(uint8_t* dst, size_t dst_capacity, uint64_t num_blocks);
2544
2552int zxc_check_eof_header(const uint8_t* hdr);
2553
2570int zxc_check_seek_header(const uint8_t* hdr, size_t avail, uint64_t total_out, size_t block_size,
2571 uint64_t* sek_bytes);
2572
2573// ---------------------------------------------------------------------------
2574// Seekable cross-TU hooks (defined in zxc_seekable.c, consumed by the
2575// FILE*-flavored open helper in zxc_driver.c).
2576// -------------------------------------------------------------------------
2577
2592
2598size_t zxc_seek_write_group(uint8_t* RESTRICT dst, uint64_t* RESTRICT anchor,
2599 const uint32_t* RESTRICT sizes, uint32_t cnt);
2600 /* end of internal */
2602
2603#ifdef __cplusplus
2604}
2605#endif
2606
2607#endif // ZXC_INTERNAL_H
struct zxc_cctx_s zxc_cctx
Opaque reusable compression context (see zxc_create_cctx).
Definition zxc_buffer.h:370
struct zxc_dctx_s zxc_dctx
Opaque reusable decompression context (see zxc_create_dctx).
Definition zxc_buffer.h:372
#define ZXC_BLOCK_SIZE_MAX
Maximum allowed block size (2 MB = 2^21).
#define ZXC_BLOCK_SIZE_MIN
Minimum allowed block size (4 KB = 2^12).
#define ZXC_BLOCK_SIZE_DEFAULT
Default block size (512 KB).
#define ZXC_DICT_SIZE_MAX
Maximum dictionary content size in bytes (64 KB - 1).
#define ZXC_HUF_TABLE_SIZE
Size of a packed literal Huffman code-lengths table (256 symbols, 4 bits each): the shared table in a...
@ ZXC_ERROR_SRC_TOO_SMALL
Source buffer too small or truncated input.
Definition zxc_error.h:45
@ ZXC_OK
Success (no error).
Definition zxc_error.h:38
#define ZXC_MAGIC_WORD
Magic word opening every frame, stored little-endian (F5 2E B0 9C).
#define ZXC_FILE_DIGEST_SIZE
Archive digest, opening the footer when the header sets HAS_CHECKSUM.
#define ZXC_FILE_HEADER_SIZE
File header size: Magic(4) + Version(1) + Chunk(1) + Flags(1) + Reserved(7) + Checksum(2).
#define ZXC_FILE_FLAG_HAS_CHECKSUM
Bit flag in the Flags byte indicating checksum presence (bit 7).
#define ZXC_SEQ_OFF_MASK
Mask to extract Offset from a PAK sequence.
static uint32_t zxc_seek_group_len(const uint64_t nblocks, const uint64_t g)
Blocks in group g of nblocks: ZXC_SEEK_GROUP, fewer for the last.
#define ZXC_BITMAP_WORDS(n_bits)
Number of uint64_t words needed to hold a bitmap of n_bits.
#define ZXC_SEEK_GROUP
Blocks per group.
#define ZXC_ALIGN_CL(x)
Round x up to the next cache-line boundary.
#define ZXC_ALWAYS_INLINE
Forces a function to be inlined (fallback for non-GCC/Clang/MSVC compilers).
#define ZXC_VARINT_INVALID
A truncated or out-of-spec varint: a length no output holds.
#define ZXC_ALIGNMENT_MASK
Bitmask for cache-line alignment checks.
#define ZXC_LZ_MAX_DIST
Maximum allowed offset distance.
#define ZXC_BLOCK_FORMAT_OVERHEAD
Worst-case format overhead inside a single block beyond the outer 8-byte block header and the optiona...
static uint64_t zxc_seek_table_bytes(const uint64_t nblocks)
Byte size of the groups for nblocks blocks, in 64 bits.
#define ZXC_SPL_MAX_INLINE_OUT_PER_SEQ
Maximum decoded output of one sequence with inline ll/ml, used by the 4x bounds checks to reserve the...
#define ZXC_FILE_FLAG_RESERVED
Reserved bit in the Flags byte (bit 4), must be 0.
#define ZXC_SPL_DESC_MAX_SIZE
Widest SPL section descriptors: the literal and token section sizes.
#define ZXC_MAX_VARINT_VALUE
Maximum legitimate value a varint can decode to.
#define ZXC_TOKEN_ML_MASK
Mask to extract Match Length from a SPL token.
static uint64_t zxc_seek_group_count(const uint64_t nblocks)
Groups holding nblocks blocks; the last one may be partial.
#define ZXC_FILE_CHECKSUM_ALGO_MASK
Mask for the checksum algorithm id (bits 0-3).
#define ZXC_SEQ_ML_BITS
Bits for Match Length in a PAK sequence.
#define ZXC_LZ_MINDIST
Match distance floor the encoder holds to at levels 1 to 5, sized to the decoder's widest match-copy ...
#define ZXC_SPL_HEADER_BINARY_SIZE
Binary size of a SPL block sub-header.
#define ZXC_SEEK_SIZE_ENTRY
One block's on-disk size, u32.
#define ZXC_LZ_MIN_MATCH_LEN
Minimum match length for an LZ77 match.
#define ZXC_LZ_WINDOW_SIZE
Sliding window size (64 KB).
#define ZXC_PAD_SIZE
Safety padding appended to buffers to tolerate overruns.
#define ZXC_FILE_FLAG_HAS_DICTIONARY
Bit flag in the Flags byte indicating a dictionary is required (bit 6).
static uint32_t zxc_seek_size_field(const uint64_t table_bytes)
SEK header size field: table_bytes with its high half folded onto the low one.
#define ZXC_LZ_OFFSET_BIAS
Base bias added to encoded offsets (stored = actual - bias).
#define ZXC_BLOCK_HEADER_SIZE
Block header size: Type(1)+Flags(1)+Reserved(1)+Checksum(1)+CompSize(4).
#define ZXC_FILE_FLAG_HAS_SEEK_TABLE
Bit flag in the Flags byte: a SEK block sits between the EOF block and the footer (bit 5).
#define ZXC_BLOCK_LIT_SLACK
Readable bytes a SPL/PAK payload guarantees after its literal section.
#define ZXC_TOKEN_ML_BITS
Bits for Match Length in a SPL token.
#define ZXC_SPL_MAX_INLINE_ML
Longest match a SPL sequence carries without a varint extension.
#define ZXC_SEQ_OFF_BITS
Bits for Offset in a PAK sequence.
#define ZXC_SEQ_LL_BITS
Bits for Literal Length in a PAK sequence.
static uint32_t zxc_read_varint(const uint8_t **ptr, const uint8_t *end)
Reads a Prefix Varint encoded integer.
#define ZXC_SEEK_ANCHOR_SIZE
Group anchor: offset of its first block, u64.
#define ZXC_LZ_MINDIST_PROBE_PER_KB
Probe sampling: one position per KB, clamped.
#define ZXC_CACHE_LINE_SIZE
Assumed CPU cache line size for alignment.
#define ZXC_LZ_WINDOW_MASK
Mask for ring-buffer indexing into chain_table (power-of-two window).
#define ZXC_LZ_MINDIST_MAX_SHORT_PCT
Short-distance hit rate, in percent, above which a block keeps its short match distances.
static int zxc_magic_prefix_ok(const uint8_t *p, const size_t n)
Whether the first n bytes (up to 4) at p agree with the magic word, so a frame may start there: the c...
#define ZXC_TOKEN_LIT_BITS
Bits for Literal Length in a SPL token.
#define ZXC_DECOMPRESS_TAIL_PAD
Tail padding required on the decompression destination buffer.
@ ZXC_LEVEL_ULTRA
Maximum density: Huffman-coded literals and sequence tokens.
@ ZXC_LEVEL_FASTEST
Fastest compression; lowest ratio.
@ ZXC_LEVEL_DENSITY
Higher density: adds Huffman-coded literals on top of COMPACT.
struct zxc_seekable_s zxc_seekable
Opaque handle for a seekable ZXC archive.
On-disk header structure for a ZXC block (8 bytes, little-endian).
uint8_t reserved
Reserved for future protocol extensions.
uint32_t comp_size
Compressed size excluding this header.
uint8_t block_type
Block type (see zxc_block_type_t).
uint8_t header_checksum
Header integrity checksum (1 byte).
uint8_t block_flags
Flags (e.g., checksum presence).
Compression / decompression context.
uint32_t offset_mask
(1U << offset_bits) - 1
uint32_t * lit_freq_acc
Trainer hook: when non-NULL, the SPL encoder accumulates post-LZ literal byte frequencies here (256 e...
uint8_t * hash_tags
Split tag table for fast match rejection (8-bit tags).
zxc_dict_huf_state_t * dict_huf
Tree-at-attach state (PivCo tree + codes + code lengths), carved from the workspace only when dict_si...
uint8_t * buf_split
Match-splitting scratch, one byte per sequence.
size_t lit_buffer_cap
Current capacity of the scratch buffer.
void * memory_block
Single allocation block owner.
size_t opt_scratch_cap
Current capacity of opt_scratch in bytes.
size_t work_buf_cap
Capacity of the work buffer.
void * entropy_block
Lazy allocation backing tok_buffer + pivco_scratch (heap decode contexts, first entropy block only).
size_t pivco_scratch_cap
Capacity of pivco_scratch in bytes.
int compression_level
Compression level.
uint32_t epoch
Current epoch for lazy hash table invalidation.
uint32_t * buf_sequences
Buffer for sequence records (packed: LL(8)|ML(8)|Offset(16)).
uint8_t * lit_buffer
Scratch buffer for literals (RLE / Huffman).
uint8_t * work_buf
Padded scratch buffer for buffer-API decompression.
uint32_t * hash_table
Hash table for LZ77 match positions (epoch|pos).
uint32_t offset_bits
log2(chunk_size) - governs epoch_mark shift.
size_t chunk_size
Effective block size in bytes.
size_t tok_buffer_cap
Capacity of tok_buffer in bytes.
zxc_spl_match_split_hist_t * buf_split_hist
Match-splitting escape histograms.
uint8_t * buf_tokens
Buffer for token sequences.
uint8_t * buf_extras
Buffer for extra lengths (vbytes for LL/ML).
uint8_t * dict_buffer
[dict | data] concat scratch carved from memory_block when dict_size > 0 (NULL otherwise).
uint8_t * pivco_scratch
Level ping-pong scratch for PivCo decode.
size_t dict_size
Dictionary prefill size (0 = no dictionary).
uint8_t * literals
Buffer for literal bytes.
uint8_t * opt_scratch
Optimal-parser DP scratch (level >= 6 only, lazy-allocated, packs dp/parent_len/parent_off/actions).
uint16_t * chain_table
Chain table for collision resolution.
int checksum_enabled
1 if checksum calculation/verification is enabled.
int dict_huf_tree_ok
1 when *dict_huf is built and valid.
uint32_t max_epoch
1U << (32 - offset_bits)
uint8_t * tok_buffer
Decode scratch for a Huffman-coded SPL token section (enc_tok == HUFFMAN); NULL on compress.
uint16_t * buf_offsets
Buffer for offsets.
size_t dict_buffer_cap
Capacity of dict_buffer in bytes (0 = none).
What zxc_scan_container learns about a container.
int uses_dict
A frame bound to a dictionary.
uint64_t frames
ZXC frames.
uint64_t dsize
Sum of the stored decompressed sizes.
Compression parameters of a zxc_cctx, the private form of what zxc_cctx_set_param() / zxc_cctx_set_di...
Frame-constant dictionary Huffman state, prebuilt once at attach.
zxc_pivco_tree_t tree
PivCo tree from the shared literal table.
uint32_t codes[256]
Leaf codes as laid out in tree.
uint8_t code_len[256]
Unpacked code lengths.
Decompression parameters of a zxc_dctx; see zxc_cparams_t.
What a frame's header and footer declare, read without decoding.
Definition zxc_buffer.h:275
Header specific to General (LZ-based) compression blocks.
uint8_t enc_tok
SPL only: encoding of the token section, whose bytes each pack a literal length and a match length ni...
uint32_t n_sequences
The total count of LZ sequences in the block.
uint8_t enc_mlen
Reserved, written 0 and ignored on decode.
uint32_t n_literals
The total count of literal bytes.
uint8_t enc_lit
Encoding method used for the literal stream.
uint8_t enc_off
SPL only: width of the offset stream (1 = 1-byte, 0 = 2-byte).
Workspace of zxc_huf_nudge_code_lengths: tables and DP planes, once a 10 KiB frame and a per-block al...
int16_t sym_order[256]
Symbols by descending frequency.
uint64_t pfg[64+1]
Group-mass prefix sums.
uint64_t jcur[(64+1) *(64+1)]
DP plane.
uint64_t pf_rank[256+1]
Frequency-rank prefix sums.
uint64_t pf[256+1]
Canonical-order prefix sums.
uint8_t arrive[(11+1) *(64+1) *(64+1)]
Per-level arrival choice, c <= ZXC_HUF_NUDGE_DP_M.
zxc_huf_pm_leaf_t leaves[256]
Live symbols, sorted.
uint64_t jnxt[(64+1) *(64+1)]
Next plane.
uint8_t cand[4][256]
Candidate code lengths.
Trace-back stack frame for the package-merge code-length recovery.
int16_t idx
Item index within that level.
int8_t lvl
Package-merge level being traced back.
Boundary package-merge work item.
int16_t right
Right child index, or -1 for a leaf.
int16_t sym
Symbol index for a leaf, or -1 for an internal node.
int16_t left
Left child index, or -1 for a leaf.
uint32_t weight
Accumulated weight (summed frequency) of the package.
A live symbol and its weight, the package-merge sort key.
uint32_t w
Frequency.
int16_t sym
Byte value.
Search parameters for LZ77 compression levels.
int lazy_attempts
Maximum number of candidates explored during lazy evaluation (same semantics as search_depth but appl...
int search_depth
Maximum number of candidates explored in the hash chain per position.
int use_lazy
Enable lazy matching.
int lazy_len_threshold
Skip lazy evaluation when the current match length already reaches this threshold: a match this long ...
uint32_t step_shift
Acceleration factor for step size: step = step_base + (distance >> step_shift).
uint8_t split_max
Longest match re-emitted as inline pieces (zxc_spl_match_split_block), in the token's units (length -...
int sufficient_len
"Good enough" match length: once a match reaches this threshold the chain walk stops immediately,...
uint32_t min_offset
Shortest match distance the parser may emit; 1 = unconstrained.
uint32_t step_base
Base step size when advancing through unmatched literals.
A PivCo code tree: its canonical shape, by depth.
uint16_t node_base[11+2]
First node index of each depth.
int16_t base[11+1]
Node index of the d-bit prefix 0.
uint8_t flat_d[((2 *256 - 1)+1)]
Flat-root depth, 0, or ZXC_PIVCO_COVERED.
uint8_t syms[256]
Leaf symbols, depth by depth.
uint16_t leaf_base[11+2]
First syms index of each depth.
void * ctx
Opaque state for read_at.
uint64_t size
Container size in bytes.
int(* read_at)(const struct zxc_scan_src_s *src, uint64_t off, void *dst, size_t len)
Reads len bytes at off; NULL reads from data.
const uint8_t * data
Container bytes when read_at is NULL.
Where a container scan reads from: memory, or a positioned callback (the FILE* size query).
One-shot buffer compression and decompression.
Build configuration: what the ZXC_BUILD_SIMD_VARIANTS choice runs, derived once.
Public constants: library version, block sizes, compression levels.
Single point of override for the C-library dependencies of libzxc.
Error codes and error-name lookup for the ZXC library.
const zxc_cparams_t * zxc_cctx_params(const zxc_cctx *cctx)
Parameters a public context carries, for the FILE* and push paths.
static uint64_t zxc_le64(const void *p)
Reads a little-endian 64-bit value from a possibly unaligned address.
zxc_block_type_t
Block types, i.e.
static int zxc_ctz32(const uint32_t x)
Counts trailing zeros, returning 32 for a zero input.
static int zxc_ss_prem_rle_q8(const int level)
Per-level RLE-vs-RAW decode premium (Q8) for the space-speed selector.
size_t zxc_huf_calc_size(const uint32_t *freq, const uint8_t *code_len, int with_header)
Exact encoded size (bytes) of a PivCo section for this histogram and code lengths; includes the 128-b...
#define ZXC_HUF_NUDGE_DP_M
Slot-ledger DP bound, coarse symbols per plane axis; the nudge groups symbols to stay under it.
int zxc_read_block_header(const uint8_t *src, const size_t src_size, zxc_block_header_t *bh)
Reads and parses a ZXC block header from src.
Definition zxc_common.c:699
void zxc_cctx_free(zxc_cctx_t *ctx)
Releases the internal buffers owned by a context.
Definition zxc_common.c:382
static uint32_t zxc_le32(const void *p)
Reads a little-endian 32-bit value from a possibly unaligned address.
int zxc_write_block_header(uint8_t *dst, const size_t dst_capacity, const zxc_block_header_t *bh)
Encodes a block header into dst.
Definition zxc_common.c:680
int zxc_write_pak_header(uint8_t *dst, const size_t rem, const zxc_gnr_header_t *gh)
Writes a PAK sub-header.
Definition zxc_common.c:990
static void zxc_copy32(void *dst, const void *src)
Copies 32 bytes from source to destination using SIMD when available.
int zxc_parse_file_footer(const uint8_t *end, size_t avail, uint64_t *src_size, uint64_t *compressed_size, size_t *sizes_len)
Parses the sizes back from the end of a frame.
Definition zxc_common.c:858
int zxc_huf_encode_section_dict(const uint8_t *literals, size_t n_literals, const uint32_t *freq, const uint8_t *code_len, const zxc_pivco_tree_t *tree, const uint32_t *codes, uint8_t *dst, size_t dst_cap)
Encode a PivCo section against a prebuilt dict tree/codes (no header).
static int zxc_huf_enc_max_code_len(const int level)
Encoder Huffman code-length cap for a compression level: levels below ZXC_LEVEL_ULTRA use ZXC_HUF_MAX...
#define ZXC_OPT_LONG_MATCH_SKIP
Threshold above which find_best_match is skipped at intra-match positions, keeping the parser O(N) on...
#define ZXC_HASH_GOLDEN64
Golden-ratio prime: header hashes and the digest spread.
static void zxc_frame_info_copy(zxc_frame_info_t *info, const size_t info_size, const zxc_frame_info_t *got)
Copies the fields of got that fit the caller's info_size bytes.
static int zxc_validate_block_size(const size_t bs)
Validates a block size.
static zxc_scan_src_t zxc_scan_src_mem(const uint8_t *data, const size_t size)
A scan source over size bytes of memory at data.
int zxc_huf_encode_section(const uint8_t *literals, size_t n_literals, const uint32_t *freq, const uint8_t *code_len, uint8_t *dst, size_t dst_cap)
Encode a PivCo literal section (128-byte lengths header + payload).
uint32_t zxc_spl_match_split_hist_t[4][2][1U<< 8]
zxc_spl_match_split_analyze's escape histograms: four rotating lanes of [escape][context] counts,...
int zxc_cctx_alloc_entropy_scratch(zxc_cctx_t *ctx)
Lazily allocates the decode-side entropy scratch (tok_buffer + pivco_scratch) for a heap context init...
Definition zxc_common.c:355
int zxc_cctx_init_in_workspace(zxc_cctx_t *ctx, void *workspace, const size_t workspace_size, const size_t chunk_size, const int mode, const int level, const int checksum_enabled, const size_t dict_size, const int defer_entropy_scratch)
Initialises a compression / decompression context inside a caller-supplied workspace.
Definition zxc_common.c:240
int zxc_seek_table_header(uint8_t *dst, size_t dst_capacity, uint64_t num_blocks)
Writes a seek table's block header for num_blocks entries.
Definition zxc_common.c:731
int zxc_container_next(const zxc_scan_src_t *src, uint64_t pos)
Tells whether a frame starts at pos.
Definition zxc_common.c:550
int zxc_check_seek_header(const uint8_t *hdr, size_t avail, uint64_t total_out, size_t block_size, uint64_t *sek_bytes)
Checks the SEK block header the file header announced, on the avail bytes present.
Definition zxc_common.c:750
#define ZXC_HUF_MAX_CODE_LEN_ULTRA
Maximum Huffman code length, in bits: the ceiling the decoder's on-wire validation accepts (and the l...
int zxc_read_frame_info(const uint8_t *header, const uint8_t *tail, size_t tail_len, uint64_t total, zxc_frame_info_t *info, size_t *footer_len, int *has_dict)
Validates a frame from its header and the end of its bytes: the one check behind zxc_get_frame_info()...
Definition zxc_common.c:640
int zxc_huf_decode_section_dict(const uint8_t *payload, size_t payload_size, uint8_t *dst, size_t n, const zxc_pivco_tree_t *tree, uint8_t *scratch)
Decode a PivCo dict section against a prebuilt dict tree.
static void zxc_store_le64(void *p, const uint64_t v)
Writes a 64-bit value little-endian to a possibly unaligned address.
static int zxc_ss_prem_huf_q8(const int level)
Per-level Huffman/PivCo-vs-RAW decode premium (Q8) for the space-speed selector.
static zxc_lz77_params_t zxc_get_lz77_params(const int level)
Retrieves LZ77 compression parameters based on the specified compression level.
void zxc_seekable_attach_owned_ctx(zxc_seekable *s, void *ctx)
Hands ownership of a heap-allocated reader context to a seekable handle.
int zxc_huf_build_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, int max_code_len)
Build length-limited canonical Huffman code lengths from a frequency table.
static uint32_t zxc_log2_u32(const uint32_t v)
Integer log-base-2 for a 32-bit value.
int zxc_scan_whole_frame(const zxc_scan_src_t *src, zxc_frame_info_t *info, size_t *footer_len)
The frame that must span all of src: zxc_get_frame_info() and its FILE* twin.
Definition zxc_common.c:593
static uint64_t zxc_digest_combine(const uint64_t acc, const uint32_t block_checksum)
Folds a data block's 32-bit checksum into the running archive digest.
size_t zxc_cctx_compute_workspace_size(const size_t chunk_size, const int mode, const int level, const size_t dict_size)
Returns the byte count that zxc_cctx_init would allocate for the given parameters.
Definition zxc_common.c:225
static size_t zxc_block_size_ceil(const size_t v)
Branchless bit_ceil: smallest power of two >= v, clamped to ZXC_BLOCK_SIZE_MIN.
static uint64_t zxc_seek_block_count(const uint64_t total_decomp, const size_t block_size)
Blocks in total_decomp bytes of block_size: the seek table's entry count, which the SEK header's fiel...
static uint16_t zxc_le16(const void *p)
Reads a little-endian 16-bit value from a possibly unaligned address.
size_t zxc_huf_calc_size_dict(const uint32_t *freq, const uint8_t *code_len, const zxc_pivco_tree_t *tree)
zxc_huf_calc_size for a dict section: prebuilt tree, no header.
static uint16_t zxc_hash16(const uint8_t *p)
Computes the 2-byte checksum for file and dictionary headers.
void zxc_huf_nudge_cost(const uint8_t *code_len, const uint32_t *freq, uint64_t *bits, uint64_t *touches)
Modeled (bits, level-touches) decode cost of one code-length vector.
static void zxc_store_le16(void *p, const uint16_t v)
Writes a 16-bit value little-endian to a possibly unaligned address.
static uint8_t zxc_hash8(const uint8_t *p)
Computes the 1-byte checksum for block headers.
int zxc_decompress_chunk_wrapper_dict(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Public dictionary chunk decoder.
int zxc_compress_chunk_wrapper(zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Compresses one chunk through the runtime ISA dispatch.
int zxc_check_file_footer(const uint8_t *footer, size_t avail, const zxc_footer_layout_t *l, uint64_t src_size, uint64_t *digest)
Checks the footer a sequential reader reaches against l, the one the frame implies,...
Definition zxc_common.c:840
static int zxc_footer_dsize_plausible(const uint64_t dsize, const size_t chunk_size, const uint64_t comp_size)
Whether a footer's decompressed size is reachable for this archive.
#define ZXC_HUF_MAX_CODE_LEN_DENSITY
Encoder code-length cap for levels up to ZXC_LEVEL_DENSITY (below ZXC_LEVEL_ULTRA): shallow 8-bit tre...
int zxc_read_spl_header_and_desc(const uint8_t *src, const size_t len, zxc_gnr_header_t *gh, uint32_t *lit_comp, uint32_t *tok_comp)
Reads a SPL sub-header and its section descriptors from a source buffer.
Definition zxc_common.c:958
#define ZXC_HUF_MARGIN_SHIFT
Huffman margin shift: source of the legacy below-ULTRA premium used by zxc_ss_prem_huf_q8 (the frozen...
static void zxc_store_le32(void *p, const uint32_t v)
Writes a 32-bit value little-endian to a possibly unaligned address.
#define ZXC_HASH_MULT64
Second multiplier of the 16-byte header hash (zxc_hash16).
static size_t zxc_uint_bytes(const uint64_t v)
Fewest little-endian bytes, 1 to 8, that hold v.
int zxc_huf_decode_section(const uint8_t *payload, size_t payload_size, uint8_t *dst, size_t n, uint8_t *scratch)
Decode a PivCo literal section into dst (exactly n bytes).
int zxc_huf_nudge_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, size_t scratch_cap, int max_code_len)
Optionally reshape freshly built code lengths for faster PivCo decode.
int zxc_check_eof_header(const uint8_t *hdr)
Checks an EOF block header against its one valid form: type 255, every other field zero,...
Definition zxc_common.c:741
static int zxc_ctz64(const uint64_t x)
Counts trailing zeros, returning 64 for a zero input.
static void zxc_copy16(void *dst, const void *src)
Copies exactly 16 bytes as one vector move where the ISA has one.
static int zxc_block_is_short_dist_bound(const uint8_t *const blk, const size_t size)
Reports whether a block leans on back-references shorter than ZXC_LZ_MINDIST.
#define ZXC_HASH_XORSHIFT64
Vigna's xorshift* multiplier: the 5-byte LZ hash and the digest fold.
int zxc_read_pak_header(const uint8_t *src, const size_t len, zxc_gnr_header_t *gh)
Reads a PAK sub-header from a buffer.
static size_t zxc_frame_tail_len(const uint64_t total)
Bytes zxc_read_frame_info() takes from the end of total bytes (at least ZXC_FRAME_MIN_SIZE): all of t...
int zxc_cctx_init(zxc_cctx_t *ctx, const size_t chunk_size, const int mode, const int level, const int checksum_enabled, const size_t dict_size)
Initialises a ZXC compression / decompression context in place.
Definition zxc_common.c:319
int zxc_scan_container(const zxc_scan_src_t *src, size_t req_chunk, zxc_container_info_t *info)
Measures a whole container without decoding: frames from the last back to the first through zxc_scan_...
Definition zxc_common.c:605
int zxc_scan_frame(const zxc_scan_src_t *src, uint64_t end, uint64_t *start, zxc_frame_info_t *info, size_t *footer_len, int *has_dict)
Measures the frame ending at end without decoding: its footer's compressed size gives where it starts...
Definition zxc_common.c:561
#define ZXC_FOOTER_MAX_SIZE_WITH_DIGEST
Most bytes a footer spans: the digest and the two longest sizes.
#define ZXC_PIVCO_NODE_SLOTS
Node-indexed array size: every node, plus a slot for the lone-symbol root's missing child.
size_t zxc_seek_write_group(uint8_t *dst, uint64_t *anchor, const uint32_t *sizes, uint32_t cnt)
Writes one group (*anchor, then cnt sizes) into dst, which holds ZXC_SEEK_GROUP_BYTES,...
Definition zxc_common.c:763
int zxc_decompress_chunk_wrapper(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Decompresses one chunk through the runtime ISA dispatch.
static void zxc_file_header_sign(uint8_t *h)
Writes the file header checksum (bytes 14-15) over the other 14 bytes.
#define ZXC_RLE_MARGIN_SHIFT
RLE margin shift: source of the legacy below-ULTRA premium used by zxc_ss_prem_rle_q8 (256 >> shift r...
int zxc_read_file_header(const uint8_t *src, const size_t src_size, size_t *out_block_size, int *out_has_checksum, int *out_has_dict, uint32_t *out_dict_id, int *out_has_seek)
Validates and reads the ZXC file header from src.
Definition zxc_common.c:499
int zxc_write_file_footer(uint8_t *dst, const size_t dst_capacity, const uint64_t prefix, const uint64_t src_size, const uint64_t digest, const int checksum_enabled)
Writes the footer of a frame whose first prefix bytes precede it.
Definition zxc_common.c:825
#define ZXC_SPL_MATCH_SPLIT_CTX_BITS
Longest escape history a context keys on; small blocks shorten it (down to 2 bits) towards 16 samples...
int zxc_write_file_header(uint8_t *dst, const size_t dst_capacity, const size_t chunk_size, const int has_checksum, const int has_dict, const uint32_t dict_id, const int has_seek)
Writes the standard ZXC file header into dst.
Definition zxc_common.c:468
static zxc_footer_layout_t zxc_footer_layout(const uint64_t prefix, const uint64_t src_size, const int checksum_enabled)
The footer of a frame whose first prefix bytes precede it.
static uint32_t zxc_checksum(const void *input, const size_t len, const uint64_t seed, const uint8_t hash_method)
Calculates a 32-bit hash for a given input buffer.
int64_t zxc_compress_block_at(zxc_cctx *cctx, const void *src, size_t src_size, void *dst, size_t dst_capacity, const zxc_cparams_t *opts, uint64_t block_index)
zxc_compress_block, its checksum seeded with block_index (public entry: 0).
int zxc_cctx_attach_dict_huf(zxc_cctx_t *ctx, const uint8_t *lengths)
Attach the shared dictionary literal table to an initialised context.
Definition zxc_common.c:435
static int zxc_short_input_verdict(const uint8_t *p, const size_t n)
The verdict on n bytes too short for a frame: the header speaks first, then ZXC_ERROR_SRC_TOO_SMALL.
void zxc_huf_pack_lengths(const uint8_t *code_len, uint8_t *out)
Pack per-symbol code lengths into the 128-byte (4-bit nibble) header.
int zxc_decompress_chunk_wrapper_safe(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Exact-capacity variant for the safe block API; dispatch table only.
static int zxc_block_header_ok(const uint8_t *p)
Block header integrity (FORMAT.md Sec 4.1, 7.1): checksum byte matches, Block Flags and Reserved are ...
static void zxc_opt_dp_sizes(const size_t chunk_size, size_t *sz_dp, size_t *sz_pl, size_t *sz_po, size_t *sz_bm)
The four DP partitions the optimal parser carves out of opt_scratch.
int zxc_huf_dict_tree_build(const uint8_t *packed_lengths, zxc_pivco_tree_t *tree, uint32_t *codes, uint8_t *code_len)
Unpack a dict table's packed lengths and prebuild its tree, codes and code lengths,...
int zxc_huf_unpack_lengths(const uint8_t *in, uint8_t *code_len)
Unpack and structurally validate a 128-byte packed lengths header.
#define ZXC_HUF_NUM_SYMBOLS
Alphabet size: one entry per possible byte value.
int zxc_write_spl_header_and_desc(uint8_t *dst, const size_t rem, const zxc_gnr_header_t *gh, const uint32_t lit_comp, const uint32_t tok_comp)
Writes a SPL sub-header followed by its section descriptors.
Definition zxc_common.c:933
zxc_section_encoding_t
Specifies the encoding methods used for internal data sections.
void(* zxc_progress_callback_t)(uint64_t bytes_processed, uint64_t bytes_total, const void *user_data)
Progress callback function type.
Definition zxc_opts.h:40
Seekable compression and random-access decompression API.