ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_decompress.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
16
17#include "zxc_build.h"
18
19// Function Multi-Versioning Support
20// With ZXC_FUNCTION_SUFFIX defined (e.g. _avx2), rename the entry point AND the
21// Huffman decoder this TU consumes. The defines precede zxc_internal.h so the
22// header's prototypes get the suffix too, keeping callers and callees matched.
23#ifdef ZXC_FUNCTION_SUFFIX
24#define ZXC_CAT_IMPL(x, y) x##y
25#define ZXC_CAT(x, y) ZXC_CAT_IMPL(x, y)
26#define zxc_decompress_chunk_wrapper ZXC_CAT(zxc_decompress_chunk_wrapper, ZXC_FUNCTION_SUFFIX)
27#define zxc_decompress_chunk_wrapper_dict \
28 ZXC_CAT(zxc_decompress_chunk_wrapper_dict, ZXC_FUNCTION_SUFFIX)
29#define zxc_decompress_chunk_wrapper_safe \
30 ZXC_CAT(zxc_decompress_chunk_wrapper_safe, ZXC_FUNCTION_SUFFIX)
31// ZXC_DISPATCH_ENTROPY: the un-suffixed entry points dispatch per CPU.
32#ifndef ZXC_DISPATCH_ENTROPY
33#define zxc_huf_decode_section ZXC_CAT(zxc_huf_decode_section, ZXC_FUNCTION_SUFFIX)
34#define zxc_huf_decode_section_dict ZXC_CAT(zxc_huf_decode_section_dict, ZXC_FUNCTION_SUFFIX)
35#endif
36#endif
37
39#include "zxc_internal.h"
40
41#if defined(ZXC_USE_NEON64) || defined(ZXC_USE_NEON32) || defined(ZXC_USE_AVX2) || \
42 defined(ZXC_USE_AVX512)
48static const ZXC_ALIGN(32) uint8_t zxc_overlap_masks32[32][32] = {
49 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // off=0 (unused)
51 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // off=1 (RLE handled separately)
53 {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
54 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}, // off=2
55 {0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0,
56 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1}, // off=3
57 {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3,
58 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3}, // off=4
59 {0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0,
60 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1}, // off=5
61 {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
62 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1}, // off=6
63 {0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1,
64 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3}, // off=7
65 {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
66 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}, // off=8
67 {0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6,
68 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4}, // off=9
69 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5,
70 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1}, // off=10
71 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4,
72 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, // off=11
73 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3,
74 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7}, // off=12
75 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2,
76 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5}, // off=13
77 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1,
78 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 2, 3}, // off=14
79 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0,
80 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1}, // off=15
81 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
82 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, // off=16
83 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
84 16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}, // off=17
85 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
86 16, 17, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}, // off=18
87 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
88 16, 17, 18, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, // off=19
89 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
90 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // off=20
91 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
92 16, 17, 18, 19, 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, // off=21
93 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
94 16, 17, 18, 19, 20, 21, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, // off=22
95 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
96 16, 17, 18, 19, 20, 21, 22, 0, 1, 2, 3, 4, 5, 6, 7, 8}, // off=23
97 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
98 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7}, // off=24
99 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
100 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6}, // off=25
101 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
102 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 1, 2, 3, 4, 5}, // off=26
103 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
104 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 1, 2, 3, 4}, // off=27
105 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
106 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 0, 1, 2, 3}, // off=28
107 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
108 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 1, 2}, // off=29
109 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
110 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 1}, // off=30
111 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
112 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 0} // off=31
113};
114#endif
115
122static const uint8_t zxc_overlap_strides32[32] = {32, 32, 32, 30, 32, 30, 30, 28, 32, 27, 30,
123 22, 24, 26, 28, 30, 32, 17, 18, 19, 20, 21,
124 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
125
147// codeql[cpp/unused-static-function] : False positive
148static ZXC_ALWAYS_INLINE void zxc_decode_copy_overlap_run32(uint8_t* dst, const uint32_t off,
149 const uint64_t ml) {
150 const size_t stride = zxc_overlap_strides32[off];
151 size_t copied = 0;
152#if defined(ZXC_USE_NEON64)
153 uint8x16x2_t tbl;
154 tbl.val[0] = vld1q_u8(dst - off);
155 tbl.val[1] = vld1q_u8(dst - off + 16);
156 const uint8x16_t pat_lo = vqtbl2q_u8(tbl, vld1q_u8(zxc_overlap_masks32[off]));
157 const uint8x16_t pat_hi = vqtbl2q_u8(tbl, vld1q_u8(zxc_overlap_masks32[off] + 16));
158 do {
159 vst1q_u8(dst + copied, pat_lo);
160 vst1q_u8(dst + copied + 16, pat_hi);
161 copied += stride;
162 } while (copied < ml);
163
164#elif defined(ZXC_USE_NEON32)
165 // VTBL reaches 8 bytes per lookup from a 4-register (32-byte) table, so the
166 // pattern takes four lookups instead of NEON64's two.
167 uint8x8x4_t tbl;
168 tbl.val[0] = vld1_u8(dst - off);
169 tbl.val[1] = vld1_u8(dst - off + 8);
170 tbl.val[2] = vld1_u8(dst - off + 16);
171 tbl.val[3] = vld1_u8(dst - off + 24);
172 const uint8_t* const m = zxc_overlap_masks32[off];
173 const uint8x8_t p0 = vtbl4_u8(tbl, vld1_u8(m));
174 const uint8x8_t p1 = vtbl4_u8(tbl, vld1_u8(m + 8));
175 const uint8x8_t p2 = vtbl4_u8(tbl, vld1_u8(m + 16));
176 const uint8x8_t p3 = vtbl4_u8(tbl, vld1_u8(m + 24));
177 do {
178 vst1_u8(dst + copied, p0);
179 vst1_u8(dst + copied + 8, p1);
180 vst1_u8(dst + copied + 16, p2);
181 vst1_u8(dst + copied + 24, p3);
182 copied += stride;
183 } while (copied < ml);
184
185#elif defined(ZXC_USE_AVX2) || defined(ZXC_USE_AVX512)
186 // pshufb only reaches 16 bytes per lane, so the 32-byte table is emulated:
187 // shuffle both halves, then pick per byte on bit 4 of the index.
188 const __m128i t0 = _mm_loadu_si128((const __m128i*)(dst - off));
189 const __m128i t1 = _mm_loadu_si128((const __m128i*)(dst - off + 16));
190 const __m128i sixteen = _mm_set1_epi8(16);
191 const __m128i m_lo = _mm_load_si128((const __m128i*)zxc_overlap_masks32[off]);
192 const __m128i m_hi = _mm_load_si128((const __m128i*)(zxc_overlap_masks32[off] + 16));
193 const __m128i pat_lo =
194 _mm_blendv_epi8(_mm_shuffle_epi8(t0, m_lo),
195 _mm_shuffle_epi8(t1, _mm_sub_epi8(m_lo, sixteen)), _mm_slli_epi16(m_lo, 3));
196 const __m128i pat_hi =
197 _mm_blendv_epi8(_mm_shuffle_epi8(t0, m_hi),
198 _mm_shuffle_epi8(t1, _mm_sub_epi8(m_hi, sixteen)), _mm_slli_epi16(m_hi, 3));
199 do {
200 _mm_storeu_si128((__m128i*)(dst + copied), pat_lo);
201 _mm_storeu_si128((__m128i*)(dst + copied + 16), pat_hi);
202 copied += stride;
203 } while (copied < ml);
204
205#else
206 // SSE2 (no PSHUFB) and non-SIMD tiers: build the 32-byte pattern with a
207 // wrap counter (no per-byte modulo), then store it as two 16-byte halves.
208 const uint8_t* src = dst - off;
209 uint8_t pat[32];
210 uint32_t k = 0;
211 for (size_t i = 0; i < 32; i++) {
212 pat[i] = src[k];
213 if (++k == off) k = 0;
214 }
215 do {
216 zxc_copy16(dst + copied, pat);
217 zxc_copy16(dst + copied + 16, pat + 16);
218 copied += stride;
219 } while (copied < ml);
220#endif
221}
222
242// codeql[cpp/unused-static-function] : False positive
243static ZXC_ALWAYS_INLINE void zxc_decode_copy_overlap_short(uint8_t* dst, const uint32_t off,
244 const uint64_t ml) {
245#if defined(ZXC_USE_NEON64)
246 const uint8x16_t s0 = vld1q_u8(dst - off);
247 vst1q_u8(dst, vqtbl1q_u8(s0, vld1q_u8(zxc_overlap_masks32[off])));
248 if (UNLIKELY(ml > 16)) {
249 uint8x16x2_t tbl;
250 tbl.val[0] = s0;
251 tbl.val[1] = vld1q_u8(dst - off + 16);
252 vst1q_u8(dst + 16, vqtbl2q_u8(tbl, vld1q_u8(zxc_overlap_masks32[off] + 16)));
253 }
254
255#elif defined(ZXC_USE_NEON32)
256 uint8x8x2_t lo_tbl;
257 lo_tbl.val[0] = vld1_u8(dst - off);
258 lo_tbl.val[1] = vld1_u8(dst - off + 8);
259 const uint8_t* const m = zxc_overlap_masks32[off];
260 vst1_u8(dst, vtbl2_u8(lo_tbl, vld1_u8(m)));
261 vst1_u8(dst + 8, vtbl2_u8(lo_tbl, vld1_u8(m + 8)));
262 if (UNLIKELY(ml > 16)) {
263 uint8x8x4_t tbl;
264 tbl.val[0] = lo_tbl.val[0];
265 tbl.val[1] = lo_tbl.val[1];
266 tbl.val[2] = vld1_u8(dst - off + 16);
267 tbl.val[3] = vld1_u8(dst - off + 24);
268 vst1_u8(dst + 16, vtbl4_u8(tbl, vld1_u8(m + 16)));
269 vst1_u8(dst + 24, vtbl4_u8(tbl, vld1_u8(m + 24)));
270 }
271
272#elif defined(ZXC_USE_AVX2) || defined(ZXC_USE_AVX512)
273 // pshufb reaches 16 bytes, so only the upper half needs two tables: shuffle
274 // both and pick per byte on bit 4 of the index.
275 const __m128i t0 = _mm_loadu_si128((const __m128i*)(dst - off));
276 _mm_storeu_si128(
277 (__m128i*)dst,
278 _mm_shuffle_epi8(t0, _mm_load_si128((const __m128i*)zxc_overlap_masks32[off])));
279 if (UNLIKELY(ml > 16)) {
280 const __m128i t1 = _mm_loadu_si128((const __m128i*)(dst - off + 16));
281 const __m128i m_hi = _mm_load_si128((const __m128i*)(zxc_overlap_masks32[off] + 16));
282 _mm_storeu_si128(
283 (__m128i*)(dst + 16),
284 _mm_blendv_epi8(_mm_shuffle_epi8(t0, m_hi),
285 _mm_shuffle_epi8(t1, _mm_sub_epi8(m_hi, _mm_set1_epi8(16))),
286 _mm_slli_epi16(m_hi, 3)));
287 }
288
289#else
290 const uint8_t* src = dst - off;
291 const size_t n = (ml > 16) ? 32 : 16;
292 uint32_t k = 0;
293 for (size_t i = 0; i < n; i++) {
294 dst[i] = src[k];
295 if (++k == off) k = 0;
296 }
297#endif
298}
299
313// codeql[cpp/unused-static-function] : False positive, used in DECODE_MATCH_SAFE/FAST macros
314static ZXC_ALWAYS_INLINE void zxc_decode_fill_run(uint8_t* dst, const uint8_t byte,
315 const uint64_t ml) {
316#if defined(ZXC_USE_AVX2) || defined(ZXC_USE_AVX512)
317 const __m256i v = _mm256_set1_epi8((char)byte);
318 _mm256_storeu_si256((__m256i*)dst, v);
319 if (UNLIKELY(ml > 32)) {
320 uint8_t* p = dst;
321 const uint8_t* const last = dst + ml - 32;
322 do {
323 p += 32;
324 _mm256_storeu_si256((__m256i*)p, v);
325 } while (p < last);
326 }
327#elif defined(ZXC_USE_SSE2)
328 const __m128i v = _mm_set1_epi8((char)byte);
329 _mm_storeu_si128((__m128i*)dst, v);
330 _mm_storeu_si128((__m128i*)(dst + 16), v);
331 if (UNLIKELY(ml > 32)) {
332 uint8_t* p = dst;
333 const uint8_t* const last = dst + ml - 32;
334 do {
335 p += 32;
336 _mm_storeu_si128((__m128i*)p, v);
337 _mm_storeu_si128((__m128i*)(p + 16), v);
338 } while (p < last);
339 }
340#elif defined(ZXC_USE_NEON64) || defined(ZXC_USE_NEON32)
341 const uint8x16_t v = vdupq_n_u8(byte);
342 vst1q_u8(dst, v);
343 vst1q_u8(dst + 16, v);
344 if (UNLIKELY(ml > 32)) {
345 uint8_t* p = dst;
346 const uint8_t* const last = dst + ml - 32;
347 do {
348 p += 32;
349 vst1q_u8(p, v);
350 vst1q_u8(p + 16, v);
351 } while (p < last);
352 }
353#else
354 ZXC_MEMSET(dst, byte, ml);
355#endif
356}
357
358// ==========================================================================
359// Shared decode macros for the SPL and PAK decoders (fast + safe variants).
360// Defined at file scope to avoid four identical copies inside each function.
361// They reference the local names l_ptr, d_ptr, d_floor that every call site
362// has in scope. #undef-ed at the end of the last consumer.
363// ==========================================================================
364
377static ZXC_ALWAYS_INLINE void zxc_wild_copy32(uint8_t* dst, const uint8_t* src, const size_t len) {
378 zxc_copy32(dst, src);
379 if (UNLIKELY(len > 32)) {
380 size_t rem = len - 32;
381 dst += 32;
382 src += 32;
383 while (rem > 32) {
384 zxc_copy32(dst, src);
385 dst += 32;
386 src += 32;
387 rem -= 32;
388 }
389 zxc_copy32(dst, src);
390 }
391}
392
408static ZXC_ALWAYS_INLINE void zxc_decode_copy_literals(uint8_t* RESTRICT dst,
409 const uint8_t* RESTRICT src,
410 const uint64_t ll) {
411 zxc_wild_copy32(dst, src, ll);
412}
413
437static ZXC_ALWAYS_INLINE void zxc_decode_copy_match(uint8_t* RESTRICT d_ptr, const uint32_t off,
438 const uint64_t ml) {
439 const uint8_t* match_src = d_ptr - off;
440 if (LIKELY(off >= 32)) {
441 zxc_wild_copy32(d_ptr, match_src, ml);
442 } else if (off == 1) {
443 zxc_decode_fill_run(d_ptr, match_src[0], ml);
444 } else {
445 zxc_decode_copy_overlap_run32(d_ptr, off, ml);
446 }
447}
448
464static ZXC_ALWAYS_INLINE void zxc_decode_copy_match_short(uint8_t* RESTRICT d_ptr,
465 const uint32_t off, const uint64_t ml) {
466 const uint8_t* match_src = d_ptr - off;
467 if (LIKELY(off >= 32)) {
468 zxc_copy32(d_ptr, match_src);
469 } else if (off == 1) {
470 zxc_decode_fill_run(d_ptr, match_src[0], ml);
471 } else {
472 zxc_decode_copy_overlap_short(d_ptr, off, ml);
473 }
474}
475
483static ZXC_ALWAYS_INLINE void zxc_decode_copy_match_spl(uint8_t* RESTRICT d_ptr, const uint32_t off,
484 const uint64_t ml) {
485 if (LIKELY(ml <= ZXC_SPL_MAX_INLINE_ML)) {
486 zxc_decode_copy_match_short(d_ptr, off, ml);
487 } else {
488 zxc_decode_copy_match(d_ptr, off, ml);
489 }
490}
491
508static ZXC_NOINLINE void zxc_decode_copy_match_exact(uint8_t* d_ptr, const uint8_t* match_src,
509 const size_t off, const size_t ml) {
510 if (off >= ml) {
511 ZXC_MEMCPY(d_ptr, match_src, ml);
512 } else if (ml < 16) {
513 for (size_t i = 0; i < ml; i++) d_ptr[i] = match_src[i];
514 } else {
515 size_t n = off;
516 ZXC_MEMCPY(d_ptr, match_src, n);
517 while (n <= ml - n) {
518 ZXC_MEMCPY(d_ptr + n, d_ptr, n);
519 n <<= 1;
520 }
521 ZXC_MEMCPY(d_ptr + n, d_ptr, ml - n);
522 }
523}
524
525// Match emission only. The literal copy lives in the per-format sequence macros
526// because the two formats want different strategies: SPL's inline ll is at most
527// 14, so one zxc_copy16 covers it, while PAK's reaches 254 and needs the
528// 32-byte ladder.
529
530// SAFE version: rejects a match reaching below d_floor. COPY is the format's
531// match-copy helper, so SPL can pass the length-bounded one.
532#define DECODE_MATCH_SAFE(ml, off, COPY) \
533 do { \
534 if (UNLIKELY((size_t)(d_ptr - d_floor) < (off))) return ZXC_ERROR_BAD_OFFSET; \
535 COPY(d_ptr, off, ml); \
536 d_ptr += ml; \
537 } while (0)
538
539// FAST version: no offset check. Only reached past d_bounds, where no encodable
540// offset can reach below d_floor, so the check above would always pass.
541#define DECODE_MATCH_FAST(ml, off, COPY) \
542 do { \
543 COPY(d_ptr, off, ml); \
544 d_ptr += ml; \
545 } while (0)
546
558#define SPL_OFF8 (gh.enc_off == 1)
559
573#define DECODE_SPL_SEQ(LL, ML, OFF, RESERVE, N_REM, DECODE, ON_FAIL) \
574 do { \
575 uint64_t ll = (LL); \
576 uint64_t ml = (ML); \
577 if (UNLIKELY(ll == ZXC_TOKEN_LL_MASK)) { \
578 ll += zxc_read_varint(&e_ptr, e_end); \
579 const uint64_t reserve = (RESERVE); \
580 /* An extended ll eats the batch's destination budget, so reserve \
581 * this sequence's match and the remaining ones too. ml is still \
582 * the raw nibble here; an escaped one re-checks itself below. */ \
583 if (UNLIKELY(ll + reserve > (size_t)(l_end - l_ptr) || \
584 ll + ml + ZXC_LZ_MIN_MATCH_LEN + \
585 (N_REM) * ZXC_SPL_MAX_INLINE_OUT_PER_SEQ + ZXC_PAD_SIZE > \
586 (size_t)(d_end - d_ptr))) \
587 ON_FAIL; \
588 zxc_decode_copy_literals(d_ptr, l_ptr, ll); \
589 } else { \
590 /* ll <= 14 here, so one 16-byte store covers it. */ \
591 zxc_copy16(d_ptr, l_ptr); \
592 } \
593 l_ptr += ll; \
594 d_ptr += ll; \
595 if (UNLIKELY(ml == ZXC_TOKEN_ML_MASK)) { \
596 ml += zxc_read_varint(&e_ptr, e_end); \
597 /* d_ptr already carries the literals, hence no `ll +` term here. */ \
598 if (UNLIKELY(ml + ZXC_LZ_MIN_MATCH_LEN + (N_REM) * ZXC_SPL_MAX_INLINE_OUT_PER_SEQ + \
599 ZXC_PAD_SIZE > \
600 (size_t)(d_end - d_ptr))) \
601 ON_FAIL; \
602 } \
603 ml += ZXC_LZ_MIN_MATCH_LEN; \
604 DECODE(ml, OFF, zxc_decode_copy_match_spl); \
605 } while (0)
606
613 * cost x86-64 spills.
614 */
615#define DECODE_SPL_BATCH_4X(DECODE, ON_FAIL) \
616 do { \
617 uint32_t tokens = zxc_le32(t_ptr); \
618 t_ptr += sizeof(uint32_t); \
619 uint64_t offs; \
620 if (SPL_OFF8) { \
621 uint64_t x = zxc_le32(o_ptr); \
622 o_ptr += sizeof(uint32_t); \
623 x = (x | (x << 16)) & 0x0000FFFF0000FFFFULL; \
624 offs = (x | (x << 8)) & 0x00FF00FF00FF00FFULL; \
625 } else { \
626 offs = zxc_le64(o_ptr); \
627 o_ptr += sizeof(uint64_t); \
628 } \
629 DECODE_SPL_SEQ((tokens & 0x0F0) >> 4, (tokens & 0x00F), \
630 ZXC_LZ_OFFSET_BIAS + (uint32_t)(offs & 0xFFFF), \
631 ((tokens >> 12) & 0xF) + ((tokens >> 20) & 0xF) + (tokens >> 28), 3U, \
632 DECODE, ON_FAIL); \
633 DECODE_SPL_SEQ((tokens & 0x0F000) >> 12, (tokens & 0x00F00) >> 8, \
634 ZXC_LZ_OFFSET_BIAS + (uint32_t)((offs >> 16) & 0xFFFF), \
635 ((tokens >> 20) & 0xF) + (tokens >> 28), 2U, DECODE, ON_FAIL); \
636 DECODE_SPL_SEQ((tokens & 0x0F00000) >> 20, (tokens & 0x00F0000) >> 16, \
637 ZXC_LZ_OFFSET_BIAS + (uint32_t)((offs >> 32) & 0xFFFF), (tokens >> 28), 1U, \
638 DECODE, ON_FAIL); \
639 DECODE_SPL_SEQ((tokens >> 28), (tokens >> 24) & 0x0F, \
640 ZXC_LZ_OFFSET_BIAS + (uint32_t)(offs >> 48), 0, 0U, DECODE, ON_FAIL); \
641 n_seq -= 4; \
642 } while (0)
643
647 * site's extras_ptr/extras_end instead of e_ptr/e_end.
648 */
649#define DECODE_PAK_SEQ(S, RESERVE, N_REM, DECODE, ON_FAIL) \
650 do { \
651 uint64_t ll = (S) >> ZXC_SEQ_LL_SHIFT; \
652 const uint32_t mb = ((S) >> ZXC_SEQ_ML_SHIFT) & ZXC_SEQ_ML_MASK; \
653 uint64_t ml = mb + ZXC_LZ_MIN_MATCH_LEN; \
654 if (UNLIKELY(ll == ZXC_SEQ_LL_MASK)) { \
655 ll += zxc_read_varint(&extras_ptr, extras_end); \
656 const uint64_t reserve = (RESERVE); \
657 /* Same reservation as the SPL twin; PAK's inline ml reaches 259. */ \
658 if (UNLIKELY(ll + reserve > (size_t)(l_end - l_ptr) || \
659 ll + ml + (N_REM) * ZXC_PAK_MAX_INLINE_OUT_PER_SEQ + ZXC_PAD_SIZE > \
660 (size_t)(d_end - d_ptr))) \
661 ON_FAIL; \
662 } \
663 if (UNLIKELY(mb == ZXC_SEQ_ML_MASK)) { \
664 ml += zxc_read_varint(&extras_ptr, extras_end); \
665 if (UNLIKELY(ll + ml + (N_REM) * ZXC_PAK_MAX_INLINE_OUT_PER_SEQ + ZXC_PAD_SIZE > \
666 (size_t)(d_end - d_ptr))) \
667 ON_FAIL; \
668 } \
669 const uint32_t off = ((S) & ZXC_SEQ_OFF_MASK) + ZXC_LZ_OFFSET_BIAS; \
670 /* PAK keeps the ladder: its inline ll reaches 254. */ \
671 zxc_decode_copy_literals(d_ptr, l_ptr, ll); \
672 l_ptr += ll; \
673 d_ptr += ll; \
674 DECODE(ml, off, zxc_decode_copy_match); \
675 } while (0)
676
680 * placed exactly where the hand-unrolled bodies had it.
681 */
682#define DECODE_PAK_BATCH_4X(DECODE, ON_FAIL, PREFETCH) \
683 do { \
684 uint32_t s1 = zxc_le32(seq_ptr); \
685 uint32_t s2 = zxc_le32(seq_ptr + sizeof(uint32_t)); \
686 uint32_t s3 = zxc_le32(seq_ptr + 2 * sizeof(uint32_t)); \
687 uint32_t s4 = zxc_le32(seq_ptr + 3 * sizeof(uint32_t)); \
688 seq_ptr += 4 * sizeof(uint32_t); \
689 PREFETCH; \
690 DECODE_PAK_SEQ( \
691 s1, (s2 >> ZXC_SEQ_LL_SHIFT) + (s3 >> ZXC_SEQ_LL_SHIFT) + (s4 >> ZXC_SEQ_LL_SHIFT), \
692 3U, DECODE, ON_FAIL); \
693 DECODE_PAK_SEQ(s2, (s3 >> ZXC_SEQ_LL_SHIFT) + (s4 >> ZXC_SEQ_LL_SHIFT), 2U, DECODE, \
694 ON_FAIL); \
695 DECODE_PAK_SEQ(s3, (s4 >> ZXC_SEQ_LL_SHIFT), 1U, DECODE, ON_FAIL); \
696 DECODE_PAK_SEQ(s4, 0, 0U, DECODE, ON_FAIL); \
697 n_seq -= 4; \
698 } while (0)
699
712 * @return @ref ZXC_OK, or @ref ZXC_ERROR_MEMORY on allocation failure.
713 */
714static ZXC_NOINLINE ZXC_COLD int zxc_ensure_entropy_scratch(const zxc_cctx_t* RESTRICT ctx) {
715 if (LIKELY(ctx->pivco_scratch)) return ZXC_OK;
716 return zxc_cctx_alloc_entropy_scratch((zxc_cctx_t*)(uintptr_t)ctx);
717}
718
719static ZXC_NOINLINE ZXC_COLD int zxc_decode_lit_pivco(const zxc_cctx_t* RESTRICT ctx,
720 const uint8_t* RESTRICT payload,
721 const size_t psize,
722 const size_t required_size) {
723 const int arc = zxc_ensure_entropy_scratch(ctx);
724 if (UNLIKELY(arc != ZXC_OK)) return arc;
725 if (UNLIKELY(ctx->lit_buffer_cap < required_size + ZXC_PAD_SIZE ||
726 ctx->pivco_scratch_cap < required_size + ZXC_PIVCO_SCRATCH_PAD))
728 return zxc_huf_decode_section(payload, psize, ctx->lit_buffer, required_size,
729 ctx->pivco_scratch);
730}
731
732#ifdef ZXC_NO_DICT
733// No dictionary support: error-returning stand-ins (corrupt input reaches them).
734#define zxc_decode_lit_pivco_dict(ctx, payload, psize, required_size) ZXC_ERROR_DICT_REQUIRED
735#define zxc_decode_block_spl_entropy_dict(ctx, src, src_size, dst, dst_capacity) \
736 ZXC_ERROR_DICT_REQUIRED
737#define zxc_decode_block_spl_dict(ctx, src, src_size, dst, dst_capacity) ZXC_ERROR_DICT_REQUIRED
738#define zxc_decode_block_pak_dict(ctx, src, src_size, dst, dst_capacity) ZXC_ERROR_DICT_REQUIRED
739#else
740static ZXC_NOINLINE ZXC_COLD int zxc_decode_lit_pivco_dict(const zxc_cctx_t* RESTRICT ctx,
741 const uint8_t* RESTRICT payload,
742 const size_t psize,
743 const size_t required_size) {
744 if (UNLIKELY(!ctx->dict_huf_tree_ok)) return ZXC_ERROR_DICT_REQUIRED;
745 const int arc = zxc_ensure_entropy_scratch(ctx);
746 if (UNLIKELY(arc != ZXC_OK)) return arc;
747 if (UNLIKELY(ctx->lit_buffer_cap < required_size + ZXC_PAD_SIZE ||
748 ctx->pivco_scratch_cap < required_size + ZXC_PIVCO_SCRATCH_PAD))
750 return zxc_huf_decode_section_dict(payload, psize, ctx->lit_buffer, required_size,
751 &ctx->dict_huf->tree, ctx->pivco_scratch);
752}
753#endif // ZXC_NO_DICT
754
755static ZXC_NOINLINE ZXC_COLD int zxc_decode_tok_pivco(const zxc_cctx_t* RESTRICT ctx,
756 const uint8_t* RESTRICT payload,
757 const size_t psize, const size_t n_tok) {
758 const int arc = zxc_ensure_entropy_scratch(ctx);
759 if (UNLIKELY(arc != ZXC_OK)) return arc;
760 if (UNLIKELY(n_tok + ZXC_PAD_SIZE > ctx->tok_buffer_cap ||
761 n_tok + ZXC_PIVCO_SCRATCH_PAD > ctx->pivco_scratch_cap))
763 return zxc_huf_decode_section(payload, psize, ctx->tok_buffer, n_tok, ctx->pivco_scratch);
764}
765
766static ZXC_NOINLINE int zxc_decode_block_spl_entropy(const zxc_cctx_t* RESTRICT ctx,
767 const uint8_t* RESTRICT src, size_t src_size,
768 uint8_t* RESTRICT dst, size_t dst_capacity);
769#ifndef ZXC_NO_DICT
770static ZXC_NOINLINE int zxc_decode_block_spl_entropy_dict(const zxc_cctx_t* RESTRICT ctx,
771 const uint8_t* RESTRICT src,
772 size_t src_size, uint8_t* RESTRICT dst,
773 size_t dst_capacity);
774#endif // ZXC_NO_DICT
775static ZXC_NOINLINE int zxc_decode_block_spl_entropy_safe(const zxc_cctx_t* RESTRICT ctx,
776 const uint8_t* RESTRICT src,
777 size_t src_size, uint8_t* RESTRICT dst,
778 size_t dst_capacity);
779
806 * @return Bytes written to @p dst on success, or a negative @ref zxc_error_t.
807 */
808static ZXC_ALWAYS_INLINE int zxc_decode_block_spl_impl(const zxc_cctx_t* RESTRICT ctx,
809 const uint8_t* RESTRICT src,
810 const size_t src_size, uint8_t* RESTRICT dst,
811 const size_t dst_capacity, const int safe,
812 const int has_dict, const int tok_entropy) {
814
815 // Constant 0 when !has_dict, so `d_floor` folds to `dst`.
816 const size_t dict_size = has_dict ? ctx->dict_size : 0;
817 uint32_t lit_comp;
818 uint32_t tok_comp;
819
820 const int hdr_sz = zxc_read_spl_header_and_desc(src, src_size, &gh, &lit_comp, &tok_comp);
821 if (UNLIKELY(hdr_sz < 0)) return ZXC_ERROR_BAD_HEADER;
822
823 // Only 0 and 1 are defined widths.
824 if (UNLIKELY(gh.enc_off > 1)) return ZXC_ERROR_CORRUPT_DATA;
825
826 // Entropy-coded tokens (level 7): tail-call the dedicated instantiation
827 // before any section work - it restarts from the header, so only the parse
828 // above is duplicated. Flags are constant per instantiation, so exactly one
829 // call survives and t_ptr keeps a single provenance below.
830 if (!tok_entropy && UNLIKELY(gh.enc_tok == ZXC_SECTION_ENCODING_HUFFMAN)) {
831 if (safe) return zxc_decode_block_spl_entropy_safe(ctx, src, src_size, dst, dst_capacity);
832 if (has_dict)
833 return zxc_decode_block_spl_entropy_dict(ctx, src, src_size, dst, dst_capacity);
834 return zxc_decode_block_spl_entropy(ctx, src, src_size, dst, dst_capacity);
835 }
836
837 const uint8_t* p_data = src + (size_t)hdr_sz;
838 const uint8_t* p_curr = p_data;
839
840 // --- Literal Stream Setup ---
841 const uint8_t* l_ptr;
842 const uint8_t* l_end;
843 uint8_t* rle_buf = NULL;
844
845 size_t lit_stream_size = lit_comp;
846 // Decoded size of an encoded literal section (RAW ignores it).
847 const size_t required_size = gh.n_literals;
848
849 if (gh.enc_lit == ZXC_SECTION_ENCODING_HUFFMAN ||
850 gh.enc_lit == ZXC_SECTION_ENCODING_HUFFMAN_DICT) {
851 if (UNLIKELY(lit_stream_size > (size_t)(src + src_size - p_curr)))
853 if (required_size == 0) {
854 l_ptr = p_curr;
855 l_end = p_curr;
856 } else {
857 if (UNLIKELY(required_size > dst_capacity || required_size > SIZE_MAX - ZXC_PAD_SIZE))
859 const int rc =
860 (gh.enc_lit == ZXC_SECTION_ENCODING_HUFFMAN)
861 ? zxc_decode_lit_pivco(ctx, p_curr, lit_stream_size, required_size)
862 : zxc_decode_lit_pivco_dict(ctx, p_curr, lit_stream_size, required_size);
863 if (UNLIKELY(rc != ZXC_OK)) return rc;
864 l_ptr = ctx->lit_buffer;
865 l_end = ctx->lit_buffer + required_size;
866 }
867 } else if (gh.enc_lit == ZXC_SECTION_ENCODING_RLE) {
868 if (required_size > 0) {
869 if (UNLIKELY(required_size > dst_capacity || required_size > SIZE_MAX - ZXC_PAD_SIZE))
871 const size_t alloc_size = required_size + ZXC_PAD_SIZE;
872
873 // lit_buffer is pre-allocated to chunk_size + ZXC_PAD_SIZE by
874 // zxc_cctx_init (mode == 0).
875 if (UNLIKELY(ctx->lit_buffer_cap < alloc_size)) return ZXC_ERROR_DST_TOO_SMALL;
876
877 rle_buf = ctx->lit_buffer;
878 if (UNLIKELY(!rle_buf || lit_stream_size > (size_t)(src + src_size - p_curr)))
880
881 const uint8_t* r_ptr = p_curr;
882 const uint8_t* r_end = r_ptr + lit_stream_size;
883 uint8_t* w_ptr = rle_buf;
884 const uint8_t* const w_end = rle_buf + required_size;
885
886 while (r_ptr < r_end && w_ptr < w_end) {
887 uint8_t token = *r_ptr++;
888 if (LIKELY(!(token & ZXC_LIT_RLE_FLAG))) {
889 // Raw copy (most common path): 32-byte wild copies (zxc_copy32 width)
890 // token is 7-bit (0-127), so len is 1-128 bytes
891 const uint32_t len = (uint32_t)token + 1;
892 if (UNLIKELY(w_ptr + len > w_end || r_ptr + len > r_end))
894
895 // Destination has ZXC_PAD_SIZE bytes of safe overrun space.
896 // Source may not - check before wild copy.
897 // Fast path: source holds a full zxc_copy32 read (most common)
898 if (LIKELY(r_ptr + 32 <= r_end)) {
899 // Single copy covers len <= 32 (most tokens)
900 zxc_copy32(w_ptr, r_ptr);
901
902 if (UNLIKELY(len > 32)) {
903 // Unroll: max len=128, so max 4 copies total. The last
904 // copy is placed to end exactly on len, overlapping the
905 // previous one - unconditional stores beat branches here.
906 if (len <= 64) {
907 zxc_copy32(w_ptr + len - 32, r_ptr + len - 32);
908 } else if (len <= 96) {
909 zxc_copy32(w_ptr + 32, r_ptr + 32);
910 zxc_copy32(w_ptr + len - 32, r_ptr + len - 32);
911 } else {
912 zxc_copy32(w_ptr + 32, r_ptr + 32);
913 zxc_copy32(w_ptr + 64, r_ptr + 64);
914 zxc_copy32(w_ptr + len - 32, r_ptr + len - 32);
915 }
916 }
917 } else {
918 // Near end of source: safe copy (rare cold path)
919 ZXC_MEMCPY(w_ptr, r_ptr, len);
920 }
921
922 w_ptr += len;
923 r_ptr += len;
924 } else {
925 // RLE run: fill with single byte
926 const uint32_t len = (token & ZXC_LIT_LEN_MASK) + ZXC_LIT_RLE_RUN_MIN;
927 if (UNLIKELY(w_ptr + len > w_end || r_ptr >= r_end))
929 ZXC_MEMSET(w_ptr, *r_ptr++, len);
930 w_ptr += len;
931 }
932 }
933 if (UNLIKELY(w_ptr != w_end || r_ptr != r_end)) return ZXC_ERROR_CORRUPT_DATA;
934 l_ptr = rle_buf;
935 l_end = rle_buf + required_size;
936 } else {
937 if (UNLIKELY(lit_stream_size != 0)) return ZXC_ERROR_CORRUPT_DATA;
938 l_ptr = p_curr;
939 l_end = p_curr;
940 }
941 } else if (gh.enc_lit == ZXC_SECTION_ENCODING_RAW) {
942 if (UNLIKELY(lit_stream_size > (size_t)(src + src_size - p_curr)))
944 l_ptr = p_curr;
945 l_end = p_curr + lit_stream_size;
946 } else {
948 }
949
950 p_curr += lit_stream_size;
951
952 // --- Stream Pointers & Validation ---
953 // Only the literal and token sizes are on the wire; offsets follow from the
954 // sequence count and width, and extras take the payload residue.
955 const size_t sz_tokens = tok_comp;
956 const uint64_t sz_offsets = SPL_OFF8 ? (uint64_t)gh.n_sequences : (uint64_t)gh.n_sequences * 2;
957
958 const size_t payload_avail = (size_t)(src + src_size - p_data);
959 const uint64_t consumed = (uint64_t)lit_stream_size + (uint64_t)sz_tokens + sz_offsets;
960 if (UNLIKELY(consumed > (uint64_t)payload_avail)) return ZXC_ERROR_CORRUPT_DATA;
961 const size_t sz_extras = payload_avail - (size_t)consumed; /* slack padding included */
962
963 // RAW literals point into the caller's buffer and the wild copy overshoots,
964 // so it needs ZXC_BLOCK_LIT_SLACK readable bytes behind it. v7 staged short
965 // streams into a padded scratch here; v8 rejects instead. No underflow:
966 // lit_stream_size <= consumed <= payload_avail.
967 if (UNLIKELY(payload_avail - lit_stream_size < ZXC_BLOCK_LIT_SLACK))
969
970 // Offsets/extras follow the on-disk token SECTION; sz_tokens is its size
971 // (== n_sequences when RAW, the Huffman payload size when enc_tok set).
972 const uint8_t* o_ptr = p_curr + sz_tokens;
973 const uint8_t* e_ptr = o_ptr + (size_t)sz_offsets;
974 const uint8_t* const e_end = e_ptr + sz_extras;
975
976 const uint8_t* RESTRICT t_ptr;
977 if (!tok_entropy) {
978 // enc_tok == 2 was re-routed right after the header parse; any other
979 // value would have mis-sized the section descriptors above.
980 if (UNLIKELY(gh.enc_tok != 0)) return ZXC_ERROR_CORRUPT_DATA;
981 t_ptr = p_curr;
982 } else {
983 if (UNLIKELY(gh.enc_tok != ZXC_SECTION_ENCODING_HUFFMAN)) return ZXC_ERROR_CORRUPT_DATA;
984 const int rc = zxc_decode_tok_pivco(ctx, p_curr, sz_tokens, gh.n_sequences);
985 if (UNLIKELY(rc != ZXC_OK)) return rc;
986 t_ptr = ctx->tok_buffer;
987 }
988
989 uint8_t* d_ptr = dst;
990 const uint8_t* const d_end = dst + dst_capacity;
991 // Lowest address a match may reach: the dictionary prefix if any, else dst.
992 const uint8_t* const d_floor = dst - dict_size;
993 // 4x loop margin: four sequences without a varint, the wild-copy overshoot, 4 of safety.
994 const size_t d_margin_4x = 4 * ZXC_SPL_MAX_INLINE_OUT_PER_SEQ + ZXC_PAD_SIZE + 4;
995 const uint8_t* const d_end_safe = (dst_capacity > d_margin_4x) ? d_end - d_margin_4x : dst;
996
997 // Literal margin for the 4x loops: without a varint, ll <= 14 per sequence,
998 // so 4 * 14 = 56. Past that margin only the cold varint path checks l_ptr.
999 const size_t spl_sz_lit = (size_t)(l_end - l_ptr);
1000 const size_t spl_margin_4x = 4 * (ZXC_TOKEN_LL_MASK - 1); // 56
1001 const size_t spl_margin_1x = ZXC_TOKEN_LL_MASK - 1; // 14
1002 const uint8_t* const l_end_safe_4x =
1003 (spl_sz_lit > spl_margin_4x) ? l_end - spl_margin_4x : l_ptr;
1004 const uint8_t* const l_end_safe_1x =
1005 (spl_sz_lit > spl_margin_1x) ? l_end - spl_margin_1x : l_ptr;
1006
1007 uint32_t n_seq = gh.n_sequences;
1008
1009 // Offsets only need checking until the output is wider than the widest offset
1010 // the format can encode (256 for 1-byte offsets, 65536 for 2-byte); past that
1011 // none can reach below d_floor. A dictionary counts as already written, so a
1012 // large one puts d_bounds at dst and skips the SAFE loop.
1013 const size_t off_span = SPL_OFF8 ? (1U << 8) : (1U << 16);
1014 const size_t span = (dict_size >= off_span) ? 0 : off_span - dict_size;
1015 const uint8_t* const d_bounds = (span >= dst_capacity) ? d_end : dst + span;
1016
1017 // --- SAFE Loop: offset validation until d_bounds (4x unroll) ---
1018 if (safe) {
1019 // SAFE variant: save per-batch state so overflow can rollback.
1020 while (n_seq >= 4 && d_ptr < d_end_safe && l_ptr < l_end_safe_4x && d_ptr < d_bounds) {
1021 const uint8_t* const t_save = t_ptr;
1022 const uint8_t* const o_save = o_ptr;
1023 const uint8_t* const e_save = e_ptr;
1024 uint8_t* const d_save = d_ptr;
1025 const uint8_t* const l_save = l_ptr;
1026 DECODE_SPL_BATCH_4X(DECODE_MATCH_SAFE, goto rollback_safe_4x);
1027 continue;
1028
1029 rollback_safe_4x:
1030 t_ptr = t_save;
1031 o_ptr = o_save;
1032 e_ptr = e_save;
1033 d_ptr = d_save;
1034 l_ptr = l_save;
1035 break;
1036 }
1037 } else {
1038 while (n_seq >= 4 && d_ptr < d_end_safe && l_ptr < l_end_safe_4x && d_ptr < d_bounds) {
1039 DECODE_SPL_BATCH_4X(DECODE_MATCH_SAFE, return ZXC_ERROR_OVERFLOW);
1040 }
1041 }
1042
1043 // --- FAST Loop: After threshold, no offset validation needed (4x unroll) ---
1044 if (safe) {
1045 while (n_seq >= 4 && d_ptr < d_end_safe && l_ptr < l_end_safe_4x) {
1046 const uint8_t* const t_save = t_ptr;
1047 const uint8_t* const o_save = o_ptr;
1048 const uint8_t* const e_save = e_ptr;
1049 uint8_t* const d_save = d_ptr;
1050 const uint8_t* const l_save = l_ptr;
1051 DECODE_SPL_BATCH_4X(DECODE_MATCH_FAST, goto rollback_fast_4x);
1052 continue;
1053
1054 rollback_fast_4x:
1055 t_ptr = t_save;
1056 o_ptr = o_save;
1057 e_ptr = e_save;
1058 d_ptr = d_save;
1059 l_ptr = l_save;
1060 break;
1061 }
1062 } else {
1063 while (n_seq >= 4 && d_ptr < d_end_safe && l_ptr < l_end_safe_4x) {
1064 DECODE_SPL_BATCH_4X(DECODE_MATCH_FAST, return ZXC_ERROR_OVERFLOW);
1065 }
1066 }
1067
1068 // --- Remaining 1 sequence (Fast Path) ---
1069 while (n_seq > 0 && d_ptr < d_end_safe && l_ptr < l_end_safe_1x) {
1070 // Save pointers before reading (in case we need to fall back to Safe Path)
1071 const uint8_t* t_save = t_ptr;
1072 const uint8_t* o_save = o_ptr;
1073 const uint8_t* e_save = e_ptr;
1074
1075 uint8_t token = *t_ptr++;
1076 uint64_t ll = token >> ZXC_TOKEN_LIT_BITS;
1077 uint64_t ml = token & ZXC_TOKEN_ML_MASK;
1078 uint32_t offset = ZXC_LZ_OFFSET_BIAS;
1079 if (SPL_OFF8) {
1080 offset += *o_ptr++; // 1-byte offset (biased)
1081 } else {
1082 offset += zxc_le16(o_ptr); // 2-byte offset (biased)
1083 o_ptr += sizeof(uint16_t);
1084 }
1085
1086 if (UNLIKELY(ll == ZXC_TOKEN_LL_MASK)) {
1087 ll += zxc_read_varint(&e_ptr, e_end);
1088 if (UNLIKELY(ll > (size_t)(l_end - l_ptr))) return ZXC_ERROR_OVERFLOW;
1089 }
1090 if (UNLIKELY(ml == ZXC_TOKEN_ML_MASK)) ml += zxc_read_varint(&e_ptr, e_end);
1092
1093 // Check bounds before wild copies - if too close to end, fall back to Safe Path
1094 if (UNLIKELY(ll + ml + ZXC_PAD_SIZE > (size_t)(d_end - d_ptr))) {
1095 t_ptr = t_save;
1096 o_ptr = o_save;
1097 e_ptr = e_save;
1098 break;
1099 }
1100
1101 // Unlike the 4x batch the copy cannot sit in the varint branch's else -
1102 // the rollback above must run first - so re-test ll instead. Exact:
1103 // the escape leaves ll >= ZXC_TOKEN_LL_MASK.
1104 if (LIKELY(ll < ZXC_TOKEN_LL_MASK)) {
1105 zxc_copy16(d_ptr, l_ptr);
1106 } else {
1107 zxc_decode_copy_literals(d_ptr, l_ptr, ll);
1108 }
1109 l_ptr += ll;
1110 d_ptr += ll;
1111
1112 if (UNLIKELY(d_ptr < d_bounds && (size_t)(d_ptr - d_floor) < offset))
1113 return ZXC_ERROR_BAD_OFFSET;
1114
1115 // The loop entry check guarantees ll + ml + ZXC_PAD_SIZE bytes of
1116 // headroom, so the wild-copy ladder (incl. overlap/fill runs) is safe.
1117 zxc_decode_copy_match_spl(d_ptr, offset, ml);
1118 d_ptr += ml;
1119 n_seq--;
1120 }
1121
1122 // --- Safe Path for Remaining Sequences ---
1123 while (n_seq > 0) {
1124 uint8_t token = *t_ptr++;
1125 uint64_t ll = token >> ZXC_TOKEN_LIT_BITS;
1126 uint64_t ml = token & ZXC_TOKEN_ML_MASK;
1127 uint32_t offset = ZXC_LZ_OFFSET_BIAS;
1128 if (SPL_OFF8) {
1129 offset += *o_ptr++; // 1-byte offset (biased)
1130 } else {
1131 offset += zxc_le16(o_ptr); // 2-byte offset (biased)
1132 o_ptr += sizeof(uint16_t);
1133 }
1134
1135 if (UNLIKELY(ll == ZXC_TOKEN_LL_MASK)) ll += zxc_read_varint(&e_ptr, e_end);
1136 if (UNLIKELY(ml == ZXC_TOKEN_ML_MASK)) ml += zxc_read_varint(&e_ptr, e_end);
1138
1139 if (UNLIKELY(ll + ml > (size_t)(d_end - d_ptr) || ll > (size_t)(l_end - l_ptr)))
1140 return ZXC_ERROR_OVERFLOW;
1141 ZXC_MEMCPY(d_ptr, l_ptr, ll);
1142 l_ptr += ll;
1143 d_ptr += ll;
1144
1145 if (UNLIKELY((size_t)(d_ptr - d_floor) < offset)) return ZXC_ERROR_BAD_OFFSET;
1146 const uint8_t* match_src = d_ptr - offset;
1147
1148 zxc_decode_copy_match_exact(d_ptr, match_src, offset, ml);
1149 d_ptr += ml;
1150 n_seq--;
1151 }
1152
1153 // --- Trailing Literals ---
1154 // Copy remaining literals from source stream (literal exhaustion)
1155 if (UNLIKELY(l_ptr > l_end)) return ZXC_ERROR_CORRUPT_DATA;
1156 if (UNLIKELY(d_ptr > d_end)) return ZXC_ERROR_OVERFLOW;
1157
1158 const size_t remaining_literals = (size_t)(l_end - l_ptr);
1159 if (UNLIKELY(remaining_literals > (size_t)(d_end - d_ptr))) return ZXC_ERROR_OVERFLOW;
1160 ZXC_MEMCPY(d_ptr, l_ptr, remaining_literals);
1161 d_ptr += remaining_literals;
1162
1163 return (int)(d_ptr - dst);
1164}
1165
1184 * @return Bytes written to @p dst on success, or a negative @ref zxc_error_t.
1185 */
1186static ZXC_ALWAYS_INLINE int zxc_decode_block_pak_impl(const zxc_cctx_t* RESTRICT ctx,
1187 const uint8_t* RESTRICT src,
1188 const size_t src_size, uint8_t* RESTRICT dst,
1189 const size_t dst_capacity, const int safe,
1190 const int has_dict) {
1192
1193 // 0 when !has_dict (safe path) -> folds `d_floor` to `dst`.
1194 const size_t dict_size = has_dict ? ctx->dict_size : 0;
1195
1196 if (UNLIKELY(zxc_read_pak_header(src, src_size, &gh) != ZXC_OK)) return ZXC_ERROR_BAD_HEADER;
1197 if (UNLIKELY(gh.enc_lit != ZXC_SECTION_ENCODING_RAW || gh.enc_tok != 0))
1199
1200 const uint8_t* const p_data = src + ZXC_PAK_HEADER_BINARY_SIZE;
1201 const uint8_t* p_curr = p_data;
1202
1203 // --- Stream Pointers & Validation ---
1204 // PAK carries no section descriptors: literals are always RAW, the sequence
1205 // stream is four bytes per sequence, and extras run to the payload end.
1206 const size_t sz_lit = gh.n_literals;
1207 const uint64_t sz_seqs = (uint64_t)gh.n_sequences * sizeof(uint32_t);
1208
1209 const size_t payload_avail = (size_t)(src + src_size - p_data);
1210 const uint64_t consumed = (uint64_t)sz_lit + sz_seqs;
1211 if (UNLIKELY(consumed > (uint64_t)payload_avail)) return ZXC_ERROR_CORRUPT_DATA;
1212 const size_t sz_exts = payload_avail - (size_t)consumed; /* slack padding included */
1213
1214 // PAK literals are always RAW, so the slack is always load-bearing here.
1215 // No underflow: sz_lit <= consumed <= payload_avail.
1216 if (UNLIKELY(payload_avail - sz_lit < ZXC_BLOCK_LIT_SLACK)) return ZXC_ERROR_CORRUPT_DATA;
1217
1218 const uint8_t* l_ptr = p_curr;
1219 const uint8_t* l_end = l_ptr + sz_lit;
1220 p_curr += sz_lit;
1221
1222 const uint8_t* seq_ptr = p_curr;
1223 const uint8_t* extras_ptr = p_curr + (size_t)sz_seqs;
1224 const uint8_t* const extras_end = extras_ptr + sz_exts;
1225
1226 uint8_t* d_ptr = dst;
1227 const uint8_t* const d_end = dst + dst_capacity;
1228 // Lowest address a match may reach: the dictionary prefix if any, else dst.
1229 const uint8_t* const d_floor = dst - dict_size;
1230 const uint8_t* const d_end_safe =
1231 (dst_capacity > ZXC_PAD_SIZE * 4) ? d_end - (ZXC_PAD_SIZE * 4) : dst; // 128
1232 // 4x loop margin: four sequences of inline output (ll <= 254, ml <= 254 + 5,
1233 // longer ones escape and check themselves) plus the wild-copy overshoot:
1234 // 4 x 513 + 32 = 2084, all of ZXC_DECOMPRESS_TAIL_PAD.
1235 const uint8_t* const d_end_fast =
1236 (dst_capacity > ZXC_DECOMPRESS_TAIL_PAD) ? d_end - ZXC_DECOMPRESS_TAIL_PAD : dst;
1237
1238 // Literal margin for the PAK loops: without a varint, ll <= 254 per sequence,
1239 // so 4 * 254 = 1016. Past that only the cold varint path checks l_ptr.
1240 const size_t pak_margin_4x = 4 * (ZXC_SEQ_LL_MASK - 1); // 1016
1241 const size_t pak_margin_1x = ZXC_SEQ_LL_MASK - 1; // 254
1242 const uint8_t* const l_end_safe_4x = (sz_lit > pak_margin_4x) ? l_end - pak_margin_4x : l_ptr;
1243 const uint8_t* const l_end_safe_1x = (sz_lit > pak_margin_1x) ? l_end - pak_margin_1x : l_ptr;
1244
1245 uint32_t n_seq = gh.n_sequences;
1246
1247 // Same handover as SPL, but the PAK offset is inline in the sequence word and
1248 // always 16 bits -- enc_off is not a width here, so the span is fixed.
1249 const size_t off_span = 1U << 16;
1250 const size_t span = (dict_size >= off_span) ? 0 : off_span - dict_size;
1251 const uint8_t* const d_bounds = (span >= dst_capacity) ? d_end : dst + span;
1252
1253 // --- SAFE loop: validate offsets until d_bounds (4x unroll) ---
1254 if (safe) {
1255 // SAFE variant: save per-batch state so an OVERFLOW can rollback and
1256 // hand over to the 1x loop / Safe Path. Wild writes already committed
1257 // are deterministically overwritten when the 1x loop replays.
1258 while (n_seq >= 4 && d_ptr < d_end_fast && l_ptr < l_end_safe_4x && d_ptr < d_bounds) {
1259 const uint8_t* const t_save = seq_ptr;
1260 const uint8_t* const e_save = extras_ptr;
1261 uint8_t* const d_save = d_ptr;
1262 const uint8_t* const l_save = l_ptr;
1263 DECODE_PAK_BATCH_4X(DECODE_MATCH_SAFE, goto rollback_safe_4x, (void)0);
1264 continue;
1265
1266 rollback_safe_4x:
1267 seq_ptr = t_save;
1268 extras_ptr = e_save;
1269 d_ptr = d_save;
1270 l_ptr = l_save;
1271 break;
1272 }
1273 } else {
1274 while (n_seq >= 4 && d_ptr < d_end_fast && l_ptr < l_end_safe_4x && d_ptr < d_bounds) {
1275 DECODE_PAK_BATCH_4X(DECODE_MATCH_SAFE, return ZXC_ERROR_OVERFLOW, (void)0);
1276 }
1277 }
1278
1279 // --- SAFE Loop tail: remaining sequences with offset validation (1x) ---
1280 while (n_seq > 0 && d_ptr < d_end_safe && d_ptr < d_bounds) {
1281 uint32_t seq = zxc_le32(seq_ptr);
1282 seq_ptr += sizeof(uint32_t);
1283
1284 uint64_t ll = seq >> ZXC_SEQ_LL_SHIFT;
1285 if (UNLIKELY(ll == ZXC_SEQ_LL_MASK)) ll += zxc_read_varint(&extras_ptr, extras_end);
1286
1287 uint32_t m_bits = (seq >> ZXC_SEQ_ML_SHIFT) & ZXC_SEQ_ML_MASK;
1288 uint64_t ml = m_bits + ZXC_LZ_MIN_MATCH_LEN;
1289 if (UNLIKELY(m_bits == ZXC_SEQ_ML_MASK)) ml += zxc_read_varint(&extras_ptr, extras_end);
1290
1291 uint32_t offset = (seq & ZXC_SEQ_OFF_MASK) + ZXC_LZ_OFFSET_BIAS;
1292
1293 // Strict bounds check: sequence must fit, AND wild copies must not overshoot
1294 // Check both destination (d_ptr) and source literal stream (l_ptr)
1295 if (UNLIKELY(ll + ml + ZXC_PAD_SIZE > (size_t)(d_end - d_ptr) ||
1296 ll + ZXC_PAD_SIZE > (size_t)(l_end - l_ptr))) {
1297 // Fallback to exact copy (slow but safe)
1298 if (UNLIKELY(ll + ml > (size_t)(d_end - d_ptr) || ll > (size_t)(l_end - l_ptr)))
1299 return ZXC_ERROR_OVERFLOW;
1300 ZXC_MEMCPY(d_ptr, l_ptr, ll);
1301 l_ptr += ll;
1302 d_ptr += ll;
1303
1304 if (UNLIKELY((size_t)(d_ptr - d_floor) < offset)) return ZXC_ERROR_BAD_OFFSET;
1305 const uint8_t* match_src = d_ptr - offset;
1306
1307 zxc_decode_copy_match_exact(d_ptr, match_src, offset, ml);
1308 d_ptr += ml;
1309 } else {
1310 zxc_decode_copy_literals(d_ptr, l_ptr, ll);
1311 l_ptr += ll;
1312 d_ptr += ll;
1313 DECODE_MATCH_SAFE(ml, offset, zxc_decode_copy_match);
1314 }
1315 n_seq--;
1316 }
1317
1318 // --- FAST Loop: After threshold, check large margin to avoid individual bounds checks ---
1319 if (safe) {
1320 while (n_seq >= 4 && d_ptr < d_end_fast && l_ptr < l_end_safe_4x) {
1321 const uint8_t* const t_save = seq_ptr;
1322 const uint8_t* const e_save = extras_ptr;
1323 uint8_t* const d_save = d_ptr;
1324 const uint8_t* const l_save = l_ptr;
1325 DECODE_PAK_BATCH_4X(DECODE_MATCH_FAST, goto rollback_fast_4x,
1326 ZXC_PREFETCH_READ(l_ptr + ZXC_CACHE_LINE_SIZE));
1327 continue;
1328
1329 rollback_fast_4x:
1330 seq_ptr = t_save;
1331 extras_ptr = e_save;
1332 d_ptr = d_save;
1333 l_ptr = l_save;
1334 break;
1335 }
1336 } else {
1337 while (n_seq >= 4 && d_ptr < d_end_fast && l_ptr < l_end_safe_4x) {
1338 DECODE_PAK_BATCH_4X(DECODE_MATCH_FAST, return ZXC_ERROR_OVERFLOW,
1339 ZXC_PREFETCH_READ(l_ptr + ZXC_CACHE_LINE_SIZE));
1340 }
1341 }
1342
1343 // --- Remaining 1 sequence (Fast Path) ---
1344 while (n_seq > 0 && d_ptr < d_end_safe && l_ptr < l_end_safe_1x) {
1345 // Save state for fallback
1346 const uint8_t* seq_save = seq_ptr;
1347 const uint8_t* ext_save = extras_ptr;
1348
1349 const uint32_t seq = zxc_le32(seq_ptr);
1350 seq_ptr += sizeof(uint32_t);
1351
1352 uint64_t ll = seq >> ZXC_SEQ_LL_SHIFT;
1353 if (UNLIKELY(ll == ZXC_SEQ_LL_MASK)) {
1354 ll += zxc_read_varint(&extras_ptr, extras_end);
1355 if (UNLIKELY(ll > (size_t)(l_end - l_ptr))) return ZXC_ERROR_OVERFLOW;
1356 }
1357
1358 uint32_t m_bits = (seq >> ZXC_SEQ_ML_SHIFT) & ZXC_SEQ_ML_MASK;
1359 uint64_t ml = m_bits + ZXC_LZ_MIN_MATCH_LEN;
1360 if (UNLIKELY(m_bits == ZXC_SEQ_ML_MASK)) ml += zxc_read_varint(&extras_ptr, extras_end);
1361
1362 // Strict bounds checks (including wild copy overrun safety)
1363 if (UNLIKELY(ll + ml + ZXC_PAD_SIZE > (size_t)(d_end - d_ptr) ||
1364 ll + ZXC_PAD_SIZE > (size_t)(l_end - l_ptr))) {
1365 seq_ptr = seq_save;
1366 extras_ptr = ext_save;
1367 break;
1368 }
1369 uint32_t offset = (seq & ZXC_SEQ_OFF_MASK) + ZXC_LZ_OFFSET_BIAS;
1370
1371 zxc_decode_copy_literals(d_ptr, l_ptr, ll);
1372 l_ptr += ll;
1373 d_ptr += ll;
1374
1375 if (UNLIKELY(d_ptr < d_bounds && (size_t)(d_ptr - d_floor) < offset))
1376 return ZXC_ERROR_BAD_OFFSET;
1377
1378 // The loop entry check guarantees ll + ml + ZXC_PAD_SIZE bytes of
1379 // headroom, so the wild-copy ladder (incl. overlap/fill runs) is safe.
1380 zxc_decode_copy_match(d_ptr, offset, ml);
1381 d_ptr += ml;
1382 n_seq--;
1383 }
1384
1385 // --- Safe Path for Remaining Sequences ---
1386 while (n_seq > 0) {
1387 uint32_t seq = zxc_le32(seq_ptr);
1388 seq_ptr += sizeof(uint32_t);
1389
1390 uint64_t ll = seq >> ZXC_SEQ_LL_SHIFT;
1391 if (UNLIKELY(ll == ZXC_SEQ_LL_MASK)) ll += zxc_read_varint(&extras_ptr, extras_end);
1392
1393 uint32_t m_bits = (seq >> ZXC_SEQ_ML_SHIFT) & ZXC_SEQ_ML_MASK;
1394 uint64_t ml = m_bits + ZXC_LZ_MIN_MATCH_LEN;
1395 if (UNLIKELY(m_bits == ZXC_SEQ_ML_MASK)) ml += zxc_read_varint(&extras_ptr, extras_end);
1396 uint32_t offset = (seq & ZXC_SEQ_OFF_MASK) + ZXC_LZ_OFFSET_BIAS;
1397
1398 if (UNLIKELY(ll + ml > (size_t)(d_end - d_ptr) || ll > (size_t)(l_end - l_ptr)))
1399 return ZXC_ERROR_OVERFLOW;
1400 ZXC_MEMCPY(d_ptr, l_ptr, ll);
1401 l_ptr += ll;
1402 d_ptr += ll;
1403
1404 if (UNLIKELY((size_t)(d_ptr - d_floor) < offset)) return ZXC_ERROR_BAD_OFFSET;
1405 const uint8_t* match_src = d_ptr - offset;
1406
1407 zxc_decode_copy_match_exact(d_ptr, match_src, offset, ml);
1408 d_ptr += ml;
1409 n_seq--;
1410 }
1411
1412 // --- Trailing Literals ---
1413 // Copy remaining literals from source stream (literal exhaustion)
1414 if (UNLIKELY(l_ptr > l_end)) return ZXC_ERROR_CORRUPT_DATA;
1415 if (UNLIKELY(d_ptr > d_end)) return ZXC_ERROR_OVERFLOW;
1416
1417 const size_t remaining_literals = (size_t)(l_end - l_ptr);
1418 if (UNLIKELY(remaining_literals > (size_t)(d_end - d_ptr))) return ZXC_ERROR_OVERFLOW;
1419 ZXC_MEMCPY(d_ptr, l_ptr, remaining_literals);
1420 d_ptr += remaining_literals;
1421
1422 return (int)(d_ptr - dst);
1423}
1424
1428 * inlined impl is fully specialized and the RAW-token fast path stays untouched.
1429 */
1430static ZXC_NOINLINE int zxc_decode_block_spl_entropy(const zxc_cctx_t* RESTRICT ctx,
1431 const uint8_t* RESTRICT src,
1432 const size_t src_size, uint8_t* RESTRICT dst,
1433 const size_t dst_capacity) {
1434 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 0, 0, 1);
1435}
1436
1437#ifndef ZXC_NO_DICT
1438static ZXC_NOINLINE int zxc_decode_block_spl_entropy_dict(const zxc_cctx_t* RESTRICT ctx,
1439 const uint8_t* RESTRICT src,
1440 const size_t src_size,
1441 uint8_t* RESTRICT dst,
1442 const size_t dst_capacity) {
1443 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 0, 1, 1);
1444}
1445#endif // ZXC_NO_DICT
1446
1447static ZXC_NOINLINE int zxc_decode_block_spl_entropy_safe(const zxc_cctx_t* RESTRICT ctx,
1448 const uint8_t* RESTRICT src,
1449 const size_t src_size,
1450 uint8_t* RESTRICT dst,
1451 const size_t dst_capacity) {
1452 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 1, 0, 1);
1453}
1454
1466 * @return Bytes written on success, or a negative @ref zxc_error_t.
1467 */
1468static int zxc_decode_block_spl(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1469 const size_t src_size, uint8_t* RESTRICT dst,
1470 const size_t dst_capacity) {
1471 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 0, 0, 0);
1472}
1473
1484 * @return Bytes written on success, or a negative @ref zxc_error_t.
1485 */
1486static int zxc_decode_block_pak(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1487 const size_t src_size, uint8_t* RESTRICT dst,
1488 const size_t dst_capacity) {
1489 return zxc_decode_block_pak_impl(ctx, src, src_size, dst, dst_capacity, 0, 0);
1490}
1491
1492#ifndef ZXC_NO_DICT
1505 * @return Bytes written on success, or a negative @ref zxc_error_t.
1506 */
1507static ZXC_NOINLINE int zxc_decode_block_spl_dict(const zxc_cctx_t* RESTRICT ctx,
1508 const uint8_t* RESTRICT src,
1509 const size_t src_size, uint8_t* RESTRICT dst,
1510 const size_t dst_capacity) {
1511 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 0, 1, 0);
1512}
1513#endif // ZXC_NO_DICT
1514
1515#ifndef ZXC_NO_DICT
1527 * @return Bytes written on success, or a negative @ref zxc_error_t.
1528 */
1529static ZXC_NOINLINE int zxc_decode_block_pak_dict(const zxc_cctx_t* RESTRICT ctx,
1530 const uint8_t* RESTRICT src,
1531 const size_t src_size, uint8_t* RESTRICT dst,
1532 const size_t dst_capacity) {
1533 return zxc_decode_block_pak_impl(ctx, src, src_size, dst, dst_capacity, 0, 1);
1534}
1535#endif // ZXC_NO_DICT
1536
1549 * @return Bytes written on success, or a negative @ref zxc_error_t.
1550 */
1551static ZXC_NOINLINE int zxc_decode_block_spl_safe(const zxc_cctx_t* RESTRICT ctx,
1552 const uint8_t* RESTRICT src,
1553 const size_t src_size, uint8_t* RESTRICT dst,
1554 const size_t dst_capacity) {
1555 return zxc_decode_block_spl_impl(ctx, src, src_size, dst, dst_capacity, 1, 0, 0);
1556}
1557
1570 * @return Bytes written on success, or a negative @ref zxc_error_t.
1571 */
1572static ZXC_NOINLINE int zxc_decode_block_pak_safe(const zxc_cctx_t* RESTRICT ctx,
1573 const uint8_t* RESTRICT src,
1574 const size_t src_size, uint8_t* RESTRICT dst,
1575 const size_t dst_capacity) {
1576 return zxc_decode_block_pak_impl(ctx, src, src_size, dst, dst_capacity, 1, 0);
1577}
1578
1579#undef DECODE_PAK_BATCH_4X
1580#undef DECODE_PAK_SEQ
1581#undef DECODE_SPL_BATCH_4X
1582#undef DECODE_SPL_SEQ
1583#undef DECODE_MATCH_FAST
1584#undef SPL_OFF8
1585#undef DECODE_MATCH_SAFE
1586
1605 * @return Bytes written on success, or a negative @ref zxc_error_t.
1606 */
1608 const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src, const size_t src_sz,
1609 uint8_t* RESTRICT dst, const size_t dst_cap, const uint64_t block_index, const int has_dict,
1610 const int safe) {
1611 if (UNLIKELY(src_sz < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
1612 if (UNLIKELY(!zxc_block_header_ok(src))) return ZXC_ERROR_BAD_HEADER;
1613
1614 const uint8_t type = src[0];
1615 const uint32_t comp_sz = zxc_le32(src + 3);
1616 const int has_checksum = ctx->checksum_enabled;
1617
1618 // A block never compresses past its own content size
1619 if (UNLIKELY((uint64_t)comp_sz > (uint64_t)ctx->chunk_size)) return ZXC_ERROR_BAD_BLOCK_SIZE;
1620
1621 // Check bounds: Header + Body + Checksum(if any)
1622 const size_t expected_sz =
1623 (size_t)ZXC_BLOCK_HEADER_SIZE + comp_sz + (has_checksum ? ZXC_BLOCK_CHECKSUM_SIZE : 0);
1624 if (UNLIKELY(src_sz < expected_sz)) return ZXC_ERROR_SRC_TOO_SMALL;
1625
1626 const uint8_t* data = src + ZXC_BLOCK_HEADER_SIZE;
1627
1628 int decoded_sz = ZXC_ERROR_BAD_BLOCK_TYPE;
1629
1630 switch (type) {
1631 case ZXC_BLOCK_SPL:
1632 decoded_sz = safe ? zxc_decode_block_spl_safe(ctx, data, comp_sz, dst, dst_cap)
1633 : has_dict ? zxc_decode_block_spl_dict(ctx, data, comp_sz, dst, dst_cap)
1634 : zxc_decode_block_spl(ctx, data, comp_sz, dst, dst_cap);
1635 break;
1636 case ZXC_BLOCK_PAK:
1637 decoded_sz = safe ? zxc_decode_block_pak_safe(ctx, data, comp_sz, dst, dst_cap)
1638 : has_dict ? zxc_decode_block_pak_dict(ctx, data, comp_sz, dst, dst_cap)
1639 : zxc_decode_block_pak(ctx, data, comp_sz, dst, dst_cap);
1640 break;
1641 case ZXC_BLOCK_RAW:
1642 // For RAW blocks, comp_sz == raw_sz (uncompressed data stored as-is)
1643 if (UNLIKELY(comp_sz > dst_cap)) return ZXC_ERROR_DST_TOO_SMALL;
1644 ZXC_MEMCPY(dst, data, comp_sz);
1645 decoded_sz = (int)comp_sz;
1646 break;
1647 case ZXC_BLOCK_EOF:
1648 // EOF should be handled by the dispatcher, not here
1650 default:
1652 }
1653
1654 // dst_cap includes the wild-copy margin: bound the block itself
1655 if (UNLIKELY(decoded_sz > 0 && (size_t)decoded_sz > ctx->chunk_size))
1657
1658 if (has_checksum && LIKELY(decoded_sz >= 0)) {
1659 const uint32_t stored = zxc_le32(data + comp_sz);
1660 if (UNLIKELY(stored !=
1661 zxc_checksum(dst, (size_t)decoded_sz, block_index, ZXC_CHECKSUM_RAPIDHASH)))
1663 }
1664
1665 return decoded_sz;
1666}
1667
1674// cppcheck-suppress unusedFunction
1675int zxc_decompress_chunk_wrapper(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1676 const size_t src_sz, uint8_t* RESTRICT dst, const size_t dst_cap,
1677 const uint64_t block_index) {
1678 return zxc_decompress_chunk_wrapper_body(ctx, src, src_sz, dst, dst_cap, block_index, 0, 0);
1679}
1680
1681#ifndef ZXC_NO_DICT
1697// cppcheck-suppress unusedFunction
1698int zxc_decompress_chunk_wrapper_dict(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1699 const size_t src_sz, uint8_t* RESTRICT dst,
1700 const size_t dst_cap, const uint64_t block_index) {
1701 return zxc_decompress_chunk_wrapper_body(ctx, src, src_sz, dst, dst_cap, block_index, 1, 0);
1702}
1703#endif // ZXC_NO_DICT
1704
1721// cppcheck-suppress unusedFunction
1722int zxc_decompress_chunk_wrapper_safe(const zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT src,
1723 const size_t src_sz, uint8_t* RESTRICT dst,
1724 const size_t dst_cap, const uint64_t block_index) {
1725 return zxc_decompress_chunk_wrapper_body(ctx, src, src_sz, dst, dst_cap, block_index, 0, 1);
1726}
@ ZXC_ERROR_BAD_BLOCK_TYPE
Unknown or unexpected block type.
Definition zxc_error.h:65
@ ZXC_ERROR_OVERFLOW
Buffer overflow detected during processing.
Definition zxc_error.h:58
@ ZXC_ERROR_BAD_OFFSET
Invalid match offset during decompression.
Definition zxc_error.h:57
@ ZXC_ERROR_CORRUPT_DATA
Corrupted compressed data.
Definition zxc_error.h:56
@ ZXC_ERROR_BAD_HEADER
Corrupted or invalid header (checksum mismatch).
Definition zxc_error.h:50
@ ZXC_ERROR_DST_TOO_SMALL
Destination buffer too small.
Definition zxc_error.h:44
@ ZXC_ERROR_SRC_TOO_SMALL
Source buffer too small or truncated input.
Definition zxc_error.h:45
@ ZXC_ERROR_DICT_REQUIRED
File requires a dictionary but none was provided.
Definition zxc_error.h:69
@ ZXC_ERROR_BAD_CHECKSUM
A block's decoded bytes fail its checksum, or the archive digest mismatches.
Definition zxc_error.h:51
@ ZXC_OK
Success (no error).
Definition zxc_error.h:38
@ ZXC_ERROR_BAD_BLOCK_SIZE
Invalid block size.
Definition zxc_error.h:66
#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_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_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_SEQ_LL_SHIFT
Shift of the Literal Length field: the top byte of the word.
#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_MIN_MATCH_LEN
Minimum match length for an LZ77 match.
#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_PAK_HEADER_BINARY_SIZE
Binary size of a PAK block sub-header.
#define ZXC_NOINLINE
Prevents inlining (best-effort no-op fallback for unknown compilers).
#define ZXC_SPL_MAX_INLINE_ML
Longest match a SPL sequence carries without a varint extension.
#define ZXC_ALIGN(x)
Specifies memory alignment using C11 _Alignas.
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_TOKEN_LIT_BITS
Bits for Literal Length in a SPL token.
#define ZXC_DECOMPRESS_TAIL_PAD
Tail padding required on the decompression destination buffer.
#define ZXC_SEQ_LL_MASK
Mask to extract Literal Length from a PAK sequence.
Compression / decompression context.
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.
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).
Build configuration: what the ZXC_BUILD_SIMD_VARIANTS choice runs, derived once.
int zxc_cctx_alloc_entropy_scratch(zxc_cctx_t *ctx)
Lazily allocates the deferred decode-side entropy scratch.
Definition zxc_common.c:355
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)
Parses a SPL block header and its section descriptors from src.
Definition zxc_common.c:958
int zxc_read_pak_header(const uint8_t *src, const size_t len, zxc_gnr_header_t *gh)
Parses a PAK block header from src.
static void zxc_wild_copy32(uint8_t *dst, const uint8_t *src, const size_t len)
Copies len bytes in 32-byte wild chunks (the zxc_copy32 width).
static int zxc_decode_block_spl_safe(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a SPL block with the strict-tail safe loop (no wild copies).
#define SPL_OFF8
True when the SPL offset stream stores 1-byte offsets, 2-byte otherwise.
static void zxc_decode_copy_match_short(uint8_t *d_ptr, const uint32_t off, const uint64_t ml)
Match copy for a length that cannot exceed 32 bytes.
static int zxc_ensure_entropy_scratch(const zxc_cctx_t *ctx)
Ensures the entropy decode scratch (tok_buffer + pivco_scratch) is available before decoding an entro...
static void zxc_decode_copy_match_exact(uint8_t *d_ptr, const uint8_t *match_src, const size_t off, const size_t ml)
Exact-size match copy for the tail loops (no overshoot headroom).
static void zxc_decode_copy_overlap_short(uint8_t *dst, const uint32_t off, const uint64_t ml)
Overlap copy for a run of period off (2..31) bounded by ml <= 32.
static void zxc_decode_copy_match(uint8_t *d_ptr, const uint32_t off, const uint64_t ml)
Copies an ml-byte LZ match from d_ptr-off to d_ptr, handling overlap.
static void zxc_decode_copy_overlap_run32(uint8_t *dst, const uint32_t off, const uint64_t ml)
Copies an ml-byte run of period off (2..31) with 32-byte stores.
#define DECODE_SPL_BATCH_4X(DECODE, ON_FAIL)
One full SPL 4x batch: token word, four offsets (1- or 2-byte form), four DECODE_SPL_SEQ emissions,...
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.
static int zxc_decode_block_pak_impl(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity, const int safe, const int has_dict)
Unified PAK (packed sequences) block decoder body, shared by the fast, safe and dictionary variants.
#define DECODE_PAK_BATCH_4X(DECODE, ON_FAIL, PREFETCH)
One full PAK 4x batch.
static void zxc_decode_copy_literals(uint8_t *dst, const uint8_t *src, const uint64_t ll)
Copies ll literal bytes from src to dst using 32-byte wild copies.
static int zxc_decode_block_pak(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a no-dict PAK block (plain, inlinable path).
static int zxc_decode_block_pak_dict(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a PAK block against a dictionary prefix (cold path).
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)
Public no-dict chunk decoder (decompression hot path).
static const uint8_t zxc_overlap_strides32[32]
Store stride for the 32-byte pattern: (32 / off) * off.
static int zxc_decode_block_spl(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a no-dict SPL block (plain, inlinable path).
static void zxc_decode_copy_match_spl(uint8_t *d_ptr, const uint32_t off, const uint64_t ml)
SPL match copy: bounded form when the ml nibble did not saturate.
static int zxc_decode_block_spl_impl(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity, const int safe, const int has_dict, const int tok_entropy)
Unified SPL (split streams) block decoder body, shared by the fast, safe, dictionary and entropy-toke...
static int zxc_decode_block_pak_safe(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a PAK block with the strict-tail safe loop (no wild copies).
static void zxc_decode_fill_run(uint8_t *dst, const uint8_t byte, const uint64_t ml)
Fills an ml-byte single-byte run (LZ offset == 1) with wild stores.
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)
Public strict-tail safe chunk decoder (dst_cap == exact decoded size).
static int zxc_decode_block_spl_entropy(const zxc_cctx_t *ctx, const uint8_t *src, size_t src_size, uint8_t *dst, size_t dst_capacity)
Cold specializations for entropy-coded SPL tokens (level 7).
static int zxc_decompress_chunk_wrapper_body(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, const int has_dict, const int safe)
Shared chunk-decode body: validates the header, decodes, then verifies the optional checksum.
static int zxc_decode_block_spl_dict(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_size, uint8_t *dst, const size_t dst_capacity)
Decode a SPL block against a dictionary prefix (cold path).
int zxc_huf_decode_section_dict(const uint8_t *payload, const size_t payload_size, uint8_t *dst, const size_t n, const zxc_pivco_tree_t *tree, uint8_t *scratch)
Decode a PivCo dict section against a prebuilt dict tree.
int zxc_huf_decode_section(const uint8_t *payload, const size_t payload_size, uint8_t *dst, const size_t n, uint8_t *scratch)
Decode a PivCo literal section into dst (exactly n bytes).
Error codes and error-name lookup for the ZXC library.
Internal definitions, constants, SIMD helpers, and utility functions.
#define ZXC_PIVCO_SCRATCH_PAD
Extra scratch slack required past n by the PivCo decoder.
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 uint16_t zxc_le16(const void *p)
Reads a little-endian 16-bit value from a possibly unaligned address.
static void zxc_copy16(void *dst, const void *src)
Copies exactly 16 bytes as one vector move where the ISA has one.
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 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 ...