ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_compress.c
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
17
18// Function Multi-Versioning Support
19// With ZXC_FUNCTION_SUFFIX defined (e.g. _avx2), rename the entry point AND the
20// Huffman entry points this TU consumes. The defines precede zxc_internal.h so
21// the header's prototypes get the suffix too, keeping callers and callees matched.
22#ifdef ZXC_FUNCTION_SUFFIX
23#define ZXC_CAT_IMPL(x, y) x##y
24#define ZXC_CAT(x, y) ZXC_CAT_IMPL(x, y)
25#define zxc_compress_chunk_wrapper ZXC_CAT(zxc_compress_chunk_wrapper, ZXC_FUNCTION_SUFFIX)
26#define zxc_huf_build_code_lengths ZXC_CAT(zxc_huf_build_code_lengths, ZXC_FUNCTION_SUFFIX)
27#define zxc_huf_unpack_lengths ZXC_CAT(zxc_huf_unpack_lengths, ZXC_FUNCTION_SUFFIX)
28#define zxc_huf_calc_size ZXC_CAT(zxc_huf_calc_size, ZXC_FUNCTION_SUFFIX)
29#define zxc_huf_calc_size_dict ZXC_CAT(zxc_huf_calc_size_dict, ZXC_FUNCTION_SUFFIX)
30#define zxc_huf_encode_section ZXC_CAT(zxc_huf_encode_section, ZXC_FUNCTION_SUFFIX)
31#define zxc_huf_encode_section_dict ZXC_CAT(zxc_huf_encode_section_dict, ZXC_FUNCTION_SUFFIX)
32#endif
33
35#include "zxc_internal.h"
36
45static ZXC_ALWAYS_INLINE uint32_t zxc_hash_func(const uint64_t val, const int use_hash5) {
46 if (use_hash5) {
47 const uint64_t v5 = val & 0xFFFFFFFFFFULL;
48 return (uint32_t)((v5 * ZXC_HASH_XORSHIFT64) >> (64 - ZXC_LZ_HASH_BITS));
49 } else {
50 const uint64_t v4 = val ^ (val >> 15);
51 return ((uint32_t)v4 * ZXC_HASH_MULT32) >> (32 - ZXC_LZ_HASH_BITS);
52 }
53}
54
61static ZXC_ALWAYS_INLINE uint8_t zxc_hash_tag(const uint32_t val4) {
62 return (uint8_t)(val4 ^ (val4 >> 16));
63}
64
71static ZXC_ALWAYS_INLINE uint32_t zxc_epoch_pos(const uint32_t head, const uint32_t offset_mask,
72 const uint32_t epoch_mark) {
73 return ((head & ~offset_mask) == epoch_mark) ? (head & offset_mask) : 0;
74}
75
82static ZXC_ALWAYS_INLINE uint16_t zxc_chain_delta(const uint32_t cur_pos, const uint32_t prev_idx) {
83 const uint32_t dist = cur_pos - prev_idx;
84 // cppcheck-suppress bitwiseOnBoolean
85 const uint32_t valid = 0U - (uint32_t)((prev_idx != 0) & (dist < ZXC_LZ_WINDOW_SIZE));
86 return (uint16_t)(dist & valid);
87}
88
98#if defined(ZXC_USE_AVX512)
99#define ZXC_RLE_WIN 64
100#define ZXC_RLE_BPB 1
101#define ZXC_RLE_CTZ(x) zxc_ctz64(x)
102typedef uint64_t zxc_rle_mask_t;
103static ZXC_ALWAYS_INLINE zxc_rle_mask_t zxc_rle_pair_mask(const uint8_t* p) {
104 return (uint64_t)_mm512_cmpeq_epi8_mask(_mm512_loadu_si512((const void*)p),
105 _mm512_loadu_si512((const void*)(p + 1)));
106}
107#elif defined(ZXC_USE_AVX2)
108#define ZXC_RLE_WIN 32
109#define ZXC_RLE_BPB 1
110#define ZXC_RLE_CTZ(x) zxc_ctz32(x)
111typedef uint32_t zxc_rle_mask_t;
112static ZXC_ALWAYS_INLINE zxc_rle_mask_t zxc_rle_pair_mask(const uint8_t* p) {
113 const __m256i v0 = _mm256_loadu_si256((const __m256i*)p);
114 const __m256i v1 = _mm256_loadu_si256((const __m256i*)(p + 1));
115 return (uint32_t)_mm256_movemask_epi8(_mm256_cmpeq_epi8(v0, v1));
116}
117#elif defined(ZXC_USE_SSE2)
118#define ZXC_RLE_WIN 16
119#define ZXC_RLE_BPB 1
120#define ZXC_RLE_CTZ(x) zxc_ctz32(x)
121typedef uint32_t zxc_rle_mask_t;
122static ZXC_ALWAYS_INLINE zxc_rle_mask_t zxc_rle_pair_mask(const uint8_t* p) {
123 const __m128i v0 = _mm_loadu_si128((const __m128i*)p);
124 const __m128i v1 = _mm_loadu_si128((const __m128i*)(p + 1));
125 return (uint32_t)_mm_movemask_epi8(_mm_cmpeq_epi8(v0, v1));
126}
127#elif defined(ZXC_USE_NEON64)
128#define ZXC_RLE_WIN 16
129#define ZXC_RLE_BPB 4
130#define ZXC_RLE_CTZ(x) zxc_ctz64(x)
131typedef uint64_t zxc_rle_mask_t;
132static ZXC_ALWAYS_INLINE zxc_rle_mask_t zxc_rle_pair_mask(const uint8_t* p) {
133 const uint8x16_t eq = vceqq_u8(vld1q_u8(p), vld1q_u8(p + 1));
134 return vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(eq), 4)), 0);
135}
136#endif
137
138// SSE2 selected, not merely available: guards the two helpers below.
139#if defined(ZXC_USE_SSE2) && !(defined(ZXC_USE_AVX512) && defined(__AVX512VL__)) && \
140 !defined(ZXC_USE_AVX2) && !defined(ZXC_USE_NEON64) && !defined(ZXC_USE_NEON32)
141#define ZXC_OPT_SSE2
142#endif
143
144#if defined(ZXC_OPT_SSE2)
157static ZXC_ALWAYS_INLINE __m128i zxc_mm_blendv_epi8_sse2(__m128i a, __m128i b, __m128i mask) {
158 return _mm_or_si128(_mm_and_si128(mask, b), _mm_andnot_si128(mask, a));
159}
160
173static ZXC_ALWAYS_INLINE __m128i zxc_mm_packus_epi32_sse2(__m128i a, __m128i b) {
174 const __m128i bias32 = _mm_set1_epi32(0x8000);
175 const __m128i bias16 = _mm_set1_epi16((short)0x8000);
176 const __m128i pa = _mm_sub_epi32(a, bias32);
177 const __m128i pb = _mm_sub_epi32(b, bias32);
178 return _mm_add_epi16(_mm_packs_epi32(pa, pb), bias16);
179}
180#endif
181
198static ZXC_ALWAYS_INLINE size_t zxc_write_varint(uint8_t* RESTRICT dst, const uint32_t val) {
199 // Values above ZXC_MAX_VARINT_VALUE are out-of-spec and the decoder would
200 // reject them. Unreachable from the Block API, so this is defence in depth;
201 // callers must treat a return of 0 as an encoding error.
202 if (UNLIKELY(val > ZXC_MAX_VARINT_VALUE)) {
203 return 0;
204 }
205
206 // 1 byte: 0xxxxxxx (7 bits)
207 if (LIKELY(val < ZXC_VARINT_1B_LIMIT)) {
208 dst[0] = (uint8_t)val;
209 return 1;
210 }
211
212 // 2 bytes: 10xxxxxx xxxxxxxx (14 bits)
213 if (LIKELY(val < ZXC_VARINT_2B_LIMIT)) {
214 dst[0] = (uint8_t)(0x80 | (val & 0x3F));
215 dst[1] = (uint8_t)(val >> 6);
216 return 2;
217 }
218
219 // 3 bytes: 110xxxxx xxxxxxxx xxxxxxxx (21 bits) -> max emittable value,
220 // matching ZXC_MAX_VARINT_VALUE = ZXC_BLOCK_SIZE_MAX - 1.
221 dst[0] = (uint8_t)(0xC0 | (val & 0x1F));
222 dst[1] = (uint8_t)(val >> 5);
223 dst[2] = (uint8_t)(val >> 13);
224 return 3;
225}
226
233static ZXC_ALWAYS_INLINE int zxc_emit_extra(uint8_t* RESTRICT extras, size_t* RESTRICT used,
234 const uint32_t val, const uint32_t mask) {
235 if (LIKELY(val < mask)) return 1;
236 const size_t n = zxc_write_varint(extras + *used, val - mask);
237 if (UNLIKELY(n == 0)) return 0;
238 *used += n;
239 return 1;
240}
241
258static ZXC_ALWAYS_INLINE int zxc_spl_put_seq(uint8_t* RESTRICT buf_tokens,
259 uint16_t* RESTRICT buf_offsets,
260 uint8_t* RESTRICT buf_extras, uint32_t* RESTRICT seq_c,
261 size_t* RESTRICT extras_sz,
262 uint16_t* RESTRICT max_offset, const uint32_t ll,
263 const uint32_t ml, const uint16_t off_biased) {
264 const uint8_t ll_code = (ll >= ZXC_TOKEN_LL_MASK) ? ZXC_TOKEN_LL_MASK : (uint8_t)ll;
265 const uint8_t ml_code = (ml >= ZXC_TOKEN_ML_MASK) ? ZXC_TOKEN_ML_MASK : (uint8_t)ml;
266 buf_tokens[*seq_c] = (uint8_t)((ll_code << ZXC_TOKEN_LIT_BITS) | ml_code);
267 buf_offsets[*seq_c] = off_biased;
268 if (off_biased > *max_offset) *max_offset = off_biased;
269 if (UNLIKELY(!zxc_emit_extra(buf_extras, extras_sz, ll, ZXC_TOKEN_LL_MASK) ||
270 !zxc_emit_extra(buf_extras, extras_sz, ml, ZXC_TOKEN_ML_MASK)))
271 return 0;
272 (*seq_c)++;
273 return 1;
274}
275
277static ZXC_ALWAYS_INLINE void zxc_extras_move(uint8_t* extras, size_t* RESTRICT w,
278 size_t* RESTRICT r, const uint8_t* to) {
279 while (extras + *r < to) extras[(*w)++] = extras[(*r)++];
280}
281
283static ZXC_ALWAYS_INLINE void zxc_varint_keep(uint8_t* extras, size_t* RESTRICT w,
284 size_t* RESTRICT r, const uint8_t* end) {
285 const uint8_t* p = extras + *r;
286 (void)zxc_read_varint(&p, end);
287 zxc_extras_move(extras, w, r, p);
288}
289
291static ZXC_ALWAYS_INLINE uint32_t zxc_spl_match_split_pieces(const uint32_t code) {
293}
294
297static ZXC_ALWAYS_INLINE uint32_t zxc_spl_match_split_piece(const uint32_t code) {
298 const uint32_t rest = code - ZXC_LZ_MIN_MATCH_LEN;
299 return (rest < ZXC_SPL_INLINE_ML_CODE) ? rest : ZXC_SPL_INLINE_ML_CODE;
300}
301
313static int zxc_spl_match_split_analyze(const uint8_t* RESTRICT tokens, const uint32_t n_seq,
314 zxc_spl_match_split_hist_t* RESTRICT hist_buf,
315 uint8_t* RESTRICT ctx_bad, uint8_t* RESTRICT side) {
316 uint32_t order = ZXC_SPL_MATCH_SPLIT_CTX_BITS;
317 while (order > 2 && (n_seq >> order) < 16) order--;
318 const uint32_t hmask = (1U << order) - 1U;
319 uint32_t (*const ctx_hist)[2][1U << ZXC_SPL_MATCH_SPLIT_CTX_BITS] = *hist_buf;
320 for (uint32_t l = 0; l < 4; l++) {
321 ZXC_MEMSET(ctx_hist[l][0], 0, (hmask + 1) * sizeof(uint32_t));
322 ZXC_MEMSET(ctx_hist[l][1], 0, (hmask + 1) * sizeof(uint32_t));
323 }
324 uint32_t hist = 0, n_esc = 0;
325 for (uint32_t i = 0; i < n_seq; i++) {
326 const uint32_t esc = (tokens[i] & ZXC_TOKEN_ML_MASK) == ZXC_TOKEN_ML_MASK;
327 side[i] = (uint8_t)hist;
328 ctx_hist[i & 3][esc][hist]++;
329 hist = ((hist << 1) | esc) & hmask;
330 n_esc += esc;
331 }
332 // No conditional sum here: GCC 14.2 miscompiles it for AVX-512
333 uint32_t errors = 0;
334 for (uint32_t c = 0; c <= hmask; c++) {
335 uint32_t n0 = 0, n1 = 0;
336 for (uint32_t l = 0; l < 4; l++) {
337 n0 += ctx_hist[l][0][c];
338 n1 += ctx_hist[l][1][c];
339 }
340 ctx_bad[c] = (n1 < n0); // escape a strict minority in its context
341 errors += (n0 < n1) ? n0 : n1;
342 }
343 return n_esc != 0 &&
344 (uint64_t)errors * 100 >= (uint64_t)ZXC_SPL_MATCH_SPLIT_MIN_MISPREDICT_PCT * n_esc;
345}
346
374static uint32_t zxc_spl_match_split_block(uint8_t* RESTRICT tokens, uint16_t* RESTRICT offsets,
375 uint8_t* RESTRICT extras, size_t* RESTRICT extras_sz,
376 uint8_t* RESTRICT side,
377 zxc_spl_match_split_hist_t* RESTRICT hist_buf,
378 const uint32_t n_seq, const uint8_t cap) {
379 if (cap <= ZXC_SPL_INLINE_ML_CODE || n_seq == 0) return n_seq;
380 uint8_t ctx_bad[1U << ZXC_SPL_MATCH_SPLIT_CTX_BITS];
381 if (!zxc_spl_match_split_analyze(tokens, n_seq, hist_buf, ctx_bad, side)) return n_seq;
382
383 // 1. Mark the matches to split (bad context, within the cap) and drop their
384 // varints; the other extras move forward.
385 const uint8_t* const extras_end = extras + *extras_sz;
386 size_t r = 0, w = 0;
387 uint32_t extra = 0;
388 for (uint32_t i = 0; i < n_seq; i++) {
389 const uint8_t tok = tokens[i];
390 const int bad = ctx_bad[side[i]];
391 side[i] = 0;
393 zxc_varint_keep(extras, &w, &r, extras_end);
394 if ((tok & ZXC_TOKEN_ML_MASK) != ZXC_TOKEN_ML_MASK) continue;
395 const uint8_t* p = extras + r;
396 const uint32_t code = zxc_read_varint(&p, extras_end) + ZXC_TOKEN_ML_MASK;
397 if (bad && code <= cap) {
398 side[i] = (uint8_t)code;
399 extra += zxc_spl_match_split_pieces(code) - 1;
400 r = (size_t)(p - extras);
401 } else {
402 zxc_extras_move(extras, &w, &r, p);
403 }
404 }
405 *extras_sz = w;
406 if (extra == 0) return n_seq;
407
408 // 2. Expand backward. A marked sequence spans its pieces, written forward: the
409 // first keeps the literal nibble and its escape, the last takes the remainder.
410 uint32_t out = n_seq + extra;
411 for (uint32_t i = n_seq; i-- > 0;) {
412 const uint8_t tok = tokens[i];
413 const uint16_t off = offsets[i];
414 if (side[i] == 0) {
415 out--;
416 tokens[out] = tok;
417 offsets[out] = off;
418 continue;
419 }
420 uint32_t code = side[i];
421 uint8_t ll_bits = tok & (uint8_t)(ZXC_TOKEN_LL_MASK << ZXC_TOKEN_LIT_BITS);
422 out -= zxc_spl_match_split_pieces(code);
423 uint32_t k = out;
424 while (code > ZXC_SPL_INLINE_ML_CODE) {
425 const uint32_t p = zxc_spl_match_split_piece(code);
426 tokens[k] = (uint8_t)(ll_bits | p);
427 offsets[k++] = off;
428 ll_bits = 0;
429 code -= p + ZXC_LZ_MIN_MATCH_LEN;
430 }
431 tokens[k] = (uint8_t)(ll_bits | code);
432 offsets[k] = off;
433 }
434 return n_seq + extra;
435}
436
443static ZXC_ALWAYS_INLINE void zxc_flush_literals(uint8_t* literals, size_t* lit_c,
444 const uint8_t* anchor, const uint32_t ll,
445 const uint8_t* iend) {
446 if (LIKELY(anchor + ZXC_PAD_SIZE <= iend)) {
447 zxc_copy32(literals + *lit_c, anchor);
448 if (UNLIKELY(ll > ZXC_PAD_SIZE))
449 ZXC_MEMCPY(literals + *lit_c + ZXC_PAD_SIZE, anchor + ZXC_PAD_SIZE, ll - ZXC_PAD_SIZE);
450 } else {
451 ZXC_MEMCPY(literals + *lit_c, anchor, ll);
452 }
453 *lit_c += ll;
454}
455
466typedef struct {
467 const uint8_t* ref;
468 uint32_t len;
469 uint32_t backtrack;
470} zxc_match_t;
471
485static ZXC_ALWAYS_INLINE int zxc_match_reaches(const uint8_t* cur, const uint8_t* ref,
486 uint32_t from, const uint32_t need,
487 const uint8_t* iend) {
488 while (from < need) {
489 if (UNLIKELY((size_t)(iend - cur) - from < sizeof(uint64_t))) {
490 while (from < need && cur[from] == ref[from]) from++;
491 return from >= need;
492 }
493 const uint64_t d = zxc_le64(cur + from) ^ zxc_le64(ref + from);
494 if (d != 0) return from + (uint32_t)(zxc_ctz64(d) >> 3) >= need;
495 from += sizeof(uint64_t);
496 }
497 return 1;
498}
499
507static ZXC_ALWAYS_INLINE int zxc_lazy_probe(const uint8_t* src, const uint8_t* lp,
508 const uint8_t* iend, const uint32_t need,
509 const uint32_t* RESTRICT hash_table,
510 const uint8_t* RESTRICT hash_tags,
511 const uint16_t* RESTRICT chain_table,
512 const uint32_t epoch_mark, const uint32_t offset_mask,
513 const int use_hash5, const zxc_lz77_params_t p) {
514 if (need > (size_t)(iend - lp)) return 0; // too close to the end to win
515
516 const uint64_t val8 = zxc_le64(lp);
517 const uint32_t val = (uint32_t)val8;
518 const uint32_t h = zxc_hash_func(val8, use_hash5);
519 const uint32_t pos = (uint32_t)(lp - src);
520 const uint32_t gate = zxc_le32(lp + need - 4);
521 uint32_t idx = zxc_epoch_pos(hash_table[h], offset_mask, epoch_mark);
522 // A head with another tag is another string: walk past it.
523 int skip = (hash_tags[h] != zxc_hash_tag(val));
524
525 for (int att = p.lazy_attempts; idx > 0 && att > 0; att--) {
526 if (UNLIKELY(pos - idx > ZXC_LZ_MAX_DIST)) break;
527 const uint8_t* const ref = src + idx;
528
529 // Filtered here too: a lazy hit only cancels best.ref, so a match
530 // we could never emit would drop a legal one for nothing.
531 if (pos - idx >= p.min_offset && !skip && zxc_le32(ref + need - 4) == gate &&
532 zxc_le32(ref) == val && zxc_match_reaches(lp, ref, sizeof(uint32_t), need, iend))
533 return 1;
534
535 const uint16_t delta = chain_table[idx & ZXC_LZ_WINDOW_MASK];
536 if (UNLIKELY(delta == 0)) break;
537 idx -= delta;
538 skip = 0;
539 }
540 return 0;
541}
542
569 const uint8_t* src, const uint8_t* ip, const uint8_t* iend, const uint8_t* search_limit,
570 const uint8_t* anchor, uint32_t* RESTRICT hash_table, uint8_t* RESTRICT hash_tags,
571 uint16_t* RESTRICT chain_table, const uint32_t epoch_mark, const uint32_t offset_mask,
572 const int level, const zxc_lz77_params_t p, const uint32_t last_off) {
573 const int use_hash5 = (level >= ZXC_LEVEL_DEFAULT);
574 // Sentinel length just below the minimum, so any valid match replaces it.
575 zxc_match_t best = (zxc_match_t){NULL, ZXC_LZ_MIN_MATCH_LEN - 1, 0};
576
577 uint64_t cur_val8 = zxc_le64(ip);
578 uint32_t cur_val = (uint32_t)cur_val8;
579 uint32_t h = zxc_hash_func(cur_val8, use_hash5);
580
581 // 8-bit tag: XOR fold of first 4 bytes for fast rejection
582 const uint8_t cur_tag = zxc_hash_tag(cur_val);
583
584 const uint32_t cur_pos = (uint32_t)(ip - src);
585
586 // Tag-first filter on fast levels.
587 const uint8_t stored_tag = hash_tags[h];
588 uint32_t match_idx;
589 if (level <= ZXC_LEVEL_FAST && stored_tag != cur_tag) {
590 match_idx = 0;
591 } else {
592 match_idx = zxc_epoch_pos(hash_table[h], offset_mask, epoch_mark);
593 }
594
595 // skip_head still drives the chain walk on level >= 3 (advances past the
596 // mismatched head without comparing). On level <= 2 it is always 0 here:
597 // either match_idx == 0 (filter-skip) or stored_tag == cur_tag.
598 // cppcheck-suppress bitwiseOnBoolean
599 const int skip_head = (match_idx != 0) & (stored_tag != cur_tag);
600
601 // Split table writes
602 hash_table[h] = epoch_mark | cur_pos;
603 hash_tags[h] = cur_tag;
604
605 chain_table[cur_pos & ZXC_LZ_WINDOW_MASK] = zxc_chain_delta(cur_pos, match_idx);
606
607 int attempts = p.search_depth;
608
609 // Repeat-offset seed (level-6 parser passes last_off; others pass 0).
610 // Probing the previous offset first often finds the longest match right
611 // away, speeding up the chain walk. It only raises best.len, never lowers
612 // it, so the result is unchanged - this is purely a speed optimization.
613 if (last_off != 0U && last_off >= p.min_offset && last_off <= (uint32_t)ZXC_LZ_MAX_DIST &&
614 last_off <= cur_pos) {
615 const uint8_t* const rep_ref = src + (cur_pos - last_off);
616 if (zxc_le32(rep_ref) == cur_val) {
617 uint32_t mlen = sizeof(uint32_t);
618 const uint8_t* const limit_8 = iend - sizeof(uint64_t);
619 while (ip + mlen < limit_8) {
620 const uint64_t diff = zxc_le64(ip + mlen) ^ zxc_le64(rep_ref + mlen);
621 if (diff == 0) {
622 mlen += sizeof(uint64_t);
623 } else {
624 mlen += (uint32_t)(zxc_ctz64(diff) >> 3);
625 goto _rep_done;
626 }
627 }
628 while (ip + mlen < iend && rep_ref[mlen] == ip[mlen]) mlen++;
629 _rep_done:;
630 best.len = mlen;
631 best.ref = rep_ref;
632 if (UNLIKELY(best.len >= (uint32_t)p.sufficient_len || ip + best.len >= iend))
633 goto _finalize_match;
634 }
635 }
636
637 if (match_idx == 0) goto _finalize_match;
638
639 // Optimization: If head tag doesn't match, advance immediately without loading the first
640 // mismatch.
641 if (skip_head) {
642 const uint16_t delta = chain_table[match_idx & ZXC_LZ_WINDOW_MASK];
643 const uint32_t next_idx = match_idx - delta;
644 match_idx = (delta != 0) ? next_idx : 0;
645 attempts--;
646 }
647
648 while (match_idx > 0) {
649 if (UNLIKELY(attempts-- < 0 || cur_pos - match_idx > ZXC_LZ_MAX_DIST)) break;
650 const uint8_t* ref = src + match_idx;
651
652 // Load the next chain link early (before the compare) so its address
653 // resolves while we prefetch. The prefetch aims at the next gate for
654 // the current best.len; a longer match found here moves that gate.
655 const uint16_t delta = chain_table[match_idx & ZXC_LZ_WINDOW_MASK];
656 const uint32_t next_idx = match_idx - delta;
657 ZXC_PREFETCH_READ(src + next_idx + best.len - 3);
658
659 // Gate first: most candidates share the head and fail on bytes
660 // [best.len-3, best.len], which a longer match must also cover.
661 const int should_compare = (cur_pos - match_idx) >= p.min_offset &&
662 zxc_le32(ref + best.len - 3) == zxc_le32(ip + best.len - 3) &&
663 zxc_le32(ref) == cur_val;
664
665 if (should_compare) {
666 uint32_t mlen = sizeof(uint32_t); // We already know the first 4 bytes match
667
668 // Fast path: Scalar 64-bit comparison for short matches (=< 64 bytes)
669 // Most matches are short, so this avoids SIMD overhead for common cases
670 const uint8_t* limit_8 = iend - sizeof(uint64_t);
671 const uint8_t* scalar_limit = ip + mlen + 64;
672 if (scalar_limit > limit_8) scalar_limit = limit_8;
673
674 while (ip + mlen < scalar_limit) {
675 uint64_t diff = zxc_le64(ip + mlen) ^ zxc_le64(ref + mlen);
676 if (diff == 0)
677 mlen += sizeof(uint64_t);
678 else {
679 mlen += (uint32_t)zxc_ctz64(diff) >> 3;
680 goto _match_len_done;
681 }
682 }
683
684 // Long match path: Use SIMD for matches exceeding 64 bytes
685#if defined(ZXC_USE_AVX512)
686 const uint8_t* limit_64 = iend - 64;
687 while (ip + mlen < limit_64) {
688 const __m512i v_src = _mm512_loadu_si512((const void*)(ip + mlen));
689 const __m512i v_ref = _mm512_loadu_si512((const void*)(ref + mlen));
690 const __mmask64 mask = _mm512_cmpeq_epi8_mask(v_src, v_ref);
691 if (mask == 0xFFFFFFFFFFFFFFFF)
692 mlen += 64;
693 else {
694 mlen += (uint32_t)zxc_ctz64(~mask);
695 goto _match_len_done;
696 }
697 }
698#elif defined(ZXC_USE_AVX2)
699 const uint8_t* limit_32 = iend - 32;
700 while (ip + mlen < limit_32) {
701 const __m256i v_src = _mm256_loadu_si256((const __m256i*)(ip + mlen));
702 const __m256i v_ref = _mm256_loadu_si256((const __m256i*)(ref + mlen));
703 const __m256i v_cmp = _mm256_cmpeq_epi8(v_src, v_ref);
704 const uint32_t mask = (uint32_t)_mm256_movemask_epi8(v_cmp);
705 if (mask == 0xFFFFFFFF)
706 mlen += 32;
707 else {
708 mlen += (uint32_t)zxc_ctz32(~mask);
709 goto _match_len_done;
710 }
711 }
712#elif defined(ZXC_USE_SSE2)
713 const uint8_t* limit_16 = iend - 16;
714 while (ip + mlen < limit_16) {
715 const __m128i v_src = _mm_loadu_si128((const __m128i*)(ip + mlen));
716 const __m128i v_ref = _mm_loadu_si128((const __m128i*)(ref + mlen));
717 const __m128i v_cmp = _mm_cmpeq_epi8(v_src, v_ref);
718 const uint32_t mask = (uint32_t)_mm_movemask_epi8(v_cmp);
719 if (mask == 0xFFFFU)
720 mlen += 16;
721 else {
722 // mask != 0xFFFF => a differing byte exists in bits 0..15,
723 // so the lowest set bit of ~mask lies in that range.
724 mlen += (uint32_t)zxc_ctz32(~mask);
725 goto _match_len_done;
726 }
727 }
728#elif defined(ZXC_USE_NEON64)
729 {
730 const uint8_t* limit_32 = iend - 32;
731 while (ip + mlen < limit_32) {
732 const uint8x16_t s0 = vld1q_u8(ip + mlen);
733 const uint8x16_t r0 = vld1q_u8(ref + mlen);
734 const uint8x16_t c0 = vceqq_u8(s0, r0);
735 const uint64_t m0 = vget_lane_u64(
736 vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(c0), 4)), 0);
737 if (UNLIKELY(m0 != ~(uint64_t)0)) {
738 mlen += (uint32_t)(zxc_ctz64(~m0) >> 2);
739 goto _match_len_done;
740 }
741 const uint8x16_t s1 = vld1q_u8(ip + mlen + 16);
742 const uint8x16_t r1 = vld1q_u8(ref + mlen + 16);
743 const uint8x16_t c1 = vceqq_u8(s1, r1);
744 const uint64_t m1 = vget_lane_u64(
745 vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(c1), 4)), 0);
746 if (UNLIKELY(m1 != ~(uint64_t)0)) {
747 mlen += 16 + (uint32_t)(zxc_ctz64(~m1) >> 2);
748 goto _match_len_done;
749 }
750 mlen += 32;
751 }
752 if (ip + mlen < iend - 16) {
753 const uint8x16_t v_src = vld1q_u8(ip + mlen);
754 const uint8x16_t v_ref = vld1q_u8(ref + mlen);
755 const uint8x16_t v_cmp = vceqq_u8(v_src, v_ref);
756 const uint64_t mask = vget_lane_u64(
757 vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(v_cmp), 4)), 0);
758 if (LIKELY(mask == ~(uint64_t)0))
759 mlen += 16;
760 else {
761 mlen += (uint32_t)(zxc_ctz64(~mask) >> 2);
762 goto _match_len_done;
763 }
764 }
765 }
766#elif defined(ZXC_USE_NEON32)
767 {
768 const uint8_t* limit_16 = iend - 16;
769 while (ip + mlen < limit_16) {
770 const uint8x16_t v_src = vld1q_u8(ip + mlen);
771 const uint8x16_t v_ref = vld1q_u8(ref + mlen);
772 const uint8x16_t v_cmp = vceqq_u8(v_src, v_ref);
773 uint8x8_t p1 = vpmin_u8(vget_low_u8(v_cmp), vget_high_u8(v_cmp));
774 uint8x8_t p2 = vpmin_u8(p1, p1);
775 uint8x8_t p3 = vpmin_u8(p2, p2);
776 uint8x8_t p4 = vpmin_u8(p3, p3);
777 uint8_t min_val = vget_lane_u8(p4, 0);
778 if (min_val == 0xFF)
779 mlen += 16;
780 else {
781 uint8x16_t v_diff = vmvnq_u8(v_cmp);
782 uint64_t lo =
783 (uint64_t)vgetq_lane_u32(vreinterpretq_u32_u8(v_diff), 0) |
784 ((uint64_t)vgetq_lane_u32(vreinterpretq_u32_u8(v_diff), 1) << 32);
785 if (lo != 0)
786 mlen += (zxc_ctz64(lo) >> 3);
787 else
788 mlen +=
789 8 + (zxc_ctz64(
790 (uint64_t)vgetq_lane_u32(vreinterpretq_u32_u8(v_diff), 2) |
791 ((uint64_t)vgetq_lane_u32(vreinterpretq_u32_u8(v_diff), 3)
792 << 32)) >>
793 3);
794 goto _match_len_done;
795 }
796 }
797 }
798#endif
799 while (ip + mlen < limit_8) {
800 const uint64_t diff = zxc_le64(ip + mlen) ^ zxc_le64(ref + mlen);
801 if (diff == 0)
802 mlen += sizeof(uint64_t);
803 else {
804 mlen += (uint32_t)zxc_ctz64(diff) >> 3;
805 goto _match_len_done;
806 }
807 }
808 while (ip + mlen < iend && ref[mlen] == ip[mlen]) mlen++;
809
810 _match_len_done:;
811 const int better = (mlen > best.len);
812 best.len = better ? mlen : best.len;
813 best.ref = better ? ref : best.ref;
814
815 if (UNLIKELY(best.len >= (uint32_t)p.sufficient_len || ip + best.len >= iend)) break;
816 }
817
818 match_idx = (delta != 0) ? next_idx : 0;
819 }
820
821_finalize_match:
822 if (best.ref) {
823 // Backtrack to extend match backwards
824 const uint8_t* b_ip = ip;
825 const uint8_t* b_ref = best.ref;
826 while (b_ip > anchor && b_ref > src && b_ip[-1] == b_ref[-1]) {
827 b_ip--;
828 b_ref--;
829 best.len++;
830 best.backtrack++;
831 }
832 best.ref = b_ref;
833 }
834
835 // Lazy: a match two bytes longer at ip+1, or from level 4 three bytes longer
836 // at ip+2, cancels this one.
837 if (p.use_lazy && best.ref && best.len < (uint32_t)p.lazy_len_threshold &&
838 ip + 1 < search_limit) {
839 if (zxc_lazy_probe(src, ip + 1, iend, best.len + 2, hash_table, hash_tags, chain_table,
840 epoch_mark, offset_mask, use_hash5, p) ||
841 (level >= ZXC_LEVEL_BALANCED && ip + 2 < search_limit &&
842 zxc_lazy_probe(src, ip + 2, iend, best.len + 3, hash_table, hash_tags, chain_table,
843 epoch_mark, offset_mask, use_hash5, p)))
844 best.ref = NULL;
845 }
846
847 return best;
848}
849
855static ZXC_ALWAYS_INLINE void zxc_opt_relax(uint32_t* RESTRICT dp, uint16_t* RESTRICT parent_len,
856 uint16_t* RESTRICT parent_off, const size_t p,
857 const size_t L, const uint32_t nxt,
858 const uint16_t off_biased) {
859 if (nxt < dp[p + L]) {
860 dp[p + L] = nxt;
861 parent_len[p + L] = (uint16_t)L;
862 parent_off[p + L] = off_biased;
863 }
864}
865
905// codeql[cpp/unused-static-function]: false positive
907 uint32_t* RESTRICT dp, uint16_t* RESTRICT parent_len, uint16_t* RESTRICT parent_off,
908 const size_t p, size_t L, const size_t L_end, const uint32_t nxt, const uint16_t off_biased) {
909#if defined(ZXC_USE_AVX512) && defined(__AVX512VL__)
910 if (L + 16 <= L_end) {
911 const __m512i v_inc =
912 _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
913 const __m512i v_nxt = _mm512_set1_epi32((int)nxt);
914 const __m256i v_off = _mm256_set1_epi16((int16_t)off_biased);
915 for (; L + 16 <= L_end; L += 16) {
916 const __m512i v_L_lanes = _mm512_add_epi32(v_inc, _mm512_set1_epi32((int)L));
917 const __m512i v_dp = _mm512_loadu_si512((const void*)&dp[p + L]);
918 const __mmask16 m = _mm512_cmplt_epu32_mask(v_nxt, v_dp);
919 _mm512_mask_storeu_epi32(&dp[p + L], m, v_nxt);
920 const __m256i v_L_u16 = _mm512_cvtusepi32_epi16(v_L_lanes);
921 _mm256_mask_storeu_epi16((void*)&parent_len[p + L], m, v_L_u16);
922 _mm256_mask_storeu_epi16((void*)&parent_off[p + L], m, v_off);
923 }
924 }
925#elif defined(ZXC_USE_AVX2)
926 if (L + 8 <= L_end) {
927 const __m256i v_inc = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
928 const __m256i v_nxt = _mm256_set1_epi32((int)nxt);
929 const __m256i v_bias = _mm256_set1_epi32((int)0x80000000);
930 const __m256i v_nxt_b = _mm256_xor_si256(v_nxt, v_bias);
931 const __m128i v_off = _mm_set1_epi16((int16_t)off_biased);
932 for (; L + 8 <= L_end; L += 8) {
933 const __m256i v_L_lanes = _mm256_add_epi32(v_inc, _mm256_set1_epi32((int)L));
934 const __m256i v_dp = _mm256_loadu_si256((const __m256i*)&dp[p + L]);
935 // Unsigned-compare-via-bias trick:
936 // (dp ^ 0x80000000) > (nxt ^ 0x80000000) iff dp > nxt
937 // because XOR with the sign bit maps unsigned ordering to
938 // signed ordering. AVX2 only has signed cmpgt for 32-bit.
939 const __m256i v_dp_b = _mm256_xor_si256(v_dp, v_bias);
940 const __m256i v_mask = _mm256_cmpgt_epi32(v_dp_b, v_nxt_b);
941 const __m256i v_dp_new = _mm256_blendv_epi8(v_dp, v_nxt, v_mask);
942 _mm256_storeu_si256((__m256i*)&dp[p + L], v_dp_new);
943 // Pack 8x int32 mask -> 8x int16 mask with signed saturation:
944 // 0xFFFFFFFF -> 0xFFFF, 0x00000000 -> 0x0000.
945 const __m128i v_mask16 = _mm_packs_epi32(_mm256_castsi256_si128(v_mask),
946 _mm256_extracti128_si256(v_mask, 1));
947 const __m128i v_L_u16 = _mm_packus_epi32(_mm256_castsi256_si128(v_L_lanes),
948 _mm256_extracti128_si256(v_L_lanes, 1));
949 const __m128i v_pl = _mm_loadu_si128((const __m128i*)&parent_len[p + L]);
950 const __m128i v_pl_new = _mm_blendv_epi8(v_pl, v_L_u16, v_mask16);
951 _mm_storeu_si128((__m128i*)&parent_len[p + L], v_pl_new);
952 const __m128i v_po = _mm_loadu_si128((const __m128i*)&parent_off[p + L]);
953 const __m128i v_po_new = _mm_blendv_epi8(v_po, v_off, v_mask16);
954 _mm_storeu_si128((__m128i*)&parent_off[p + L], v_po_new);
955 }
956 }
957#elif defined(ZXC_USE_NEON64) || defined(ZXC_USE_NEON32)
958 if (L + 4 <= L_end) {
959 static const uint32_t k_inc_array[4] = {0, 1, 2, 3};
960 const uint32x4_t v_inc = vld1q_u32(k_inc_array);
961 const uint32x4_t v_nxt = vdupq_n_u32(nxt);
962 const uint16x4_t v_off = vdup_n_u16(off_biased);
963 for (; L + 4 <= L_end; L += 4) {
964 const uint32x4_t v_L_lanes = vaddq_u32(v_inc, vdupq_n_u32((uint32_t)L));
965 const uint32x4_t v_dp = vld1q_u32(&dp[p + L]);
966 const uint32x4_t v_mask = vcgtq_u32(v_dp, v_nxt);
967 vst1q_u32(&dp[p + L], vbslq_u32(v_mask, v_nxt, v_dp));
968 const uint16x4_t v_mask16 = vmovn_u32(v_mask);
969 const uint16x4_t v_L_u16 = vqmovn_u32(v_L_lanes);
970 const uint16x4_t v_pl = vld1_u16(&parent_len[p + L]);
971 vst1_u16(&parent_len[p + L], vbsl_u16(v_mask16, v_L_u16, v_pl));
972 const uint16x4_t v_po = vld1_u16(&parent_off[p + L]);
973 vst1_u16(&parent_off[p + L], vbsl_u16(v_mask16, v_off, v_po));
974 }
975 }
976#elif defined(ZXC_OPT_SSE2)
977 if (L + 4 <= L_end) {
978 const __m128i v_inc = _mm_setr_epi32(0, 1, 2, 3);
979 const __m128i v_nxt = _mm_set1_epi32((int)nxt);
980 const __m128i v_bias = _mm_set1_epi32((int)0x80000000);
981 const __m128i v_nxt_b = _mm_xor_si128(v_nxt, v_bias);
982 const __m128i v_off = _mm_set1_epi16((short)off_biased);
983 for (; L + 4 <= L_end; L += 4) {
984 const __m128i v_L_lanes = _mm_add_epi32(v_inc, _mm_set1_epi32((int)L));
985 const __m128i v_dp = _mm_loadu_si128((const __m128i*)&dp[p + L]);
986 // Unsigned compare via sign-bit bias (SSE2 cmpgt is signed only):
987 // (dp ^ 0x80000000) > (nxt ^ 0x80000000) iff dp > nxt.
988 const __m128i v_dp_b = _mm_xor_si128(v_dp, v_bias);
989 const __m128i v_mask = _mm_cmpgt_epi32(v_dp_b, v_nxt_b);
990 const __m128i v_dp_new = zxc_mm_blendv_epi8_sse2(v_dp, v_nxt, v_mask);
991 _mm_storeu_si128((__m128i*)&dp[p + L], v_dp_new);
992 // Narrow the 4x int32 mask / length lanes to 4x int16 (low 64 bits).
993 // packs: 0xFFFFFFFF -> 0xFFFF, 0 -> 0; packus (SSE2-emulated): u32->u16.
994 const __m128i v_mask16 = _mm_packs_epi32(v_mask, v_mask);
995 const __m128i v_L_u16 = zxc_mm_packus_epi32_sse2(v_L_lanes, v_L_lanes);
996 __m128i v_pl = _mm_loadl_epi64((const __m128i*)&parent_len[p + L]);
997 v_pl = zxc_mm_blendv_epi8_sse2(v_pl, v_L_u16, v_mask16);
998 _mm_storel_epi64((__m128i*)&parent_len[p + L], v_pl);
999 __m128i v_po = _mm_loadl_epi64((const __m128i*)&parent_off[p + L]);
1000 v_po = zxc_mm_blendv_epi8_sse2(v_po, v_off, v_mask16);
1001 _mm_storel_epi64((__m128i*)&parent_off[p + L], v_po);
1002 }
1003 }
1004#endif
1005 // Scalar tail (and full path on archs without SIMD).
1006 // L < L_end <= UINT16_MAX (caller precondition), so the cast is lossless.
1007 for (; L < L_end; L++) zxc_opt_relax(dp, parent_len, parent_off, p, L, nxt, off_biased);
1008 return L;
1009}
1010
1030// codeql[cpp/unused-static-function]: false positive
1031static uint32_t zxc_opt_estimate_lit_bits(const uint8_t* RESTRICT src, const size_t src_sz,
1032 void* RESTRICT scratch) {
1033 if (UNLIKELY(src_sz < ZXC_OPT_LIT_SAMPLE_MIN)) return CHAR_BIT;
1034
1035 uint32_t hist[ZXC_HUF_NUM_SYMBOLS] = {0};
1036 const size_t step =
1037 (src_sz > ZXC_OPT_LIT_SAMPLE_TARGET) ? src_sz / ZXC_OPT_LIT_SAMPLE_TARGET : 1U;
1038 size_t sampled = 0;
1039 for (size_t i = 0; i < src_sz; i += step) {
1040 hist[src[i]]++;
1041 sampled++;
1042 }
1043
1044 uint8_t code_len[ZXC_HUF_NUM_SYMBOLS];
1045 if (UNLIKELY(zxc_huf_build_code_lengths(hist, code_len, scratch,
1047 return CHAR_BIT;
1048
1049 // Sample-weighted sum of code lengths = predicted Huffman bits; divide by
1050 // the sample count for bits/byte, rounded up. The DP is integer, and
1051 // rounding up favours matches over fractional-cost literals.
1052 uint32_t total_bits = 0;
1053 for (int k = 0; k < ZXC_HUF_NUM_SYMBOLS; k++) {
1054 total_bits += hist[k] * (uint32_t)code_len[k];
1055 }
1056 const uint32_t n = (uint32_t)sampled;
1057 const uint32_t avg = (total_bits + n - 1) / n;
1058
1059 // Cap at RAW cost: if Huffman can't beat 8 bits/byte on the sample,
1060 // the encoder will pick RAW anyway and 8 is the actual literal cost.
1061 return (avg < CHAR_BIT) ? avg : CHAR_BIT;
1062}
1063
1109static int zxc_lz77_optimal_parse_spl(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1110 const size_t src_sz, uint32_t* RESTRICT hash_table,
1111 uint8_t* RESTRICT hash_tags, uint16_t* RESTRICT chain_table,
1112 const uint32_t epoch_mark, const uint32_t offset_mask,
1113 const int level, uint8_t* RESTRICT literals,
1114 uint8_t* RESTRICT buf_tokens, uint16_t* RESTRICT buf_offsets,
1115 uint8_t* RESTRICT buf_extras, uint32_t* RESTRICT seq_c_out,
1116 size_t* RESTRICT lit_c_out, size_t* RESTRICT extras_sz_out,
1117 uint16_t* RESTRICT max_offset_out) {
1118 zxc_lz77_params_t lzp_opt = zxc_get_lz77_params(level);
1119 lzp_opt.use_lazy = 0; // guard
1120
1121 // With a dictionary, src = [dict | block]. The DP arrays index from the block
1122 // start, so src_base points at the first block byte for literal copies while
1123 // src stays the match finder's base.
1124 const size_t dict_sz = ctx->dict_size;
1125 const size_t block_sz = src_sz - dict_sz;
1126 const uint8_t* const src_base = src + dict_sz;
1127 const uint8_t* const iend = src + src_sz;
1128
1129 // Block too small for any match: emit all as literals.
1130 if (UNLIKELY(block_sz < ZXC_LZ_SEARCH_MARGIN + 1)) {
1131 if (block_sz > 0) ZXC_MEMCPY(literals, src_base, block_sz);
1132 *lit_c_out = block_sz;
1133 *seq_c_out = 0;
1134 *extras_sz_out = 0;
1135 *max_offset_out = 0;
1136 return 0;
1137 }
1138
1139 const size_t search_limit_pos = block_sz - ZXC_LZ_SEARCH_MARGIN;
1140 const uint8_t* const search_limit = src + search_limit_pos;
1141
1142 // DP arrays carved from ctx->opt_scratch, one allocation reused across
1143 // blocks, each sub-buffer cache-line padded.
1144 //
1145 // dp : (chunk+1) x u32: min cost to reach position p.
1146 // parent_len : (chunk+1) x u16: 0 = literal, >= MIN_MATCH = match.
1147 // parent_off : (chunk+1) x u16: biased match offset (distance-1).
1148 // match_end_bits : one bit per position, set when a match on the chosen
1149 // path ends there - a forward actions[] stack at 1/64
1150 // the cost.
1151 //
1152 // The same buffer doubles as package-merge scratch for the code-length
1153 // builder: that scratch is live before the DP and after the parse is read
1154 // out, never during, so capacity is just the larger of the two.
1155 size_t sz_dp;
1156 size_t sz_pl;
1157 size_t sz_po;
1158 size_t sz_bm;
1159 zxc_opt_dp_sizes(ctx->chunk_size, &sz_dp, &sz_pl, &sz_po, &sz_bm);
1160 const size_t n_bm_words = ZXC_BITMAP_WORDS(ctx->chunk_size + 1);
1161
1162 // Per-block literal cost (sample only block data, not dict prefix):
1163 const uint32_t lit_cost = zxc_opt_estimate_lit_bits(src_base, block_sz, ctx->opt_scratch);
1164
1165 uint32_t* const dp = (uint32_t*)ctx->opt_scratch;
1166 uint16_t* const parent_len = (uint16_t*)(ctx->opt_scratch + sz_dp);
1167 uint16_t* const parent_off = (uint16_t*)(ctx->opt_scratch + sz_dp + sz_pl);
1168 uint64_t* const match_end_bits = (uint64_t*)(ctx->opt_scratch + sz_dp + sz_pl + sz_po);
1169
1170 dp[0] = 0;
1171 ZXC_MEMSET(dp + 1, 0xFF, block_sz * sizeof(uint32_t));
1172 ZXC_MEMSET(match_end_bits, 0, sz_bm);
1173
1174 // Forward DP: visit every position, update reachable successors.
1175 // `skip_until` suppresses find_best_match strictly inside the last long
1176 // match - the transition from its start already covers dp[p+1..p+L], and
1177 // re-searching there is what makes the parser quadratic on repetitive data.
1178 size_t skip_until = 0;
1179 // Rolling repeat-offset seed for find_best_match
1180 uint32_t last_off = 0;
1181 // Previous matched position and the length relaxed from it.
1182 size_t prev_p = 0;
1183 size_t prev_len = 0;
1184 for (size_t p = 0; p < search_limit_pos; p++) {
1185 if (UNLIKELY(dp[p] == UINT32_MAX)) continue;
1186
1187 // Literal transition.
1188 const uint32_t lit_next = dp[p] + lit_cost;
1189 if (lit_next < dp[p + 1]) {
1190 dp[p + 1] = lit_next;
1191 parent_len[p + 1] = 0;
1192 }
1193
1194 if (p < skip_until) continue;
1195
1196 // Match transition: no lazy, no backtrack (anchor=ip). Sub-lengths are
1197 // iterated because any L <= max_L matches at the same offset and may end
1198 // at a more useful DP position. ip is absolute so dict references
1199 // resolve against src.
1200 const uint8_t* ip = src_base + p;
1201 const zxc_match_t m = zxc_lz77_find_best_match(
1202 src, ip, iend, search_limit, /*anchor=*/ip, hash_table, hash_tags, chain_table,
1203 epoch_mark, offset_mask, level, lzp_opt, last_off);
1204
1205 if (m.ref) {
1206 const uint32_t off = (uint32_t)(ip - m.ref);
1207 if (off > 0 && off <= ZXC_LZ_WINDOW_SIZE) {
1208 last_off = off;
1209 const size_t L_max_raw = (m.len > block_sz - p) ? (block_sz - p) : (size_t)m.len;
1210 const size_t L_max = (L_max_raw > UINT16_MAX) ? UINT16_MAX : L_max_raw;
1211
1212 // Cost is piecewise constant in varint segments, so split
1213 // [MIN_MATCH, L_max] into:
1214 // 1. cheap : v < ML_MASK -> base
1215 // 2. varint1 : v in [ML_MASK, ML_MASK + VARINT_1B_LIMIT) -> base + 8
1216 // 3. varint2+: v >= ML_MASK + VARINT_1B_LIMIT -> base + 16, ...
1217 // The first two have a constant nxt and vectorize; the third is
1218 // rare enough to stay scalar.
1219 const uint16_t off_biased = (uint16_t)(off - ZXC_LZ_OFFSET_BIAS);
1220 const size_t L_max_plus = L_max + 1;
1221 const size_t L_cheap_end = ZXC_LZ_MIN_MATCH_LEN + ZXC_TOKEN_ML_MASK;
1222 const size_t L_v1_end = L_cheap_end + ZXC_VARINT_1B_LIMIT;
1223 const uint32_t nxt_cheap = dp[p] + ZXC_OPT_MATCH_COST_BASE;
1224 const uint32_t nxt_v1 = nxt_cheap + CHAR_BIT;
1225
1226 // Covered: each processed position q bounds dp[q+l] by
1227 // dp[q] + cost(l), by relaxing or through its own predecessor.
1228 // With dp[p] >= dp[p-1], length l only wins where cost(l) <
1229 // cost(l+1): the last length of the two classes below
1230 // ZXC_OPT_LONG_MATCH_SKIP. Costs ignore the offset.
1231 const int covered = prev_len > L_max && prev_p + 1 == p && dp[p] >= dp[p - 1];
1232 prev_p = p;
1233 prev_len = L_max;
1234
1235 if (covered) {
1236 if (L_max_plus >= L_cheap_end)
1237 zxc_opt_relax(dp, parent_len, parent_off, p, L_cheap_end - 1, nxt_cheap,
1238 off_biased);
1239 if (L_max_plus >= L_v1_end)
1240 zxc_opt_relax(dp, parent_len, parent_off, p, L_v1_end - 1, nxt_v1,
1241 off_biased);
1242 } else {
1243 // 1. Cheap range.
1245 dp, parent_len, parent_off, p, ZXC_LZ_MIN_MATCH_LEN,
1246 (L_max_plus < L_cheap_end) ? L_max_plus : L_cheap_end, nxt_cheap,
1247 off_biased);
1248
1249 // 2. First varint level (1-byte extension).
1250 if (L < L_max_plus)
1252 dp, parent_len, parent_off, p, L,
1253 (L_max_plus < L_v1_end) ? L_max_plus : L_v1_end, nxt_v1, off_biased);
1254
1255 // 3. Higher varint levels: variable cost, kept scalar.
1256 // Reached only by L >= ML_MASK + 128 + MIN_MATCH, so the
1257 // v >= ML_MASK guard from the original loop is implied.
1258 for (; L < L_max_plus; L++) {
1259 uint32_t cost = ZXC_OPT_MATCH_COST_BASE;
1260 uint32_t v = (uint32_t)(L - ZXC_LZ_MIN_MATCH_LEN) - ZXC_TOKEN_ML_MASK;
1261 cost += CHAR_BIT;
1262 while (v >= 128) {
1263 v >>= 7;
1264 cost += CHAR_BIT;
1265 }
1266 zxc_opt_relax(dp, parent_len, parent_off, p, L, dp[p] + cost, off_biased);
1267 }
1268 }
1269 if (UNLIKELY(L_max >= ZXC_OPT_LONG_MATCH_SKIP)) skip_until = p + L_max - 1;
1270 }
1271 }
1272 }
1273
1274 // Tail (last ZXC_LZ_SEARCH_MARGIN bytes) can only be literals: the match finder
1275 // stops at search_limit so its 8-byte probe reads stay in bounds.
1276 for (size_t p = search_limit_pos; p < block_sz; p++) {
1277 if (UNLIKELY(dp[p] == UINT32_MAX)) continue;
1278 const uint32_t lit_next = dp[p] + lit_cost;
1279 if (lit_next < dp[p + 1]) {
1280 dp[p + 1] = lit_next;
1281 parent_len[p + 1] = 0;
1282 }
1283 }
1284
1285 // Backtrack from src_sz to 0. Only match endpoints are recorded; literals
1286 // are the unmarked runs between them, rebuilt at emission from lit_start,
1287 // so they need no backtrack storage.
1288 {
1289 size_t pos = block_sz;
1290 while (pos > 0) {
1291 const uint32_t L = parent_len[pos];
1292 if (L == 0) {
1293 pos -= 1;
1294 } else {
1295 match_end_bits[pos >> 6] |= (uint64_t)1 << (pos & 63);
1296 pos -= L;
1297 }
1298 }
1299 }
1300
1301 // Forward emission: walk match_end_bits word-by-word, peeling set bits
1302 // with ctzll. Each set bit gives a match endpoint; parent_len/parent_off
1303 // at that position recover (length, offset).
1304 uint32_t seq_c = 0;
1305 size_t lit_c = 0;
1306 size_t extras_sz = 0;
1307 uint16_t max_offset = 0;
1308 size_t lit_start = 0;
1309
1310 for (size_t word_idx = 0; word_idx < n_bm_words; word_idx++) {
1311 uint64_t w = match_end_bits[word_idx];
1312 while (w) {
1313 const size_t pos = (word_idx << 6) + (size_t)zxc_ctz64(w);
1314 w &= w - 1;
1315 const uint32_t L = parent_len[pos];
1316 const uint16_t off_biased = parent_off[pos];
1317 const size_t match_start = pos - L;
1318
1319 const size_t LL = match_start - lit_start;
1320 if (LL > 0) {
1321 ZXC_MEMCPY(literals + lit_c, src_base + lit_start, LL);
1322 lit_c += LL;
1323 }
1324 const uint32_t ll = (uint32_t)LL;
1325 const uint32_t ml = L - ZXC_LZ_MIN_MATCH_LEN;
1326 if (UNLIKELY(!zxc_spl_put_seq(buf_tokens, buf_offsets, buf_extras, &seq_c, &extras_sz,
1327 &max_offset, ll, ml, off_biased)))
1328 return ZXC_ERROR_OVERFLOW;
1329 lit_start = pos;
1330 }
1331 }
1332
1333 // Tail literals after the last match (or all literals if no match).
1334 if (lit_start < block_sz) {
1335 const size_t tail = block_sz - lit_start;
1336 ZXC_MEMCPY(literals + lit_c, src_base + lit_start, tail);
1337 lit_c += tail;
1338 }
1339
1340 *seq_c_out = seq_c;
1341 *lit_c_out = lit_c;
1342 *extras_sz_out = extras_sz;
1343 *max_offset_out = max_offset;
1344 return 0;
1345}
1346
1363static void zxc_lz_seed_dict(const uint8_t* RESTRICT src, const size_t dict_size,
1364 uint32_t* RESTRICT hash_table, uint8_t* RESTRICT hash_tags,
1365 uint16_t* RESTRICT chain_table, const uint32_t epoch_mark,
1366 const uint32_t offset_mask, const int level) {
1367 if (UNLIKELY(dict_size < ZXC_LZ_MIN_MATCH_LEN)) return;
1368
1369 const int use_hash5 = (level >= ZXC_LEVEL_DEFAULT);
1370 const size_t limit = dict_size - (ZXC_LZ_MIN_MATCH_LEN - 1);
1371
1372 // Sparse seeding for the first half, dense for the second half.
1373 // Positions near the end of the dict produce shorter offsets and are
1374 // more likely to yield matches, so they deserve full coverage.
1375 const size_t half = limit / 2;
1376 for (size_t i = 0; i < half; i += 4) {
1377 const uint64_t val8 = zxc_le64(src + i);
1378 const uint32_t h = zxc_hash_func(val8, use_hash5);
1379 const uint32_t cur_pos = (uint32_t)i;
1380
1381 hash_table[h] = epoch_mark | cur_pos;
1382 hash_tags[h] = zxc_hash_tag((uint32_t)val8);
1383 chain_table[cur_pos & ZXC_LZ_WINDOW_MASK] = 0;
1384 }
1385 for (size_t i = half; i < limit; i++) {
1386 const uint64_t val8 = zxc_le64(src + i);
1387 const uint32_t h = zxc_hash_func(val8, use_hash5);
1388 const uint32_t cur_pos = (uint32_t)i;
1389 const uint32_t prev_idx = zxc_epoch_pos(hash_table[h], offset_mask, epoch_mark);
1390
1391 hash_table[h] = epoch_mark | cur_pos;
1392 hash_tags[h] = zxc_hash_tag((uint32_t)val8);
1393 chain_table[cur_pos & ZXC_LZ_WINDOW_MASK] = zxc_chain_delta(cur_pos, prev_idx);
1394 }
1395}
1396
1419static int zxc_encode_block_spl(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1420 const size_t src_sz, uint8_t* RESTRICT dst, size_t dst_cap,
1421 size_t* RESTRICT out_sz) {
1422 if (UNLIKELY(dst_cap < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
1423
1424 const int level = ctx->compression_level;
1425 const size_t dict_sz = ctx->dict_size;
1426
1428 // The floor is a candidate until the block itself clears it.
1429 if (lzp.min_offset > 1 && zxc_block_is_short_dist_bound(src + dict_sz, src_sz - dict_sz))
1430 lzp.min_offset = 1;
1431
1432 ctx->epoch++;
1433 if (UNLIKELY(ctx->epoch >= ctx->max_epoch)) {
1434 ZXC_MEMSET(ctx->hash_table, 0, ZXC_LZ_HASH_SIZE * sizeof(uint32_t));
1435 ZXC_MEMSET(ctx->hash_tags, 0, ZXC_LZ_HASH_SIZE * sizeof(uint8_t));
1436 ctx->epoch = 1;
1437 }
1438 const uint32_t offset_bits = ctx->offset_bits;
1439 const uint32_t offset_mask = ctx->offset_mask;
1440 const uint32_t epoch_mark = ctx->epoch << offset_bits;
1441
1442 if (dict_sz > 0)
1443 zxc_lz_seed_dict(src, dict_sz, ctx->hash_table, ctx->hash_tags, ctx->chain_table,
1444 epoch_mark, offset_mask, level);
1445
1446 const uint8_t* ip = src + dict_sz;
1447 const uint8_t* iend = src + src_sz;
1448 const uint8_t* anchor = ip;
1449 const uint8_t* search_limit = iend - ZXC_LZ_SEARCH_MARGIN;
1450
1451 uint32_t* const hash_table = ctx->hash_table;
1452 uint8_t* const hash_tags = ctx->hash_tags;
1453 uint16_t* const chain_table = ctx->chain_table;
1454 uint8_t* const literals = ctx->literals;
1455 uint8_t* const buf_tokens = ctx->buf_tokens;
1456 uint16_t* const buf_offsets = ctx->buf_offsets;
1457 uint8_t* const buf_extras = ctx->buf_extras;
1458
1459 uint32_t seq_c = 0;
1460 size_t lit_c = 0;
1461 size_t extras_sz = 0;
1462 uint16_t max_offset = 0; // Track max offset for 1-byte/2-byte mode decision
1463
1464 // Level 6+: price-based optimal parser (fills outputs and skips the
1465 // lazy loop + last_lits handling below via `goto parse_done`).
1466 if (level >= ZXC_LEVEL_DENSITY) {
1467 const int rc = zxc_lz77_optimal_parse_spl(
1468 ctx, src, src_sz, hash_table, hash_tags, chain_table, epoch_mark, offset_mask, level,
1469 literals, buf_tokens, buf_offsets, buf_extras, &seq_c, &lit_c, &extras_sz, &max_offset);
1470 if (UNLIKELY(rc != 0)) return rc;
1471 goto parse_done;
1472 }
1473
1474 while (LIKELY(ip < search_limit)) {
1475 const size_t dist = (size_t)(ip - anchor);
1476 size_t step = lzp.step_base + (dist >> lzp.step_shift);
1477 if (UNLIKELY(ip + step >= search_limit)) step = 1;
1478
1479 if (LIKELY(ip + step + sizeof(uint64_t) <= iend)) {
1480 const uint64_t v_next = zxc_le64(ip + step);
1481 // cppcheck-suppress unreadVariable
1482 const uint32_t h_next = zxc_hash_func(v_next, 1);
1483 ZXC_PREFETCH_READ(&hash_tags[h_next]);
1484 ZXC_PREFETCH_READ(&hash_table[h_next]);
1485 }
1486
1487 const zxc_match_t m =
1488 zxc_lz77_find_best_match(src, ip, iend, search_limit, anchor, hash_table, hash_tags,
1489 chain_table, epoch_mark, offset_mask, level, lzp,
1490 /*last_off=*/0U);
1491
1492 if (m.ref) {
1493 ip -= m.backtrack;
1494 const uint32_t ll = (uint32_t)(ip - anchor);
1495 const uint32_t ml = m.len - ZXC_LZ_MIN_MATCH_LEN;
1496 const uint32_t off = (uint32_t)(ip - m.ref);
1497 const uint16_t off_biased = (uint16_t)(off - ZXC_LZ_OFFSET_BIAS);
1498
1499 if (ll > 0) zxc_flush_literals(literals, &lit_c, anchor, ll, iend);
1500
1501 if (UNLIKELY(!zxc_spl_put_seq(buf_tokens, buf_offsets, buf_extras, &seq_c, &extras_sz,
1502 &max_offset, ll, ml, off_biased)))
1503 return ZXC_ERROR_OVERFLOW;
1504
1505 if (m.len > 2 && level > ZXC_LEVEL_BALANCED) {
1506 const uint8_t* match_end = ip + m.len;
1507 if (match_end < iend - 7) {
1508 const uint32_t pos_u = (uint32_t)((match_end - 2) - src);
1509 const uint64_t val_u8 = zxc_le64(match_end - 2);
1510 const uint32_t val_u = (uint32_t)val_u8;
1511 const uint32_t h_u = zxc_hash_func(val_u8, 1);
1512 const uint32_t prev_idx =
1513 zxc_epoch_pos(hash_table[h_u], offset_mask, epoch_mark);
1514 hash_table[h_u] = epoch_mark | pos_u;
1515 hash_tags[h_u] = zxc_hash_tag(val_u);
1516 chain_table[pos_u & ZXC_LZ_WINDOW_MASK] = zxc_chain_delta(pos_u, prev_idx);
1517 }
1518 }
1519
1520 ip += m.len;
1521 anchor = ip;
1522 } else {
1523 ip += step;
1524 }
1525 }
1526
1527 const size_t last_lits = (size_t)(iend - anchor);
1528 if (last_lits > 0) {
1529 ZXC_MEMCPY(literals + lit_c, anchor, last_lits);
1530 lit_c += last_lits;
1531 }
1532
1533parse_done:;
1534 // Per-block match splitting on the parsed block (see zxc_spl_match_split_block).
1535 seq_c = zxc_spl_match_split_block(buf_tokens, buf_offsets, buf_extras, &extras_sz,
1536 ctx->buf_split, ctx->buf_split_hist, seq_c, lzp.split_max);
1537 // Dictionary-table trainer hook: accumulate the REAL post-LZ literal
1538 // frequencies (see zxc_dict_train_huf). Cold path, NULL outside training.
1539 if (UNLIKELY(ctx->lit_freq_acc)) {
1540 for (size_t i = 0; i < lit_c; i++) ctx->lit_freq_acc[literals[i]]++;
1541 }
1542
1543 // --- RLE ANALYSIS ---
1544 size_t rle_size = 0;
1545 int enc_lit = ZXC_SECTION_ENCODING_RAW;
1546 size_t best_j = lit_c;
1547
1548 if (lit_c > 0) {
1549 const uint8_t* p = literals;
1550 const uint8_t* const p_end = literals + lit_c;
1551 const uint8_t* const p_end_4 = p_end - 3; // Safe limit for 4-byte lookahead
1552
1553 while (LIKELY(p < p_end)) {
1554 const uint8_t b = *p;
1555 const uint8_t* run_start = p++;
1556
1557 // Fast run counting with early SIMD exit
1558#if defined(ZXC_USE_AVX512)
1559 const __m512i vb = _mm512_set1_epi8((char)b);
1560 while (p <= p_end - 64) {
1561 const __m512i v = _mm512_loadu_si512((const void*)p);
1562 const __mmask64 mask = _mm512_cmpeq_epi8_mask(v, vb);
1563 if (mask != 0xFFFFFFFFFFFFFFFFULL) {
1564 p += (size_t)zxc_ctz64(~mask);
1565 goto _run_done;
1566 }
1567 p += 64;
1568 }
1569#elif defined(ZXC_USE_AVX2)
1570 const __m256i vb = _mm256_set1_epi8((char)b);
1571 while (p <= p_end - 32) {
1572 const __m256i v = _mm256_loadu_si256((const __m256i*)p);
1573 const uint32_t mask = (uint32_t)_mm256_movemask_epi8(_mm256_cmpeq_epi8(v, vb));
1574 if (mask != 0xFFFFFFFF) {
1575 p += zxc_ctz32(~mask);
1576 goto _run_done;
1577 }
1578 p += 32;
1579 }
1580#elif defined(ZXC_USE_SSE2)
1581 const __m128i vb = _mm_set1_epi8((char)b);
1582 while (p <= p_end - 16) {
1583 const __m128i v = _mm_loadu_si128((const __m128i*)p);
1584 const uint32_t mask = (uint32_t)_mm_movemask_epi8(_mm_cmpeq_epi8(v, vb));
1585 if (mask != 0xFFFFU) {
1586 p += zxc_ctz32(~mask);
1587 goto _run_done;
1588 }
1589 p += 16;
1590 }
1591#elif defined(ZXC_USE_NEON64)
1592 const uint8x16_t vb = vdupq_n_u8(b);
1593 while (p <= p_end - 16) {
1594 const uint8x16_t v = vld1q_u8(p);
1595 const uint8x16_t eq = vceqq_u8(v, vb);
1596 // SHRN nibble-mask: see find_best_match above for rationale.
1597 const uint64_t mask =
1598 vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(eq), 4)), 0);
1599 if (LIKELY(mask == ~(uint64_t)0)) {
1600 p += 16;
1601 } else {
1602 p += (size_t)(zxc_ctz64(~mask) >> 2);
1603 goto _run_done;
1604 }
1605 }
1606#elif defined(ZXC_USE_NEON32)
1607 uint8x16_t vb = vdupq_n_u8(b);
1608 while (p <= p_end - 16) {
1609 uint8x16_t v = vld1q_u8(p);
1610 uint8x16_t eq = vceqq_u8(v, vb);
1611 uint8x16_t not_eq = vmvnq_u8(eq);
1612
1613 // 32-bit ARM NEON doesn't always support vgetq_lane_u64 / vreinterpretq_u64_u8 so
1614 // we treat the 128-bit vector as 4 x 32-bit lanes */
1615 const uint32x4_t neq32 = vreinterpretq_u32_u8(not_eq);
1616 const uint32_t l0 = vgetq_lane_u32(neq32, 0);
1617 const uint32_t l1 = vgetq_lane_u32(neq32, 1);
1618
1619 const uint64_t lo = ((uint64_t)l1 << 32) | l0;
1620 if (lo != 0) {
1621 p += (size_t)(zxc_ctz64(lo) >> 3);
1622 goto _run_done;
1623 }
1624
1625 const uint32_t h0 = vgetq_lane_u32(neq32, 2);
1626 const uint32_t h1 = vgetq_lane_u32(neq32, 3);
1627 const uint64_t hi = ((uint64_t)h1 << 32) | h0;
1628
1629 if (hi != 0) {
1630 p += 8 + (zxc_ctz64(hi) >> 3);
1631 goto _run_done;
1632 }
1633 p += 16;
1634 }
1635#endif
1636 while (p < p_end && *p == b) p++;
1637
1638#if defined(ZXC_USE_AVX512) || defined(ZXC_USE_AVX2) || defined(ZXC_USE_NEON64) || \
1639 defined(ZXC_USE_NEON32) || defined(ZXC_USE_SSE2)
1640 _run_done:;
1641#endif
1642 const size_t run = (size_t)(p - run_start);
1643
1644 if (run >= ZXC_LIT_RLE_RUN_MIN) {
1645 // RLE run: 2 bytes per ZXC_LIT_RLE_RUN_MAX values, then remainder
1646 // Branchless: full_chunks * 2 + remainder handling
1647 const size_t full_chunks = run / ZXC_LIT_RLE_RUN_MAX;
1648 const size_t rem = run - full_chunks * ZXC_LIT_RLE_RUN_MAX; // Avoid modulo
1649 rle_size += full_chunks * 2;
1650 // Remainder: if >= 4 -> 2 bytes (RLE), else 1 + rem (literal)
1651 if (rem >= ZXC_LIT_RLE_RUN_MIN)
1652 rle_size += 2;
1653 else if (rem > 0)
1654 rle_size += 1 + rem;
1655 } else {
1656 // Literal run: scan ahead with fast SIMD lookahead
1657 const uint8_t* lit_start = run_start;
1658
1659#if defined(ZXC_RLE_WIN)
1660 while (p <= p_end_4 - ZXC_RLE_WIN) {
1661 const zxc_rle_mask_t m = zxc_rle_pair_mask(p);
1662 const zxc_rle_mask_t mask = m & (m >> ZXC_RLE_BPB) & (m >> (2 * ZXC_RLE_BPB));
1663 if (LIKELY(mask == 0)) {
1664 p += ZXC_RLE_WIN - 2;
1665 continue;
1666 }
1667 const unsigned rpos = (unsigned)(ZXC_RLE_CTZ(mask) / ZXC_RLE_BPB);
1668 const unsigned rpairs =
1669 (unsigned)(ZXC_RLE_CTZ(~(m >> (rpos * ZXC_RLE_BPB))) / ZXC_RLE_BPB);
1670 if (UNLIKELY(rpos + rpairs >= ZXC_RLE_WIN)) {
1671 p += rpos;
1672 goto _lit_done; /* run may extend past the window */
1673 }
1674 const size_t seg = (size_t)(p + rpos - lit_start);
1675 rle_size += seg + (seg + ZXC_LIT_LEN_MASK) / ZXC_LIT_RUN_MAX;
1676 rle_size += 2; /* run fits one chunk: full_chunks=0, rem>=4 */
1677 p += rpos + rpairs + 1;
1678 lit_start = p;
1679 }
1680#elif defined(ZXC_USE_NEON32)
1681 while (p <= p_end_4 - 16) {
1682 uint8x16_t v0 = vld1q_u8(p);
1683 uint8x16_t v1 = vld1q_u8(p + 1);
1684 const uint8x16_t pe = vceqq_u8(v0, v1);
1685 const uint8x16_t zv = vdupq_n_u8(0);
1686 const uint8x16_t eq =
1687 vandq_u8(pe, vandq_u8(vextq_u8(pe, zv, 1), vextq_u8(pe, zv, 2)));
1688
1689 uint32x4_t eq32 = vreinterpretq_u32_u8(eq);
1690 uint32_t l0 = vgetq_lane_u32(eq32, 0);
1691 uint32_t l1 = vgetq_lane_u32(eq32, 1);
1692 uint64_t lo = ((uint64_t)l1 << 32) | l0;
1693
1694 if (lo != 0) {
1695 p += (zxc_ctz64(lo) >> 3);
1696 goto _lit_done;
1697 }
1698
1699 uint32_t h0 = vgetq_lane_u32(eq32, 2);
1700 uint32_t h1 = vgetq_lane_u32(eq32, 3);
1701 uint64_t hi = ((uint64_t)h1 << 32) | h0;
1702
1703 if (hi != 0) {
1704 p += 8 + (zxc_ctz64(hi) >> 3);
1705 goto _lit_done;
1706 }
1707 p += 14;
1708 }
1709#endif
1710 while (p < p_end_4) {
1711 if (UNLIKELY(p[0] == p[1] && p[1] == p[2] && p[2] == p[3])) break;
1712 p++;
1713 }
1714 if (p >= p_end_4) p = p_end;
1715
1716#if defined(ZXC_USE_AVX512) || defined(ZXC_USE_AVX2) || defined(ZXC_USE_NEON64) || \
1717 defined(ZXC_USE_NEON32) || defined(ZXC_USE_SSE2)
1718 _lit_done:;
1719#endif
1720 const size_t lit_run = (size_t)(p - lit_start);
1721 // 1 header per ZXC_LIT_RUN_MAX bytes + all data bytes
1722 rle_size += lit_run + (lit_run + ZXC_LIT_LEN_MASK) / ZXC_LIT_RUN_MAX;
1723 }
1724 }
1725
1726 // RLE over RAW: space-speed J comparison. The per-level premium
1727 // reproduces the historical margin exactly below ULTRA.
1728 const size_t rle_j = rle_size + ZXC_SS_TAX(lit_c, zxc_ss_prem_rle_q8(level));
1729 if (rle_j < best_j) {
1730 enc_lit = ZXC_SECTION_ENCODING_RLE;
1731 best_j = rle_j;
1732 }
1733 }
1734
1735 // Level >= 6: Huffman as a third literal-encoding candidate. Histogram,
1736 // length-limited code lengths, exact PivCo section size, and switch if its
1737 // J (size + decode tax) beats the current winner's.
1738 uint8_t huf_code_len[ZXC_HUF_NUM_SYMBOLS];
1739 size_t huf_total_size = SIZE_MAX;
1740 uint32_t lit_freq[ZXC_HUF_NUM_SYMBOLS]; /* valid iff huf_total_size != SIZE_MAX */
1741 if (level >= ZXC_LEVEL_DENSITY && lit_c >= ZXC_HUF_MIN_LITERALS) {
1742 uint32_t freq0[ZXC_HUF_NUM_SYMBOLS] = {0};
1743 uint32_t freq1[ZXC_HUF_NUM_SYMBOLS] = {0};
1744 uint32_t freq2[ZXC_HUF_NUM_SYMBOLS] = {0};
1745 uint32_t freq3[ZXC_HUF_NUM_SYMBOLS] = {0};
1746 {
1747 size_t i = 0;
1748 for (; i + 4 <= lit_c; i += 4) {
1749 freq0[literals[i + 0]]++;
1750 freq1[literals[i + 1]]++;
1751 freq2[literals[i + 2]]++;
1752 freq3[literals[i + 3]]++;
1753 }
1754 for (; i < lit_c; i++) freq0[literals[i]]++;
1755 }
1756 uint32_t* const freq = lit_freq;
1757 for (int k = 0; k < ZXC_HUF_NUM_SYMBOLS; k++) {
1758 freq[k] = freq0[k] + freq1[k] + freq2[k] + freq3[k];
1759 }
1760
1761 if (zxc_huf_build_code_lengths(freq, huf_code_len, ctx->opt_scratch,
1762 zxc_huf_enc_max_code_len(level)) == ZXC_OK) {
1763 (void)zxc_huf_nudge_code_lengths(freq, huf_code_len, ctx->opt_scratch,
1764 ctx->opt_scratch_cap, zxc_huf_enc_max_code_len(level));
1765 huf_total_size = zxc_huf_calc_size(freq, huf_code_len, 1);
1766 // Space-speed: the entropy candidate must beat the current winner's
1767 // J, paying its own decode tax over the copy path.
1768 if (huf_total_size != SIZE_MAX) {
1769 const size_t huf_j = huf_total_size + ZXC_SS_TAX(lit_c, zxc_ss_prem_huf_q8(level));
1770 if (huf_j < best_j) {
1771 enc_lit = ZXC_SECTION_ENCODING_HUFFMAN;
1772 best_j = huf_j;
1773 }
1774 }
1775 }
1776 }
1777
1778 // Shared dictionary table (level >= 6, dict with a table): the HUFFMAN
1779 // bitstream minus the 128-byte header, so it stays viable far below
1780 // ZXC_HUF_MIN_LITERALS. A literal without a code drops the candidate.
1781 size_t huf_dict_total_size = SIZE_MAX;
1782#ifndef ZXC_NO_DICT
1783 if (level >= ZXC_LEVEL_DENSITY && ctx->dict_huf_tree_ok && lit_c > 0) {
1784 // The dict candidate runs on sections too small for the per-block
1785 // table, so the histogram may not have been built above.
1786 if (huf_total_size == SIZE_MAX) {
1787 ZXC_MEMSET(lit_freq, 0, sizeof(uint32_t) * ZXC_HUF_NUM_SYMBOLS);
1788 for (size_t i = 0; i < lit_c; i++) lit_freq[literals[i]]++;
1789 }
1790 // zxc_huf_calc_size returns SIZE_MAX for unencodable candidates
1791 // (a literal byte without a code in the shared table).
1792 huf_dict_total_size =
1793 zxc_huf_calc_size_dict(lit_freq, ctx->dict_huf->code_len, &ctx->dict_huf->tree);
1794 if (huf_dict_total_size != SIZE_MAX) {
1795 // Same J rule against the running winner: vs the per-block Huffman
1796 // candidate the equal entropy taxes cancel (pure size comparison),
1797 // while RAW/RLE baselines keep their decode-tax edge.
1798 const size_t huf_dict_j =
1799 huf_dict_total_size + ZXC_SS_TAX(lit_c, zxc_ss_prem_huf_q8(level));
1800 // Last candidate: no need to keep best_j updated past this point.
1801 if (huf_dict_j < best_j) enc_lit = ZXC_SECTION_ENCODING_HUFFMAN_DICT;
1802 }
1803 }
1804#endif
1805
1806 // Level-7 (ULTRA): Huffman-code the token stream with the literal codec -
1807 // tokens are a <= 256-symbol alphabet. Same J rule; the decoder picks the
1808 // path from gh.enc_tok. opt_scratch is free by now.
1809 uint8_t tok_code_len[ZXC_HUF_NUM_SYMBOLS];
1810 uint8_t enc_tok = ZXC_SECTION_ENCODING_RAW;
1811 size_t tok_huf_size = 0;
1812 uint32_t tfreq[ZXC_HUF_NUM_SYMBOLS];
1813 if (level >= ZXC_LEVEL_ULTRA && seq_c >= ZXC_HUF_MIN_LITERALS) {
1814 ZXC_MEMSET(tfreq, 0, sizeof(tfreq)); /* only the ULTRA path reads tfreq */
1815 for (uint32_t i = 0; i < seq_c; i++) tfreq[buf_tokens[i]]++;
1816 if (zxc_huf_build_code_lengths(tfreq, tok_code_len, ctx->opt_scratch,
1817 zxc_huf_enc_max_code_len(level)) == ZXC_OK) {
1818 (void)zxc_huf_nudge_code_lengths(tfreq, tok_code_len, ctx->opt_scratch,
1819 ctx->opt_scratch_cap, zxc_huf_enc_max_code_len(level));
1820 tok_huf_size = zxc_huf_calc_size(tfreq, tok_code_len, 1);
1821 // Space-speed J comparison (this path is ULTRA-only): the PivCo
1822 // token section pays the same decode tax as PivCo literals.
1823 if (tok_huf_size != SIZE_MAX &&
1824 tok_huf_size + ZXC_SS_TAX((size_t)seq_c, zxc_ss_prem_huf_q8(level)) < (size_t)seq_c)
1825 enc_tok = ZXC_SECTION_ENCODING_HUFFMAN;
1826 }
1827 }
1828
1829 zxc_block_header_t bh = {.block_type = ZXC_BLOCK_SPL};
1830 uint8_t* const p = dst + ZXC_BLOCK_HEADER_SIZE;
1831 size_t rem = dst_cap - ZXC_BLOCK_HEADER_SIZE;
1832
1833 const int use_8bit_off = (max_offset <= 255) ? 1 : 0;
1834 const size_t off_stream_size = use_8bit_off ? seq_c : (seq_c * 2);
1835
1836 const zxc_gnr_header_t gh = {.n_sequences = seq_c,
1837 .n_literals = (uint32_t)lit_c,
1838 .enc_lit = (uint8_t)enc_lit,
1839 .enc_tok = enc_tok,
1840 .enc_mlen = 0,
1841 .enc_off = (uint8_t)use_8bit_off};
1842
1843 const size_t sz_lit = (enc_lit == ZXC_SECTION_ENCODING_RLE) ? rle_size
1844 : (enc_lit == ZXC_SECTION_ENCODING_HUFFMAN) ? huf_total_size
1845 : (enc_lit == ZXC_SECTION_ENCODING_HUFFMAN_DICT) ? huf_dict_total_size
1846 : lit_c;
1847 const size_t sz_tok = (enc_tok == ZXC_SECTION_ENCODING_HUFFMAN) ? tok_huf_size : seq_c;
1848 const size_t sz_off = off_stream_size;
1849 const size_t sz_ext = extras_sz;
1850
1851 const int ghs = zxc_write_spl_header_and_desc(p, rem, &gh, (uint32_t)sz_lit, (uint32_t)sz_tok);
1852 if (UNLIKELY(ghs < 0)) return ghs;
1853
1854 uint8_t* p_curr = p + ghs;
1855 rem -= (size_t)ghs;
1856
1857 if (UNLIKELY(rem < sz_lit)) return ZXC_ERROR_DST_TOO_SMALL;
1858
1859 if (enc_lit == ZXC_SECTION_ENCODING_HUFFMAN) {
1860 const int written =
1861 zxc_huf_encode_section(literals, lit_c, lit_freq, huf_code_len, p_curr, rem);
1862 if (UNLIKELY(written < 0)) return written;
1863 if (UNLIKELY((size_t)written != huf_total_size)) return ZXC_ERROR_DST_TOO_SMALL;
1864 p_curr += written;
1865#ifndef ZXC_NO_DICT
1866 } else if (enc_lit == ZXC_SECTION_ENCODING_HUFFMAN_DICT) {
1867 const int written =
1868 zxc_huf_encode_section_dict(literals, lit_c, lit_freq, ctx->dict_huf->code_len,
1869 &ctx->dict_huf->tree, ctx->dict_huf->codes, p_curr, rem);
1870 if (UNLIKELY(written < 0)) return written;
1871 if (UNLIKELY((size_t)written != huf_dict_total_size)) return ZXC_ERROR_DST_TOO_SMALL;
1872 p_curr += written;
1873#endif
1874 } else if (enc_lit == ZXC_SECTION_ENCODING_RLE) {
1875 // Write RLE - optimized single-pass encoding
1876 const uint8_t* lit_ptr = literals;
1877 const uint8_t* const lit_end = literals + lit_c;
1878
1879 while (lit_ptr < lit_end) {
1880 uint8_t b = *lit_ptr;
1881 const uint8_t* run_start = lit_ptr++;
1882
1883 while (lit_ptr < lit_end && *lit_ptr == b) lit_ptr++;
1884 size_t run = (size_t)(lit_ptr - run_start);
1885
1886 if (run >= ZXC_LIT_RLE_RUN_MIN) {
1887 // RLE runs: emit 2-byte tokens (header + value)
1888 while (run >= ZXC_LIT_RLE_RUN_MIN) {
1889 size_t chunk = (run > ZXC_LIT_RLE_RUN_MAX) ? ZXC_LIT_RLE_RUN_MAX : run;
1890 *p_curr++ = (uint8_t)(ZXC_LIT_RLE_FLAG | (chunk - ZXC_LIT_RLE_RUN_MIN));
1891 *p_curr++ = b;
1892 run -= chunk;
1893 }
1894 // Leftover < 4 bytes: emit as literal
1895 if (run > 0) {
1896 *p_curr++ = (uint8_t)(run - 1);
1897 ZXC_MEMCPY(p_curr, lit_ptr - run, run);
1898 p_curr += run;
1899 }
1900 } else {
1901 // Literal run: scan ahead to find next RLE opportunity
1902 const uint8_t* lit_run_start = run_start;
1903
1904 while (lit_ptr < lit_end) {
1905 if (UNLIKELY(lit_ptr + 3 < lit_end && lit_ptr[0] == lit_ptr[1] &&
1906 lit_ptr[1] == lit_ptr[2] && lit_ptr[2] == lit_ptr[3])) {
1907 break;
1908 }
1909 lit_ptr++;
1910 }
1911
1912 size_t lit_run = (size_t)(lit_ptr - lit_run_start);
1913 const uint8_t* src_ptr = lit_run_start;
1914
1915 // Emit literal chunks (ZXC_LIT_RUN_MAX bytes each at most)
1916 while (lit_run > 0) {
1917 size_t chunk = (lit_run > ZXC_LIT_RUN_MAX) ? ZXC_LIT_RUN_MAX : lit_run;
1918 *p_curr++ = (uint8_t)(chunk - 1);
1919 ZXC_MEMCPY(p_curr, src_ptr, chunk);
1920 p_curr += chunk;
1921 src_ptr += chunk;
1922 lit_run -= chunk;
1923 }
1924 }
1925 }
1926 } else {
1927 ZXC_MEMCPY(p_curr, literals, lit_c);
1928 p_curr += lit_c;
1929 }
1930 rem -= sz_lit;
1931
1932 if (UNLIKELY(rem < sz_tok)) return ZXC_ERROR_DST_TOO_SMALL;
1933
1934 if (enc_tok == ZXC_SECTION_ENCODING_HUFFMAN) {
1935 const int written =
1936 zxc_huf_encode_section(buf_tokens, seq_c, tfreq, tok_code_len, p_curr, rem);
1937 if (UNLIKELY(written < 0)) return written;
1938 if (UNLIKELY((size_t)written != tok_huf_size)) return ZXC_ERROR_DST_TOO_SMALL;
1939 p_curr += written;
1940 } else {
1941 ZXC_MEMCPY(p_curr, buf_tokens, seq_c);
1942 p_curr += seq_c;
1943 }
1944 rem -= sz_tok;
1945
1946 if (UNLIKELY(rem < sz_off)) return ZXC_ERROR_DST_TOO_SMALL;
1947
1948 if (use_8bit_off) {
1949 // Write 1-byte offsets - unroll for better throughput
1950 uint32_t i = 0;
1951 for (; i + 8 <= seq_c; i += 8) {
1952 p_curr[0] = (uint8_t)buf_offsets[i + 0];
1953 p_curr[1] = (uint8_t)buf_offsets[i + 1];
1954 p_curr[2] = (uint8_t)buf_offsets[i + 2];
1955 p_curr[3] = (uint8_t)buf_offsets[i + 3];
1956 p_curr[4] = (uint8_t)buf_offsets[i + 4];
1957 p_curr[5] = (uint8_t)buf_offsets[i + 5];
1958 p_curr[6] = (uint8_t)buf_offsets[i + 6];
1959 p_curr[7] = (uint8_t)buf_offsets[i + 7];
1960 p_curr += 8;
1961 }
1962 for (; i < seq_c; i++) {
1963 *p_curr++ = (uint8_t)buf_offsets[i];
1964 }
1965 } else {
1966 // Write 2-byte offsets in little-endian order
1967#ifdef ZXC_BIG_ENDIAN
1968 for (uint32_t i = 0; i < seq_c; i++) {
1969 zxc_store_le16(p_curr, buf_offsets[i]);
1970 p_curr += sizeof(uint16_t);
1971 }
1972#else
1973 ZXC_MEMCPY(p_curr, buf_offsets, seq_c * sizeof(uint16_t));
1974 p_curr += seq_c * sizeof(uint16_t);
1975#endif
1976 }
1977 rem -= sz_off;
1978
1979 // The sections behind the literals must total ZXC_BLOCK_LIT_SLACK bytes so
1980 // the decoder's literal wild-copy can overshoot. Tokens and offsets alone
1981 // clear it from 16 sequences on, so pad is 0 on any real block. It rides
1982 // inside the extras section, which the decoder sizes from the payload
1983 // residue - hence no wire field.
1984 const size_t behind_lit = sz_tok + sz_off + sz_ext;
1985 const size_t pad = (behind_lit < ZXC_BLOCK_LIT_SLACK) ? ZXC_BLOCK_LIT_SLACK - behind_lit : 0;
1986
1987 if (UNLIKELY(rem < sz_ext + pad)) return ZXC_ERROR_DST_TOO_SMALL;
1988
1989 ZXC_MEMCPY(p_curr, buf_extras, extras_sz);
1990 p_curr += extras_sz;
1991
1992 ZXC_MEMSET(p_curr, 0, pad);
1993 p_curr += pad;
1994
1995 bh.comp_size = (uint32_t)(p_curr - (dst + ZXC_BLOCK_HEADER_SIZE));
1996 const int hw = zxc_write_block_header(dst, dst_cap, &bh);
1997 if (UNLIKELY(hw < 0)) return hw;
1998
1999 // Checksum will be appended by the wrapper
2000 *out_sz = ZXC_BLOCK_HEADER_SIZE + bh.comp_size;
2001 return ZXC_OK;
2002}
2003
2023static int zxc_encode_block_pak(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
2024 const size_t src_sz, uint8_t* RESTRICT dst, const size_t dst_cap,
2025 size_t* RESTRICT const out_sz) {
2026 if (UNLIKELY(dst_cap < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
2027
2028 const int level = ctx->compression_level;
2029 const size_t dict_sz = ctx->dict_size;
2030
2032 // The floor is a candidate until the block itself clears it.
2033 if (lzp.min_offset > 1 && zxc_block_is_short_dist_bound(src + dict_sz, src_sz - dict_sz))
2034 lzp.min_offset = 1;
2035
2036 ctx->epoch++;
2037 if (UNLIKELY(ctx->epoch >= ctx->max_epoch)) {
2038 ZXC_MEMSET(ctx->hash_table, 0, ZXC_LZ_HASH_SIZE * sizeof(uint32_t));
2039 ZXC_MEMSET(ctx->hash_tags, 0, ZXC_LZ_HASH_SIZE * sizeof(uint8_t));
2040 ctx->epoch = 1;
2041 }
2042 const uint32_t offset_bits = ctx->offset_bits;
2043 const uint32_t offset_mask = ctx->offset_mask;
2044 const uint32_t epoch_mark = ctx->epoch << offset_bits;
2045
2046 if (dict_sz > 0)
2047 zxc_lz_seed_dict(src, dict_sz, ctx->hash_table, ctx->hash_tags, ctx->chain_table,
2048 epoch_mark, offset_mask, level);
2049
2050 const uint8_t* ip = src + dict_sz;
2051 const uint8_t* iend = src + src_sz;
2052 const uint8_t* anchor = ip;
2053 const uint8_t* search_limit = iend - ZXC_LZ_SEARCH_MARGIN;
2054
2055 uint32_t* const hash_table = ctx->hash_table;
2056 uint8_t* const hash_tags = ctx->hash_tags;
2057 uint8_t* const buf_extras = ctx->buf_extras;
2058 uint16_t* const chain_table = ctx->chain_table;
2059 uint8_t* const literals = ctx->literals;
2060 uint32_t* const buf_sequences = ctx->buf_sequences;
2061
2062 uint32_t seq_c = 0;
2063 size_t extras_c = 0;
2064 size_t lit_c = 0;
2065
2066 while (LIKELY(ip < search_limit)) {
2067 size_t dist = (size_t)(ip - anchor);
2068 size_t step = lzp.step_base + (dist >> lzp.step_shift);
2069 if (UNLIKELY(ip + step >= search_limit)) step = 1;
2070
2071 ZXC_PREFETCH_READ(ip + step * 4 + ZXC_CACHE_LINE_SIZE);
2072
2073 if (LIKELY(ip + step + sizeof(uint64_t) <= iend)) {
2074 const uint64_t v_next = zxc_le64(ip + step);
2075 // cppcheck-suppress unreadVariable
2076 const uint32_t h_next = zxc_hash_func(v_next, 0);
2077 ZXC_PREFETCH_READ(&hash_tags[h_next]);
2078 ZXC_PREFETCH_READ(&hash_table[h_next]);
2079 }
2080
2081 const zxc_match_t m =
2082 zxc_lz77_find_best_match(src, ip, iend, search_limit, anchor, hash_table, hash_tags,
2083 chain_table, epoch_mark, offset_mask, level, lzp,
2084 /*last_off=*/0U);
2085
2086 if (m.ref) {
2087 ip -= m.backtrack;
2088 const uint32_t ll = (uint32_t)(ip - anchor);
2089 const uint32_t ml = m.len - ZXC_LZ_MIN_MATCH_LEN;
2090 const uint32_t off = (uint32_t)(ip - m.ref);
2091
2092 if (ll > 0) zxc_flush_literals(literals, &lit_c, anchor, ll, iend);
2093
2094 const uint32_t ll_write = (ll >= ZXC_SEQ_LL_MASK) ? ZXC_SEQ_LL_MASK : ll;
2095 const uint32_t ml_write = (ml >= ZXC_SEQ_ML_MASK) ? ZXC_SEQ_ML_MASK : ml;
2096 const uint32_t seq_val = (ll_write << ZXC_SEQ_LL_SHIFT) |
2097 (ml_write << ZXC_SEQ_ML_SHIFT) |
2099 buf_sequences[seq_c] = seq_val;
2100 seq_c++;
2101
2102 if (UNLIKELY(!zxc_emit_extra(buf_extras, &extras_c, ll, ZXC_SEQ_LL_MASK) ||
2103 !zxc_emit_extra(buf_extras, &extras_c, ml, ZXC_SEQ_ML_MASK)))
2104 return ZXC_ERROR_OVERFLOW;
2105
2106 ip += m.len;
2107 anchor = ip;
2108 } else {
2109 ip += step;
2110 }
2111 }
2112
2113 const size_t last_lits = (size_t)(iend - anchor);
2114 if (last_lits > 0) {
2115 ZXC_MEMCPY(literals + lit_c, anchor, last_lits);
2116 lit_c += last_lits;
2117 }
2118
2119 zxc_block_header_t bh = {.block_type = ZXC_BLOCK_PAK};
2120 uint8_t* const p = dst + ZXC_BLOCK_HEADER_SIZE;
2121 size_t rem = dst_cap - ZXC_BLOCK_HEADER_SIZE;
2122
2123 const zxc_gnr_header_t gh = {.n_sequences = seq_c,
2124 .n_literals = (uint32_t)lit_c,
2125 .enc_lit = ZXC_SECTION_ENCODING_RAW,
2126 .enc_tok = 0,
2127 .enc_mlen = 0,
2128 .enc_off = 0};
2129
2130 const int ghs = zxc_write_pak_header(p, rem, &gh);
2131 if (UNLIKELY(ghs < 0)) return ghs;
2132
2133 uint8_t* p_curr = p + ghs;
2134 rem -= (size_t)ghs;
2135
2136 const size_t sz_lit = lit_c;
2137 const size_t sz_seq = seq_c * sizeof(uint32_t);
2138 const size_t sz_ext = extras_c;
2139
2140 // See the SPL twin. PAK literals are always RAW, so the slack always
2141 // matters here.
2142 const size_t behind_lit = sz_seq + sz_ext;
2143 const size_t pad = (behind_lit < ZXC_BLOCK_LIT_SLACK) ? ZXC_BLOCK_LIT_SLACK - behind_lit : 0;
2144
2145 if (UNLIKELY(rem < sz_lit + sz_seq + sz_ext + pad)) return ZXC_ERROR_DST_TOO_SMALL;
2146
2147 ZXC_MEMCPY(p_curr, literals, lit_c);
2148 p_curr += lit_c;
2149
2150 // Write sequences in little-endian order
2151#ifdef ZXC_BIG_ENDIAN
2152 for (uint32_t i = 0; i < seq_c; i++) {
2153 zxc_store_le32(p_curr, buf_sequences[i]);
2154 p_curr += sizeof(uint32_t);
2155 }
2156#else
2157 ZXC_MEMCPY(p_curr, buf_sequences, sz_seq);
2158 p_curr += sz_seq;
2159#endif
2160
2161 // --- WRITE EXTRAS ---
2162 ZXC_MEMCPY(p_curr, buf_extras, sz_ext);
2163 p_curr += sz_ext;
2164
2165 ZXC_MEMSET(p_curr, 0, pad);
2166 p_curr += pad;
2167
2168 bh.comp_size = (uint32_t)(p_curr - (dst + ZXC_BLOCK_HEADER_SIZE));
2169 const int hw = zxc_write_block_header(dst, dst_cap, &bh);
2170 if (UNLIKELY(hw < 0)) return hw;
2171
2172 // Checksum will be appended by the wrapper
2173 *out_sz = ZXC_BLOCK_HEADER_SIZE + bh.comp_size;
2174 return ZXC_OK;
2175}
2176
2192static int zxc_encode_block_raw(const uint8_t* RESTRICT src, const size_t src_sz,
2193 uint8_t* RESTRICT const dst, const size_t dst_cap,
2194 size_t* RESTRICT const out_sz) {
2195 if (UNLIKELY(dst_cap < ZXC_BLOCK_HEADER_SIZE + src_sz)) return ZXC_ERROR_DST_TOO_SMALL;
2196
2198 bh.block_type = ZXC_BLOCK_RAW;
2199 bh.block_flags = 0; // Checksum flag moved to file header
2200 bh.reserved = 0;
2201 bh.comp_size = (uint32_t)src_sz;
2202
2203 const int hw = zxc_write_block_header(dst, dst_cap, &bh);
2204 if (UNLIKELY(hw < 0)) return hw;
2205
2206 ZXC_MEMCPY(dst + ZXC_BLOCK_HEADER_SIZE, src, src_sz);
2207
2208 // Checksum will be appended by the wrapper
2209 *out_sz = ZXC_BLOCK_HEADER_SIZE + src_sz;
2210 return ZXC_OK;
2211}
2212
2222// cppcheck-suppress unusedFunction
2223int zxc_compress_chunk_wrapper(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT chunk,
2224 const size_t src_sz, uint8_t* RESTRICT dst, const size_t dst_cap,
2225 const uint64_t block_index) {
2226 if (UNLIKELY(dst_cap < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
2227
2228 const size_t dict_sz = ctx->dict_size;
2229 const size_t block_sz = src_sz - dict_sz;
2230 const uint8_t* block_data = chunk + dict_sz;
2231 size_t w = 0;
2232 int res = ZXC_OK;
2233
2234 if (ctx->compression_level <= 2)
2235 res = zxc_encode_block_pak(ctx, chunk, src_sz, dst, dst_cap, &w);
2236 else
2237 res = zxc_encode_block_spl(ctx, chunk, src_sz, dst, dst_cap, &w);
2238
2239 // Check expansion against block data size (excluding dict prefix).
2240 if (UNLIKELY(res != ZXC_OK || w >= block_sz)) {
2241 res = zxc_encode_block_raw(block_data, block_sz, dst, dst_cap, &w);
2242 if (UNLIKELY(res != ZXC_OK)) return res;
2243 }
2244
2245 if (ctx->checksum_enabled) {
2246 if (UNLIKELY(w + ZXC_BLOCK_CHECKSUM_SIZE > dst_cap)) return ZXC_ERROR_OVERFLOW;
2247
2248 zxc_store_le32(dst + w,
2249 zxc_checksum(block_data, block_sz, block_index, ZXC_CHECKSUM_RAPIDHASH));
2251 }
2252
2253 return (int)w;
2254}
@ ZXC_ERROR_OVERFLOW
Buffer overflow detected during processing.
Definition zxc_error.h:58
@ ZXC_ERROR_DST_TOO_SMALL
Destination buffer too small.
Definition zxc_error.h:44
@ ZXC_OK
Success (no error).
Definition zxc_error.h:38
#define ZXC_SPL_INLINE_ML_CODE
Longest match length code (length minus ZXC_LZ_MIN_MATCH_LEN) a SPL token carries inline; the code ab...
#define ZXC_LIT_LEN_MASK
Mask to extract the run/literal length (lower 7 bits).
#define ZXC_SEQ_OFF_MASK
Mask to extract Offset from a PAK sequence.
#define ZXC_BITMAP_WORDS(n_bits)
Number of uint64_t words needed to hold a bitmap of n_bits.
#define ZXC_ALWAYS_INLINE
Forces a function to be inlined (fallback for non-GCC/Clang/MSVC compilers).
#define ZXC_LIT_RLE_RUN_MIN
Shortest run worth an RLE token: a length field of 0 means this many bytes.
#define ZXC_SEQ_ML_MASK
Mask to extract Match Length from a PAK sequence.
#define ZXC_CHECKSUM_RAPIDHASH
Checksum algorithm id for RapidHash (default, sole implementation).
#define ZXC_SEQ_ML_SHIFT
Shift of the Match Length field: just above the offset.
#define ZXC_LZ_MAX_DIST
Maximum allowed offset distance.
#define ZXC_MAX_VARINT_VALUE
Maximum legitimate value a varint can decode to.
#define ZXC_SEQ_LL_SHIFT
Shift of the Literal Length field: the top byte of the word.
#define ZXC_LZ_SEARCH_MARGIN
Bytes at the block end where match search stops (left as literals).
#define ZXC_TOKEN_ML_MASK
Mask to extract Match Length from a SPL token.
#define ZXC_TOKEN_LL_MASK
Mask to extract Literal Length from a SPL token.
#define ZXC_LZ_HASH_SIZE
Maximum number of entries in the hash table.
#define ZXC_LZ_HASH_BITS
Address bits for the LZ77 hash table (2^15 = 32 768 buckets).
#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_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_BLOCK_LIT_SLACK
Readable bytes a SPL/PAK payload guarantees after its literal section.
#define ZXC_LIT_RUN_MAX
Longest literal run one token carries: a length field of 0 means 1 byte.
#define ZXC_SPL_MAX_INLINE_ML
Longest match a SPL sequence carries without a varint extension.
static uint32_t zxc_read_varint(const uint8_t **ptr, const uint8_t *end)
Reads a Prefix Varint encoded integer.
#define ZXC_LIT_RLE_FLAG
Flag bit indicating an RLE run in the literal stream (0x80).
#define ZXC_BLOCK_CHECKSUM_SIZE
Size of the per-block checksum field in bytes.
#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_TOKEN_LIT_BITS
Bits for Literal Length in a SPL token.
#define ZXC_SEQ_LL_MASK
Mask to extract Literal Length from a PAK sequence.
#define ZXC_LIT_RLE_RUN_MAX
Longest run one RLE token carries.
@ ZXC_LEVEL_ULTRA
Maximum density: Huffman-coded literals and sequence tokens.
@ ZXC_LEVEL_DEFAULT
Recommended default: better ratio and decode speed than LZ4.
@ ZXC_LEVEL_DENSITY
Higher density: adds Huffman-coded literals on top of COMPACT.
@ ZXC_LEVEL_BALANCED
Balanced trade-off between ratio and decode speed.
@ ZXC_LEVEL_FAST
Fast compression; slightly better ratio than FASTEST.
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 block_flags
Flags (e.g., checksum presence).
Compression / decompression context.
Header specific to General (LZ-based) compression blocks.
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.
int zxc_write_block_header(uint8_t *dst, const size_t dst_capacity, const zxc_block_header_t *bh)
Serialises a block header (8 bytes) 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)
Serialises a PAK block header.
Definition zxc_common.c:990
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)
Serialises a SPL block header followed by its section descriptors.
Definition zxc_common.c:933
static int zxc_match_reaches(const uint8_t *cur, const uint8_t *ref, uint32_t from, const uint32_t need, const uint8_t *iend)
Tells whether a match reaches a given length, without measuring it.
static void zxc_opt_relax(uint32_t *dp, uint16_t *parent_len, uint16_t *parent_off, const size_t p, const size_t L, const uint32_t nxt, const uint16_t off_biased)
Relaxes dp[p + L] with a match of length L costing nxt in total.
static int zxc_lz77_optimal_parse_spl(zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint32_t *hash_table, uint8_t *hash_tags, uint16_t *chain_table, const uint32_t epoch_mark, const uint32_t offset_mask, const int level, uint8_t *literals, uint8_t *buf_tokens, uint16_t *buf_offsets, uint8_t *buf_extras, uint32_t *seq_c_out, size_t *lit_c_out, size_t *extras_sz_out, uint16_t *max_offset_out)
Static price-based optimal LZ77 parser for level 6.
static int zxc_spl_match_split_analyze(const uint8_t *tokens, const uint32_t n_seq, zxc_spl_match_split_hist_t *hist_buf, uint8_t *ctx_bad, uint8_t *side)
Predictability of the block's ML-escape branch, for the split decision.
static int zxc_encode_block_pak(zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, size_t *const out_sz)
Encodes one block in the PAK format (levels 1 and 2, the speed path).
int zxc_compress_chunk_wrapper(zxc_cctx_t *ctx, const uint8_t *chunk, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Compresses one chunk into a single ZXC block (the compression hot path).
static void zxc_lz_seed_dict(const uint8_t *src, const size_t dict_size, uint32_t *hash_table, uint8_t *hash_tags, uint16_t *chain_table, const uint32_t epoch_mark, const uint32_t offset_mask, const int level)
Seeds the hash/chain tables from dictionary content prepended to src.
static uint32_t zxc_spl_match_split_pieces(const uint32_t code)
Inline pieces a match of length code code splits into: ceil(length / 19).
static void zxc_varint_keep(uint8_t *extras, size_t *w, size_t *r, const uint8_t *end)
Keeps the varint at extras[*r]: moves it down to extras[*w].
static void zxc_extras_move(uint8_t *extras, size_t *w, size_t *r, const uint8_t *to)
Moves extras[*r, to) down to extras[*w] (w <= r), advancing both.
static void zxc_flush_literals(uint8_t *literals, size_t *lit_c, const uint8_t *anchor, const uint32_t ll, const uint8_t *iend)
Stages a run of literals into the literal stream.
static uint8_t zxc_hash_tag(const uint32_t val4)
8-bit rejection tag: XOR fold of the first four bytes at a position.
static int zxc_encode_block_spl(zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, size_t dst_cap, size_t *out_sz)
Encodes one block in the SPL format (levels 3 and up).
static int zxc_spl_put_seq(uint8_t *buf_tokens, uint16_t *buf_offsets, uint8_t *buf_extras, uint32_t *seq_c, size_t *extras_sz, uint16_t *max_offset, const uint32_t ll, const uint32_t ml, const uint16_t off_biased)
Emits one SPL sequence (token, offset, LL/ML escapes) and updates max_offset, the block's widest bias...
static size_t zxc_opt_dp_update_const_cost(uint32_t *dp, uint16_t *parent_len, uint16_t *parent_off, const size_t p, size_t L, const size_t L_end, const uint32_t nxt, const uint16_t off_biased)
Update dp[p + L_start .
static int zxc_emit_extra(uint8_t *extras, size_t *used, const uint32_t val, const uint32_t mask)
Appends a saturated token field's excess to the extras stream.
static size_t zxc_write_varint(uint8_t *dst, const uint32_t val)
Pair-equality mask for the RLE lookahead: element i is set when p[i] == p[i+1].
static uint16_t zxc_chain_delta(const uint32_t cur_pos, const uint32_t prev_idx)
Chain link from a position back to the one the hash slot held.
static int zxc_lazy_probe(const uint8_t *src, const uint8_t *lp, const uint8_t *iend, const uint32_t need, const uint32_t *hash_table, const uint8_t *hash_tags, const uint16_t *chain_table, const uint32_t epoch_mark, const uint32_t offset_mask, const int use_hash5, const zxc_lz77_params_t p)
Tells whether lp holds a match of at least need bytes, within the lazy search budget.
static uint32_t zxc_epoch_pos(const uint32_t head, const uint32_t offset_mask, const uint32_t epoch_mark)
Decodes a hash-table slot into a block position, 0 if it is stale.
static uint32_t zxc_opt_estimate_lit_bits(const uint8_t *src, const size_t src_sz, void *scratch)
Estimate per-block literal cost from a sampled histogram passed through the actual length-limited Huf...
static uint32_t zxc_hash_func(const uint64_t val, const int use_hash5)
Computes a hash value for either a 4-byte or 5-byte sequence.
static uint32_t zxc_spl_match_split_block(uint8_t *tokens, uint16_t *offsets, uint8_t *extras, size_t *extras_sz, uint8_t *side, zxc_spl_match_split_hist_t *hist_buf, const uint32_t n_seq, const uint8_t cap)
Per-block match splitting: escaped matches re-emitted as inline pieces.
static int zxc_encode_block_raw(const uint8_t *src, const size_t src_sz, uint8_t *const dst, const size_t dst_cap, size_t *const out_sz)
Encodes a RAW (stored) block: header plus a verbatim copy.
static uint32_t zxc_spl_match_split_piece(const uint32_t code)
Next piece of a match of length code code above the inline reach: the longest inline one that leaves ...
static zxc_match_t zxc_lz77_find_best_match(const uint8_t *src, const uint8_t *ip, const uint8_t *iend, const uint8_t *search_limit, const uint8_t *anchor, uint32_t *hash_table, uint8_t *hash_tags, uint16_t *chain_table, const uint32_t epoch_mark, const uint32_t offset_mask, const int level, const zxc_lz77_params_t p, const uint32_t last_off)
Finds the best matching sequence for LZ77 compression.
size_t zxc_huf_calc_size(const uint32_t *freq, const uint8_t *code_len, const int with_header)
Un-suffixed forwarders for the PivCo section codec (tests, tools).
int zxc_huf_build_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, const int max_code_len)
Build length-limited per-symbol Huffman code lengths from frequencies.
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.
int zxc_huf_encode_section_dict(const uint8_t *literals, const 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, const size_t dst_cap)
Encode a PivCo section against a prebuilt dict tree/codes (no header).
int zxc_huf_encode_section(const uint8_t *literals, const size_t n_literals, const uint32_t *freq, const uint8_t *code_len, uint8_t *dst, const size_t dst_cap)
Encode a PivCo literal section (128-byte lengths header + payload).
Error codes and error-name lookup for the ZXC library.
int zxc_huf_nudge_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, const size_t scratch_cap, const int max_code_len)
Optionally reshape freshly built code lengths for faster PivCo decode.
Internal definitions, constants, SIMD helpers, and utility functions.
static uint64_t zxc_le64(const void *p)
Reads a little-endian 64-bit value from a possibly unaligned address.
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.
static uint32_t zxc_le32(const void *p)
Reads a little-endian 32-bit value from a possibly unaligned address.
static void zxc_copy32(void *dst, const void *src)
Copies 32 bytes from source to destination using SIMD when available.
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_HUF_MIN_LITERALS
Absolute floor (in literals) below which a Huffman candidate is never evaluated.
#define ZXC_OPT_LONG_MATCH_SKIP
Threshold above which find_best_match is skipped at intra-match positions, keeping the parser O(N) on...
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,...
#define ZXC_OPT_MATCH_COST_BASE
Static price (bits) of a match token before varint extras: 1 byte token + 2 byte offset.
#define ZXC_OPT_LIT_SAMPLE_TARGET
Bytes that estimator samples per block: enough for a 256-symbol histogram.
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.
#define ZXC_OPT_LIT_SAMPLE_MIN
Minimum literal count for the sample-based Huffman cost estimator used by the optimal parser.
static void zxc_store_le16(void *p, const uint16_t v)
Writes a 16-bit value little-endian to a possibly unaligned address.
#define ZXC_SS_TAX(n, prem_q8)
Decode tax of a candidate: n decoded bytes at premium prem (Q8).
#define ZXC_HASH_MULT32
Marsaglia 32-bit multiplier: the 4-byte LZ and dictionary hash.
#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...
static void zxc_store_le32(void *p, const uint32_t v)
Writes a 32-bit value little-endian to a possibly unaligned address.
static int zxc_ctz64(const uint64_t x)
Counts trailing zeros, returning 64 for a zero input.
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.
#define ZXC_SPL_MATCH_SPLIT_MIN_MISPREDICT_PCT
Mispredict rate, in percent of a block's escapes, from which the block is split.
#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...
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.
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.
#define ZXC_HUF_NUM_SYMBOLS
Alphabet size: one entry per possible byte value.