ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_huffman.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 */
8
33
34// Function Multi-Versioning Support
35// With ZXC_FUNCTION_SUFFIX defined (e.g. _avx2), each variant TU gets its own
36// copy under a unique symbol, which the runtime dispatcher routes to. The
37// defines precede zxc_internal.h so the header's prototypes take the same
38// suffix as the definitions below.
39#ifdef ZXC_FUNCTION_SUFFIX
40#define ZXC_CAT_IMPL(x, y) x##y
41#define ZXC_CAT(x, y) ZXC_CAT_IMPL(x, y)
42#define zxc_huf_build_code_lengths ZXC_CAT(zxc_huf_build_code_lengths, ZXC_FUNCTION_SUFFIX)
43#define zxc_huf_pack_lengths ZXC_CAT(zxc_huf_pack_lengths, ZXC_FUNCTION_SUFFIX)
44#define zxc_huf_unpack_lengths ZXC_CAT(zxc_huf_unpack_lengths, ZXC_FUNCTION_SUFFIX)
45#define zxc_huf_calc_size ZXC_CAT(zxc_huf_calc_size, ZXC_FUNCTION_SUFFIX)
46#define zxc_huf_calc_size_dict ZXC_CAT(zxc_huf_calc_size_dict, ZXC_FUNCTION_SUFFIX)
47#define zxc_huf_encode_section ZXC_CAT(zxc_huf_encode_section, ZXC_FUNCTION_SUFFIX)
48#define zxc_huf_encode_section_dict ZXC_CAT(zxc_huf_encode_section_dict, ZXC_FUNCTION_SUFFIX)
49#define zxc_huf_decode_section ZXC_CAT(zxc_huf_decode_section, ZXC_FUNCTION_SUFFIX)
50#define zxc_huf_decode_section_dict ZXC_CAT(zxc_huf_decode_section_dict, ZXC_FUNCTION_SUFFIX)
51#endif
52
53// Mark the primary variant (only _default, or a no-suffix build) so ISA-
54// independent cold code compiles once, not in every per-ISA copy. Keyed off the
55// suffix value, so every build gets it with no extra flag.
56#ifdef ZXC_FUNCTION_SUFFIX
57#define ZXC_PRIMARY__default 1
58#define ZXC_PRIMARY__avx2 0
59#define ZXC_PRIMARY__avx512 0
60#define ZXC_PRIMARY__neon32 0
61#define ZXC_PRIMARY_CAT_(a, b) a##b
62#define ZXC_PRIMARY_CAT(a, b) ZXC_PRIMARY_CAT_(a, b)
63#if ZXC_PRIMARY_CAT(ZXC_PRIMARY_, ZXC_FUNCTION_SUFFIX)
64#define ZXC_VARIANT_PRIMARY 1
65#endif
66#else
67#define ZXC_VARIANT_PRIMARY 1
68#endif
69
71#include "zxc_internal.h"
72#include "zxc_pivco_tables.h"
73
74// SIMD variants drop the roles bound to _default; the primary copy keeps all.
75#if !defined(ZXC_VARIANT_PRIMARY) && defined(ZXC_ENCODER_DEFAULT)
76#define ZXC_HUF_NO_ENCODER
77#endif
78#if !defined(ZXC_VARIANT_PRIMARY) && defined(ZXC_ENTROPY_DECODER_DEFAULT)
79#define ZXC_HUF_NO_DECODER
80#endif
81#if !defined(ZXC_VARIANT_PRIMARY) && defined(ZXC_NO_DICT)
82#define ZXC_HUF_NO_DICT_SECTIONS
83#endif
84
85// ===========================================================================
86// Length-limited Huffman: boundary package-merge
87// ===========================================================================
88//
89// Builds optimal length-limited Huffman code lengths (max length
90// ZXC_HUF_MAX_CODE_LEN_ULTRA) on 256-symbol alphabets. Package-merge is run for
91// ZXC_HUF_MAX_CODE_LEN_ULTRA levels; each level holds up to 2N items (leaves +
92// paired packages). Selection of the cheapest 2N - 2 items at level
93// ZXC_HUF_MAX_CODE_LEN_ULTRA gives the appearance count of each leaf, which is
94// its code length.
95
96#ifndef ZXC_HUF_NO_ENCODER
97typedef zxc_huf_pm_item_t pm_item_t;
98
99typedef zxc_huf_pm_leaf_t pm_leaf_t;
100
101typedef zxc_huf_pm_frame_t frame_t;
102
120static void pm_leaves_sort(pm_leaf_t* RESTRICT leaves, const int n) {
121 // One bucket per possible value of floor(log2(weight)) for a 32-bit
122 // weight, i.e. 32 buckets.
123 enum { NUM_BUCKETS = 32 };
124 int count[NUM_BUCKETS];
125 int offset[NUM_BUCKETS + 1]; /* +1 sentinel = n, avoids end-of-bucket branch. */
126 uint8_t bucket_of[ZXC_HUF_NUM_SYMBOLS];
127 pm_leaf_t tmp[ZXC_HUF_NUM_SYMBOLS];
128
129 ZXC_MEMSET(count, 0, sizeof(count));
130 for (int i = 0; i < n; i++) {
131 const unsigned b = zxc_log2_u32(leaves[i].w);
132 bucket_of[i] = (uint8_t)b;
133 count[b]++;
134 }
135
136 int acc = 0;
137 for (int b = 0; b < NUM_BUCKETS; b++) {
138 offset[b] = acc;
139 acc += count[b];
140 }
141 offset[NUM_BUCKETS] = n;
142
143 int pos[NUM_BUCKETS];
144 ZXC_MEMCPY(pos, offset, sizeof(pos));
145 for (int i = 0; i < n; i++) {
146 tmp[pos[bucket_of[i]]++] = leaves[i];
147 }
148
149 for (int b = 0; b < NUM_BUCKETS; b++) {
150 if (count[b] < 2) continue;
151 const int s = offset[b];
152 const int e = offset[b + 1];
153 for (int i = s + 1; i < e; i++) {
154 const pm_leaf_t key = tmp[i];
155 int j = i - 1;
156 while (j >= s && (tmp[j].w > key.w || (tmp[j].w == key.w && tmp[j].sym > key.sym))) {
157 tmp[j + 1] = tmp[j];
158 j--;
159 }
160 tmp[j + 1] = key;
161 }
162 }
163
164 ZXC_MEMCPY(leaves, tmp, (size_t)n * sizeof(pm_leaf_t));
165}
166
175int zxc_huf_build_code_lengths(const uint32_t* RESTRICT freq, uint8_t* RESTRICT code_len,
176 void* RESTRICT scratch, const int max_code_len) {
177 ZXC_MEMSET(code_len, 0, ZXC_HUF_NUM_SYMBOLS);
178
179 pm_leaf_t leaves[ZXC_HUF_NUM_SYMBOLS];
180 int n = 0;
181 for (int i = 0; i < ZXC_HUF_NUM_SYMBOLS; i++) {
182 if (freq[i] > 0) {
183 leaves[n].w = freq[i];
184 leaves[n].sym = (int16_t)i;
185 n++;
186 }
187 }
188 if (UNLIKELY(n == 0)) return ZXC_ERROR_CORRUPT_DATA;
189 if (n == 1) {
190 code_len[leaves[0].sym] = 1;
191 return ZXC_OK;
192 }
193
194 pm_leaves_sort(leaves, n);
195
196 // Callers pass max_code_len >= 8, and n <= 256 <= 2^max_code_len, so the
197 // length limit is always feasible (a full 8-bit code covers all 256 symbols).
198 const int max_per_level = 2 * n;
199
200 // Working buffers: either carve from caller-provided scratch (sized for
201 // the worst-case alphabet) or fall back to per-call malloc/free.
202 pm_item_t* items;
203 int* counts;
204 frame_t* stack;
205 pm_item_t* owned_items = NULL;
206 int* owned_counts = NULL;
207 frame_t* owned_stack = NULL;
208 if (scratch) {
209 uint8_t* p = (uint8_t*)scratch;
210 items = (pm_item_t*)p;
211 p +=
212 (size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * (size_t)ZXC_HUF_PM_LEVEL_BOUND * sizeof(pm_item_t);
213 p = (uint8_t*)(((uintptr_t)p + 7U) & ~(uintptr_t)7U);
214 counts = (int*)p;
215 ZXC_MEMSET(counts, 0, (size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * sizeof(int));
216 p += (size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA * sizeof(int);
217 p = (uint8_t*)(((uintptr_t)p + 7U) & ~(uintptr_t)7U);
218 stack = (frame_t*)p;
219 } else {
220 owned_items = (pm_item_t*)ZXC_MALLOC((size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA *
221 (size_t)max_per_level * sizeof(pm_item_t));
222 owned_counts = (int*)ZXC_CALLOC((size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA, sizeof(int));
223 owned_stack = (frame_t*)ZXC_MALLOC((size_t)ZXC_HUF_MAX_CODE_LEN_ULTRA *
224 (size_t)max_per_level * sizeof(frame_t));
225 if (UNLIKELY(!owned_items || !owned_counts || !owned_stack)) {
226 ZXC_FREE(owned_items);
227 ZXC_FREE(owned_counts);
228 ZXC_FREE(owned_stack);
229 return ZXC_ERROR_MEMORY;
230 }
231 items = owned_items;
232 counts = owned_counts;
233 stack = owned_stack;
234 }
235#define ITEM(k, i) items[(size_t)(k) * (size_t)max_per_level + (size_t)(i)]
236
237 // Level 0 (logical level 1): the leaves themselves, already sorted.
238 for (int i = 0; i < n; i++) {
239 ITEM(0, i).weight = leaves[i].w;
240 ITEM(0, i).left = -1;
241 ITEM(0, i).right = -1;
242 ITEM(0, i).sym = leaves[i].sym;
243 }
244 counts[0] = n;
245
246 // Levels 1..max_code_len-1: merge sorted leaves with sorted packages from the previous
247 // level.
248 for (int k = 1; k < max_code_len; k++) {
249 const int prev = counts[k - 1];
250 const int packs = prev / 2;
251 int li = 0;
252 int pi = 0;
253 int n_lvl = 0;
254 while (li < n || pi < packs) {
255 const uint32_t wl = (li < n) ? leaves[li].w : UINT32_MAX;
256 const uint32_t wp =
257 (pi < packs)
258 ? (uint32_t)(ITEM(k - 1, 2 * pi).weight + ITEM(k - 1, 2 * pi + 1).weight)
259 : UINT32_MAX;
260 if (wl <= wp && li < n) {
261 ITEM(k, n_lvl).weight = wl;
262 ITEM(k, n_lvl).left = -1;
263 ITEM(k, n_lvl).right = -1;
264 ITEM(k, n_lvl).sym = leaves[li].sym;
265 li++;
266 } else {
267 ITEM(k, n_lvl).weight = wp;
268 ITEM(k, n_lvl).left = (int16_t)(2 * pi);
269 ITEM(k, n_lvl).right = (int16_t)(2 * pi + 1);
270 ITEM(k, n_lvl).sym = -1;
271 pi++;
272 }
273 n_lvl++;
274 }
275 counts[k] = n_lvl;
276 }
277
278 // Step 3: take first 2n-2 items at level max_code_len-1; trace back, counting leaf
279 // appearances.
280 int n_take = 2 * n - 2;
281 if (n_take > counts[max_code_len - 1]) n_take = counts[max_code_len - 1];
282
283 // Worst case stack depth: (max_code_len * n_take) frames; bounded by
284 // max_code_len * 2n <= ZXC_HUF_MAX_CODE_LEN_ULTRA * 2n. `stack` was set up earlier from
285 // scratch (or the local malloc fallback), sized for the ceiling.
286 int sp = 0;
287 for (int i = 0; i < n_take; i++) {
288 stack[sp].lvl = (int8_t)(max_code_len - 1);
289 stack[sp].idx = (int16_t)i;
290 sp++;
291 }
292 while (sp > 0) {
293 frame_t f = stack[--sp];
294 const pm_item_t* it = &ITEM(f.lvl, f.idx);
295 if (it->sym >= 0) {
296 code_len[it->sym]++;
297 } else {
298 stack[sp].lvl = (int8_t)(f.lvl - 1);
299 stack[sp].idx = it->left;
300 sp++;
301 stack[sp].lvl = (int8_t)(f.lvl - 1);
302 stack[sp].idx = it->right;
303 sp++;
304 }
305 }
306
307 if (owned_items) {
308 ZXC_FREE(owned_items);
309 ZXC_FREE(owned_counts);
310 ZXC_FREE(owned_stack);
311 }
312#undef ITEM
313 return ZXC_OK;
314}
315
316// ===========================================================================
317// Encoder-side joint flat/length nudge (idea: pivco-huffman issue #20)
318// ===========================================================================
319//
320// Package-merge minimizes bits alone; the PivCo decoder's cost also depends on
321// the SHAPE of the length histogram (pass count = max_depth + 1, and maximal
322// complete subtrees collapse into single unpacks -- see the decode section).
323// The functions below reshape the class counts toward power-of-two boundaries
324// and shallower caps under an adoption guard, trading a bounded ratio loss for
325// fewer modeled decode level-touches.
326//
327// Everything is exact integer arithmetic on the canonical code space. With
328// leaves assigned in (length, symbol) ascending order -- the canonical rule of
329// zxc_pivco_tree_build -- the depth-l leaves occupy one contiguous ALIGNED run
330// [S_{l-1}, S_l) of the code space at 2^-11 slot granularity, where
331// S_l = sum_{j<=l} bl_count[j] << (11-j) (each prior term is divisible by
332// 2^(12-l), so runs start on even slot boundaries). The maximal dyadic (buddy)
333// blocks of each run are EXACTLY the decoder's maximal flat subtrees, so any
334// candidate histogram is priced without building a tree.
335//
336// Compiled once in the primary variant: this is ISA-independent cold encoder
337// policy, and a single copy guarantees cross-ISA identical archives. For an
338// A/B build without the nudge, set ZXC_HUF_NUDGE_MERGE_Q8 to 0 in
339// zxc_internal.h: the guard then rejects every candidate.
340#if defined(ZXC_VARIANT_PRIMARY)
341
343typedef struct {
344 uint64_t bits;
345 uint64_t touches;
346} zxc_huf_nudge_cost_t;
347
356static int zxc_huf_nudge_classes(const uint8_t* RESTRICT code_len, uint32_t* RESTRICT blc) {
357 ZXC_MEMSET(blc, 0, (ZXC_HUF_MAX_CODE_LEN_ULTRA + 1) * sizeof(uint32_t));
358 int n = 0;
359 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++) {
360 const int l = code_len[s];
361 if (!l) continue;
362 blc[l]++;
363 n++;
364 }
365 return n;
366}
367
377static void zxc_huf_nudge_pf_canonical(const uint8_t* RESTRICT code_len,
378 const uint32_t* RESTRICT freq, const uint32_t* RESTRICT blc,
379 uint64_t* RESTRICT pf) {
380 uint32_t pos[ZXC_HUF_MAX_CODE_LEN_ULTRA + 1];
381 uint32_t acc = 0;
382 for (int l = 1; l <= ZXC_HUF_MAX_CODE_LEN_ULTRA; l++) {
383 pos[l] = acc;
384 acc += blc[l];
385 }
386 uint32_t val[ZXC_HUF_NUM_SYMBOLS];
387 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++) {
388 const int l = code_len[s];
389 if (l) val[pos[l]++] = freq[s];
390 }
391 pf[0] = 0;
392 for (uint32_t i = 0; i < acc; i++) pf[i + 1] = pf[i] + val[i];
393}
394
413static void zxc_huf_nudge_eval(const uint32_t* RESTRICT blc, const uint64_t* RESTRICT pf,
414 zxc_huf_nudge_cost_t* RESTRICT out) {
415 enum { LU = ZXC_HUF_MAX_CODE_LEN_ULTRA };
416 uint64_t bits = 0;
417 uint64_t touches = 0;
418 int max_len = 0;
419 uint32_t S = 0; /* code-space cursor, in 2^-LU slots */
420 uint32_t base = 0; /* leaf index where the current run starts */
421 for (int l = 1; l <= LU; l++) {
422 if (!blc[l]) continue;
423 max_len = l;
424 bits += (uint64_t)l * (pf[base + blc[l]] - pf[base]);
425 const uint32_t w = 1U << (LU - l);
426 const uint32_t end = S + blc[l] * w;
427 uint32_t x = S;
428 while (x < end) {
429 const uint32_t wx = x ? (x & (0U - x)) : (1U << LU);
430 const uint32_t wr = 1U << zxc_log2_u32(end - x);
431 const uint32_t W = wx < wr ? wx : wr;
432 const int D = (int)zxc_log2_u32(W) - (LU - l);
433 const uint32_t i0 = base + ((x - S) >> (LU - l));
434 const uint64_t mass = pf[i0 + (W >> (LU - l))] - pf[i0];
435 int t;
436 if (D == 0) {
437 t = l + 1; /* lone leaf: one memset + merges above */
438 } else if (D == 1) {
439 t = l; /* leaf pair: parent XOR-blend at depth l-1 */
440 } else {
441 t = (l - D) + 1; /* flat root: one unpack + merges above */
443 }
444 touches += mass * (uint64_t)t;
445 x += W;
446 }
447 S = end;
448 base += blc[l];
449 }
450 touches += (uint64_t)ZXC_HUF_NUDGE_LEVEL_COST * (uint64_t)(max_len + 1);
451 out->bits = bits;
452 out->touches = touches;
453}
454
461static ZXC_ALWAYS_INLINE uint64_t zxc_huf_nudge_j(const zxc_huf_nudge_cost_t* c) {
462 return 256U * c->bits + (uint64_t)ZXC_HUF_NUDGE_LAMBDA_Q8 * c->touches;
463}
464
484static uint32_t zxc_huf_nudge_clamp(const uint32_t want, const uint32_t s, const uint32_t n_rem,
485 const int l, const int cap) {
486 if (n_rem <= s || l >= cap) return n_rem; /* forced finish */
487 const uint32_t m = 1U << (cap - l);
488 const uint32_t lo = (2 * s > n_rem) ? 2 * s - n_rem : 0;
489 uint32_t hi = s - 1;
490 const uint32_t cap_hi = (s * m - n_rem) / (m - 1);
491 if (cap_hi < hi) hi = cap_hi;
492 const uint32_t c = want < lo ? lo : want;
493 return c > hi ? hi : c;
494}
495
507static void zxc_huf_nudge_complete(uint32_t* RESTRICT blc, const int l, uint32_t s, uint32_t n_rem,
508 const uint32_t* RESTRICT blc0, const int cap) {
509 for (int j = l + 1; j <= cap && n_rem; j++) {
510 const uint32_t c = zxc_huf_nudge_clamp(blc0[j], s, n_rem, j, cap);
511 blc[j] = c;
512 n_rem -= c;
513 s = 2 * (s - c);
514 }
515}
516
537static void zxc_huf_nudge_walk(const uint32_t* RESTRICT blc0, const uint64_t* RESTRICT pf_rank,
538 const int n, const int cap, uint32_t* RESTRICT out_blc) {
539 enum { LU = ZXC_HUF_MAX_CODE_LEN_ULTRA };
540 ZXC_MEMSET(out_blc, 0, (LU + 1) * sizeof(uint32_t));
541 uint32_t s = 2; /* the root's two slots at level 1 (n >= 4 => root is internal) */
542 uint32_t n_rem = (uint32_t)n;
543 for (int l = 1; l <= cap && n_rem; l++) {
544 struct {
545 uint32_t c;
546 int flat_d; /* > 0: complete as one uniform run at depth l + flat_d */
547 } cand[6];
548 int n_cand = 0;
549 const uint32_t c_base = zxc_huf_nudge_clamp(blc0[l], s, n_rem, l, cap);
550 cand[n_cand].c = c_base;
551 cand[n_cand++].flat_d = 0;
552 if (c_base < n_rem) {
553 // Shape the internal-node count i = s - c toward few set bits.
554 const uint32_t i_base = s - c_base;
555 const uint32_t i_dn = 1U << zxc_log2_u32(i_base);
556 const uint32_t rest = i_base - i_dn;
557 const uint32_t shapes[3] = {i_dn, i_dn << 1,
558 i_dn | (rest ? 1U << zxc_log2_u32(rest) : 0U)};
559 for (int k = 0; k < 3; k++) {
560 const uint32_t want = s > shapes[k] ? s - shapes[k] : 0;
561 const uint32_t c = zxc_huf_nudge_clamp(want, s, n_rem, l, cap);
562 int dup = 0;
563 for (int p = 0; p < n_cand; p++) dup |= (cand[p].c == c);
564 if (!dup) {
565 cand[n_cand].c = c;
566 cand[n_cand++].flat_d = 0;
567 }
568 }
569 // Uniform finish: c leaves here, the rest as i complete depth-D
570 // subtrees (c*(2^D - 1) == s*2^D - n_rem must divide exactly).
571 for (int d = 1; d <= cap - l && n_cand < 6; d++) {
572 const uint32_t den = (1U << d) - 1;
573 const int32_t num = (int32_t)(s << d) - (int32_t)n_rem;
574 if (num < 0 || (uint32_t)num % den) continue;
575 const uint32_t c = (uint32_t)num / den;
576 if (c >= s || c >= n_rem) continue; /* need i >= 1 and a remainder */
577 cand[n_cand].c = c;
578 cand[n_cand++].flat_d = d;
579 break; /* the shallowest exact finish is the aggressive one */
580 }
581 }
582 uint64_t best_j = UINT64_MAX;
583 uint32_t best_c = c_base;
584 for (int k = 0; k < n_cand; k++) {
585 uint32_t tmp[LU + 1];
586 ZXC_MEMCPY(tmp, out_blc, sizeof(tmp));
587 tmp[l] = cand[k].c;
588 const uint32_t rem = n_rem - cand[k].c;
589 if (rem) {
590 if (cand[k].flat_d)
591 tmp[l + cand[k].flat_d] = rem;
592 else
593 zxc_huf_nudge_complete(tmp, l, 2 * (s - cand[k].c), rem, blc0, cap);
594 }
595 zxc_huf_nudge_cost_t cc;
596 zxc_huf_nudge_eval(tmp, pf_rank, &cc);
597 const uint64_t j = zxc_huf_nudge_j(&cc);
598 if (j < best_j) {
599 best_j = j;
600 best_c = cand[k].c;
601 }
602 }
603 out_blc[l] = best_c;
604 n_rem -= best_c;
605 s = 2 * (s - best_c);
606 }
607}
608
630static uint64_t zxc_huf_nudge_dp_run_j(const int lu, const int lc, const int g_log2,
631 const uint32_t s, const uint32_t c,
632 const uint64_t* RESTRICT pfg, const uint32_t k) {
633 if (!c) return 0;
634 const int lr = lc + g_log2; /* real code length of these leaves */
635 const uint32_t w = 1U << (lu - lc);
636 const uint32_t S = (1U << lu) - s * w;
637 const uint32_t end = S + c * w;
638 const uint64_t bits = (uint64_t)lr * (pfg[k + c] - pfg[k]);
639 uint64_t touches = 0;
640 uint32_t x = S;
641 while (x < end) {
642 const uint32_t wx = x ? (x & (0U - x)) : (1U << lu);
643 const uint32_t wr = 1U << zxc_log2_u32(end - x);
644 const uint32_t W = wx < wr ? wx : wr;
645 const int d = (int)zxc_log2_u32(W >> (lu - lc)) + g_log2;
646 const uint32_t i0 = k + ((x - S) >> (lu - lc));
647 const uint64_t mass = pfg[i0 + (W >> (lu - lc))] - pfg[i0];
648 int t;
649 if (d == 0) {
650 t = lr + 1;
651 } else if (d == 1) {
652 t = lr;
653 } else {
654 t = (lr - d) + 1;
656 }
657 touches += mass * (uint64_t)t;
658 x += W;
659 }
660 return 256U * bits + (uint64_t)ZXC_HUF_NUDGE_LAMBDA_Q8 * touches;
661}
662
686static int zxc_huf_nudge_dp_solve(zxc_huf_nudge_ws_t* ws, const uint64_t* RESTRICT pfg, const int m,
687 const int cap_c, const int lu, const int g_log2,
688 uint32_t* RESTRICT out_cblc) {
689 if (UNLIKELY(m < 2 || m > ZXC_HUF_NUDGE_DP_M || cap_c < 1 ||
691 return 0;
692
693 const size_t plane = (size_t)(m + 1) * (size_t)(m + 1);
694 const size_t arrive_cnt = (size_t)(cap_c + 1) * plane;
695 uint64_t* jcur = ws->jcur;
696 uint64_t* jnxt = ws->jnxt;
697 uint8_t* const arrive = ws->arrive;
698 int ok = 0;
699
700#define ZXC_NUDGE_DP_IDX(k, s) ((size_t)(k) * (size_t)(m + 1) + (size_t)(s))
701 for (size_t i = 0; i < plane; i++) jcur[i] = UINT64_MAX;
702 jcur[ZXC_NUDGE_DP_IDX(0, 2)] = 0;
703 uint64_t best_j = UINT64_MAX;
704 int best_l = 0;
705 int best_k = 0;
706 int best_s = 0;
707 for (int lc = 1; lc <= cap_c; lc++) {
708 for (size_t i = 0; i < plane; i++) jnxt[i] = UINT64_MAX;
709 for (int k = 0; k < m; k++) {
710 const uint32_t n_rem = (uint32_t)(m - k);
711 for (uint32_t s = 1; s <= n_rem; s++) {
712 const size_t from = ZXC_NUDGE_DP_IDX(k, s);
713 if (UNLIKELY(from >= plane)) continue;
714 const uint64_t j0 = jcur[from];
715 if (j0 == UINT64_MAX) continue;
716 if (s == n_rem) {
717 // Forced finish: fill every slot, close the tree here.
718 const uint64_t j =
719 j0 + zxc_huf_nudge_dp_run_j(lu, lc, g_log2, s, s, pfg, (uint32_t)k) +
721 (uint64_t)(lc + g_log2 + 1);
722 if (j < best_j) {
723 best_j = j;
724 best_l = lc;
725 best_k = k;
726 best_s = (int)s;
727 }
728 continue;
729 }
730 if (lc == cap_c) continue; /* must finish at the cap */
731 const uint32_t mm = 1U << (cap_c - lc);
732 const uint32_t lo = (2 * s > n_rem) ? 2 * s - n_rem : 0;
733 uint32_t hi = s - 1;
734 const uint32_t cap_hi = (s * mm - n_rem) / (mm - 1);
735 if (cap_hi < hi) hi = cap_hi;
736 for (uint32_t c = lo; c <= hi; c++) {
737 const uint64_t j =
738 j0 + zxc_huf_nudge_dp_run_j(lu, lc, g_log2, s, c, pfg, (uint32_t)k);
739 const size_t to = ZXC_NUDGE_DP_IDX(k + (int)c, 2 * (s - c));
740 const size_t arr = (size_t)(lc + 1) * plane + to;
741
742 if (UNLIKELY(to >= plane || arr >= arrive_cnt)) continue;
743 if (j < jnxt[to]) {
744 jnxt[to] = j;
745 arrive[arr] = (uint8_t)c;
746 }
747 }
748 }
749 }
750 uint64_t* tmp = jcur;
751 jcur = jnxt;
752 jnxt = tmp;
753 }
754 if (best_j == UINT64_MAX) goto done;
755 ZXC_MEMSET(out_cblc, 0, (ZXC_HUF_MAX_CODE_LEN_ULTRA + 1) * sizeof(uint32_t));
756 out_cblc[best_l] = (uint32_t)best_s;
757 {
758 int k = best_k;
759 int s = best_s;
760 for (int lc = best_l; lc > 1; lc--) {
761 const uint32_t c = arrive[(size_t)lc * plane + ZXC_NUDGE_DP_IDX(k, s)];
762 out_cblc[lc - 1] = c;
763 s = s / 2 + (int)c;
764 k -= (int)c;
765 }
766 if (UNLIKELY(k != 0 || s != 2)) goto done; /* backtrack corruption: drop candidate */
767 }
768 ok = 1;
769done:
770#undef ZXC_NUDGE_DP_IDX
771 return ok;
772}
773
782static void zxc_huf_nudge_assign(const uint32_t* RESTRICT blc, const int16_t* RESTRICT sym_order,
783 uint8_t* RESTRICT cand_len) {
784 ZXC_MEMSET(cand_len, 0, ZXC_HUF_NUM_SYMBOLS);
785 int r = 0;
786 for (int l = 1; l <= ZXC_HUF_MAX_CODE_LEN_ULTRA; l++)
787 for (uint32_t k = 0; k < blc[l]; k++) cand_len[sym_order[r++]] = (uint8_t)l;
788}
789
790void zxc_huf_nudge_cost(const uint8_t* RESTRICT code_len, const uint32_t* RESTRICT freq,
791 uint64_t* RESTRICT bits, uint64_t* RESTRICT touches) {
792 uint32_t blc[ZXC_HUF_MAX_CODE_LEN_ULTRA + 1];
793 (void)zxc_huf_nudge_classes(code_len, blc);
794 uint64_t pf[ZXC_HUF_NUM_SYMBOLS + 1];
795 zxc_huf_nudge_pf_canonical(code_len, freq, blc, pf);
796 zxc_huf_nudge_cost_t c;
797 zxc_huf_nudge_eval(blc, pf, &c);
798 *bits = c.bits;
799 *touches = c.touches;
800}
801
802int zxc_huf_nudge_code_lengths(const uint32_t* RESTRICT freq, uint8_t* RESTRICT code_len,
803 void* RESTRICT scratch, const size_t scratch_cap,
804 const int max_code_len) {
805 enum { LU = ZXC_HUF_MAX_CODE_LEN_ULTRA };
806 uint32_t blc0[LU + 1];
807 const int n = zxc_huf_nudge_classes(code_len, blc0);
808 // Degenerate alphabets have no shape freedom (and n == 1 is format-pinned
809 // to code length exactly 1): leave them untouched.
810 if (n < 4) return 0;
811
812 // Tables and DP planes live past the rebuilds' region of the scratch when it
813 // has the room (opt_scratch does), else in one allocation: no 10 KiB frame.
814 const int owned = !scratch || scratch_cap < ZXC_HUF_NUDGE_SCRATCH_SIZE;
815 zxc_huf_nudge_ws_t* const ws =
816 owned ? (zxc_huf_nudge_ws_t*)ZXC_MALLOC(sizeof(*ws))
817 : (zxc_huf_nudge_ws_t*)((uint8_t*)scratch + ZXC_HUF_NUDGE_SCRATCH_OFF);
818 if (UNLIKELY(!ws)) return 0;
819
820 // Baseline cost, exact (canonical-order frequency weighting).
821 uint64_t* const pf = ws->pf;
822 zxc_huf_nudge_pf_canonical(code_len, freq, blc0, pf);
823 zxc_huf_nudge_cost_t c0;
824 zxc_huf_nudge_eval(blc0, pf, &c0);
825
826 // Frequency-rank order shared by every candidate (rank 0 = most frequent;
827 // pm_leaves_sort is ascending, ties on symbol, so read it backwards).
828 pm_leaf_t* const leaves = ws->leaves;
829 int k = 0;
830 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++) {
831 if (!freq[s]) continue;
832 leaves[k].w = freq[s];
833 leaves[k].sym = (int16_t)s;
834 k++;
835 }
836 pm_leaves_sort(leaves, n);
837 int16_t* const sym_order = ws->sym_order;
838 uint64_t* const pf_rank = ws->pf_rank;
839 pf_rank[0] = 0;
840 for (int r = 0; r < n; r++) {
841 sym_order[r] = leaves[n - 1 - r].sym;
842 pf_rank[r + 1] = pf_rank[r] + leaves[n - 1 - r].w;
843 }
844
845 // Candidates: the greedy ledger walk, package-merge rebuilt at reduced caps
846 // (the pass loop runs max_depth + 1 times, so depth cuts attack the decoder's
847 // biggest fixed cost), and the slot-ledger DP below. All Kraft-exact.
848 uint8_t (*const cand)[ZXC_HUF_NUM_SYMBOLS] = ws->cand;
849 int n_cand = 0;
850 {
851 uint32_t blc_w[LU + 1];
852 zxc_huf_nudge_walk(blc0, pf_rank, n, max_code_len, blc_w);
853 zxc_huf_nudge_assign(blc_w, sym_order, cand[n_cand]);
854 n_cand++;
855 }
856 int max_len0 = 0;
857 for (int l = LU; l >= 1; l--) {
858 if (blc0[l]) {
859 max_len0 = l;
860 break;
861 }
862 }
863 if (max_len0 >= 2) {
864 for (int cut = 1; cut <= 2; cut++) {
865 const int cap2 = max_len0 - cut;
866 if (cap2 < 2 || ((uint32_t)1 << cap2) < (uint32_t)n) break;
867 if (zxc_huf_build_code_lengths(freq, cand[n_cand], scratch, cap2) != ZXC_OK) break;
868 n_cand++;
869 }
870 }
871
872 // Slot-ledger DP: optimal class counts under the rank-weighted model, over
873 // groups of 2^G frequency-adjacent symbols (G = 0 is exact; coarser tiers
874 // keep the plane cache-resident, bounding the call to a few hundred us).
875 // When G does not divide n the lightest group is padded with zero-freq
876 // ghost leaves on unused byte values - wire-legal, empty runs, and the
877 // evaluator prices the burnt code space like anything else.
878 {
879 int g_log2 = 0; /* coarsen until the groups fit the DP plane */
880 while (((n + (1 << g_log2) - 1) >> g_log2) > ZXC_HUF_NUDGE_DP_M) g_log2++;
881 const int g = 1 << g_log2;
882 const int m = (n + g - 1) / g;
883 const int cap_c = max_code_len - g_log2;
884 if (m >= 2 && cap_c >= 1 && m <= (1 << cap_c)) {
885 uint64_t* const pfg = ws->pfg;
886 for (int j2 = 0; j2 <= m; j2++) {
887 int r = j2 * g;
888 if (r > n) r = n;
889 pfg[j2] = pf_rank[r];
890 }
891 uint32_t cblc[LU + 1];
892 if (zxc_huf_nudge_dp_solve(ws, pfg, m, cap_c, LU - g_log2, g_log2, cblc)) {
893 uint8_t* const cl = cand[n_cand];
894 ZXC_MEMSET(cl, 0, ZXC_HUF_NUM_SYMBOLS);
895 int r = 0;
896 int ghosts = 0;
897 uint8_t ghost_len = 0;
898 for (int lc = 1; lc <= cap_c; lc++) {
899 for (uint32_t q = 0; q < cblc[lc]; q++) {
900 for (int e = 0; e < g; e++, r++) {
901 if (r < n) {
902 cl[sym_order[r]] = (uint8_t)(lc + g_log2);
903 } else {
904 ghost_len = (uint8_t)(lc + g_log2);
905 ghosts++;
906 }
907 }
908 }
909 }
910 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS && ghosts; s++) {
911 if (freq[s] == 0 && cl[s] == 0) {
912 cl[s] = ghost_len;
913 ghosts--;
914 }
915 }
916 n_cand++;
917 }
918 }
919 }
920
921 // Adopt the cheapest candidate clearing both guard rails and strictly
922 // beating the baseline J; otherwise leave code_len byte-for-byte alone, so a
923 // rejection never depends on package-merge tie assignment.
924 const uint64_t j0 = zxc_huf_nudge_j(&c0);
925 uint64_t best_j = j0;
926 int best = -1;
927 for (int ci = 0; ci < n_cand; ci++) {
928 // Every live symbol must keep a code; ghost-padded candidates carry
929 // MORE nonzero lengths than n, which is fine.
930 int valid = 1;
931 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++) {
932 if (freq[s] != 0 && cand[ci][s] == 0) {
933 valid = 0;
934 break;
935 }
936 }
937 if (!valid) continue;
938 uint32_t blc[LU + 1];
939 (void)zxc_huf_nudge_classes(cand[ci], blc);
940 zxc_huf_nudge_pf_canonical(cand[ci], freq, blc, pf);
941 zxc_huf_nudge_cost_t c1;
942 zxc_huf_nudge_eval(blc, pf, &c1);
943 if (c1.bits * 1000 > c0.bits * ZXC_HUF_NUDGE_BITS_PERMIL) continue;
944 if (c1.touches * 256 > c0.touches * ZXC_HUF_NUDGE_MERGE_Q8) continue;
945 const uint64_t j = zxc_huf_nudge_j(&c1);
946 if (j < best_j) {
947 best_j = j;
948 best = ci;
949 }
950 }
951 if (best >= 0) ZXC_MEMCPY(code_len, cand[best], ZXC_HUF_NUM_SYMBOLS);
952 if (owned) ZXC_FREE(ws);
953 return best >= 0;
954}
955#endif /* ZXC_VARIANT_PRIMARY */
956#endif /* !ZXC_HUF_NO_ENCODER */
957
958// ===========================================================================
959// 128-byte length header: 256 x 4-bit lengths, low nibble first.
960// =========================================================================
961
962#ifndef ZXC_HUF_NO_ENCODER
963void zxc_huf_pack_lengths(const uint8_t* RESTRICT code_len, uint8_t* RESTRICT out) {
964 for (int i = 0; i < ZXC_HUF_NUM_SYMBOLS; i += 2) {
965 const uint8_t lo = code_len[i] & 0x0F;
966 const uint8_t hi = code_len[i + 1] & 0x0F;
967 out[i >> 1] = (uint8_t)(lo | (hi << 4));
968 }
969}
970
971#endif /* !ZXC_HUF_NO_ENCODER */
972
973int zxc_huf_unpack_lengths(const uint8_t* RESTRICT in, uint8_t* RESTRICT code_len) {
974 int max_len = 0;
975 int n_present = 0;
976 for (int i = 0; i < ZXC_HUF_NUM_SYMBOLS; i += 2) {
977 const uint8_t b = in[i >> 1];
978 const uint8_t lo = b & 0x0F;
979 const uint8_t hi = (uint8_t)(b >> 4);
980 code_len[i] = lo;
981 code_len[i + 1] = hi;
982 if (lo > max_len) max_len = lo;
983 if (hi > max_len) max_len = hi;
984 if (lo) n_present++;
985 if (hi) n_present++;
986 }
987 if (UNLIKELY(max_len > ZXC_HUF_MAX_CODE_LEN_ULTRA || n_present == 0))
989 return ZXC_OK;
990}
991
992// ===========================================================================
993// PivCo-Huffman section codec (enc 2/3)
994// ===========================================================================
995//
996// Level-ordered layout and the merge-based decode are from PivCo-Huffman
997// by Marcin Zukowski (https://github.com/MarcinZukowski/pivco-huffman).
998// Implemented independently here.
999//
1000// Layout: [128-byte packed code lengths (literal sections only)] then, for
1001// every EMITTING node of the canonical code tree in BFS order, that node's
1002// run: one branch bit per symbol routed through the node (0 = left child,
1003// 1 = right), in sequence order -- or, for flat subtree roots, D packed bits
1004// per symbol (bit j = branch at relative depth j). Runs are LSB-first within
1005// bytes and byte-padded; descendants of a flat root emit nothing.
1006//
1007// The decoder recovers each node's symbol count for free: the root handles
1008// n symbols, and popcounting a node's bits yields its right child's count.
1009// Reconstruction runs bottom-up, one level at a time: leaves are runs of a
1010// single symbol; an internal node MERGES its two children's sequences under
1011// the control of its bits. Merges are branch-free shuffles (16 outputs per
1012// step on AArch64 via a two-register TBL, 8 on ARMv7 via VTBL4, 64 on
1013// AVX-512-VBMI2 via vpexpandb), which is what makes this layout
1014// decode faster than the serial bit-chain of the classic 4-stream layout on
1015// any target with a 16-byte shuffle.
1016//
1017// Level buffers ping-pong between `scratch` (odd depths) and `dst` (even
1018// depths, final output at depth 0), so one n-sized scratch suffices. Both
1019// buffers need read slack past `n` (speculative 16-byte kernel loads):
1020// ZXC_PAD_SIZE on dst (already true for lit/token buffers), and
1021// ZXC_PIVCO_SCRATCH_PAD on scratch.
1022
1023#if !defined(ZXC_HUF_NO_ENCODER) || !defined(ZXC_HUF_NO_DECODER)
1024static ZXC_ALWAYS_INLINE int zxc_pivco_popcnt32(const uint32_t v) { return (int)ZXC_POPCOUNT32(v); }
1025
1026static ZXC_ALWAYS_INLINE int zxc_pivco_popcnt64(const uint64_t v) { return (int)ZXC_POPCOUNT64(v); }
1027
1029static ZXC_ALWAYS_INLINE int zxc_pivco_leaves(const zxc_pivco_tree_t* RESTRICT t, const int d) {
1030 return t->leaf_base[d + 1] - t->leaf_base[d];
1031}
1032
1034static ZXC_ALWAYS_INLINE int zxc_pivco_flat_leaves(const zxc_pivco_tree_t* RESTRICT t, const int g,
1035 const int d, const int D) {
1036 const int e = d + D;
1037 return t->leaf_base[e] + t->base[e] - t->node_base[e] + ((g - t->base[d]) << D);
1038}
1039
1041static void zxc_pivco_bitrev_permute(uint8_t* RESTRICT s, const int D) {
1042 const unsigned m = 1U << D;
1043 unsigned c = 0; /* r bit-reversed */
1044 for (unsigned r = 0; r < m; r++) {
1045 if (r < c) {
1046 const uint8_t x = s[r];
1047 s[r] = s[c];
1048 s[c] = x;
1049 }
1050 unsigned bit = m >> 1; /* reversed increment */
1051 for (; c & bit; bit >>= 1) c ^= bit;
1052 c |= bit;
1053 }
1054}
1055
1065static int zxc_pivco_tree_build(const uint8_t* RESTRICT code_len, zxc_pivco_tree_t* RESTRICT t) {
1066 uint16_t bl_count[ZXC_HUF_MAX_CODE_LEN_ULTRA + 1] = {0};
1067 int n_present = 0;
1068 int max_depth = 0;
1069 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++) {
1070 const int l = code_len[s];
1071 if (l == 0) continue;
1072 if (UNLIKELY(l > ZXC_HUF_MAX_CODE_LEN_ULTRA)) return -1;
1073 bl_count[l]++;
1074 n_present++;
1075 if (l > max_depth) max_depth = l;
1076 }
1077 if (UNLIKELY(n_present == 0)) return -1;
1078 if (n_present >= 2) {
1079 uint32_t kraft = 0;
1080 for (int l = 1; l <= ZXC_HUF_MAX_CODE_LEN_ULTRA; l++)
1081 kraft += (uint32_t)bl_count[l] << (ZXC_HUF_MAX_CODE_LEN_ULTRA - l);
1082 if (UNLIKELY(kraft != (1U << ZXC_HUF_MAX_CODE_LEN_ULTRA))) return -1;
1083 } else if (UNLIKELY(bl_count[1] != 1)) {
1084 return -1; /* the lone symbol is pinned at length 1 */
1085 }
1086 t->max_depth = max_depth;
1087
1088 // Two children per internal node above, one under the lone symbol's root.
1089 // The d-bit prefixes start at `first`.
1090 unsigned width = 1;
1091 unsigned first = 0;
1092 t->node_base[0] = 0;
1093 t->leaf_base[0] = 0;
1094 for (int d = 0; d <= max_depth; d++) {
1095 t->base[d] = (int16_t)(t->node_base[d] - (int)first);
1096 t->node_base[d + 1] = (uint16_t)(t->node_base[d] + width);
1097 t->leaf_base[d + 1] = (uint16_t)(t->leaf_base[d] + bl_count[d]);
1098 first = 2 * (first + bl_count[d]);
1099 width = (d == 0 && n_present == 1) ? 1U : 2 * (width - bl_count[d]);
1100 }
1101
1102 uint16_t pos[ZXC_HUF_MAX_CODE_LEN_ULTRA + 1];
1103 for (int d = 0; d <= max_depth; d++) pos[d] = t->leaf_base[d];
1104 for (int s = 0; s < ZXC_HUF_NUM_SYMBOLS; s++)
1105 if (code_len[s]) t->syms[pos[code_len[s]]++] = (uint8_t)s;
1106
1107 // FORMAT RULE: a flat root is a MAXIMAL complete subtree of depth D >= 2
1108 // (D = 1 is a leaf pair). Bottom-up, flat_d holds complete heights: 0 at
1109 // leaves and the slot, INCOMPLETE across depths.
1110 enum { INCOMPLETE = 0xFE };
1111 t->flat_d[t->node_base[max_depth + 1]] = 0;
1112 for (int d = max_depth; d >= 0; d--) {
1113 uint8_t* const h = t->flat_d + t->node_base[d];
1114 const uint8_t* const hc = t->flat_d + t->node_base[d + 1];
1115 const int L = zxc_pivco_leaves(t, d);
1116 const int N = t->node_base[d + 1] - t->node_base[d];
1117 for (int i = 0; i < L; i++) h[i] = 0;
1118 for (int i = L; i < N; i++) {
1119 const uint8_t a = hc[2 * (i - L)];
1120 const uint8_t b = hc[2 * (i - L) + 1];
1121 h[i] = (a == b && a != INCOMPLETE) ? (uint8_t)(a + 1) : (uint8_t)INCOMPLETE;
1122 }
1123 }
1124 // Top-down: the first height >= 2 on a path is a flat root, the internal
1125 // nodes below are covered. The wire packs a path LSB first, so leaf r has
1126 // packed code r bit-reversed: store the leaves in that order.
1127 for (int d = 0; d < max_depth; d++) {
1128 uint8_t* const fd = t->flat_d + t->node_base[d];
1129 const uint8_t* const up =
1130 d ? t->flat_d + t->node_base[d - 1] + zxc_pivco_leaves(t, d - 1) : NULL;
1131 const int N = t->node_base[d + 1] - t->node_base[d];
1132 for (int i = zxc_pivco_leaves(t, d); i < N; i++) {
1133 if (up && up[i >> 1]) {
1134 fd[i] = ZXC_PIVCO_COVERED;
1135 } else if (fd[i] < 2 || fd[i] == INCOMPLETE) {
1136 fd[i] = 0;
1137 } else {
1138 const int g = t->node_base[d] + i;
1139 zxc_pivco_bitrev_permute(t->syms + zxc_pivco_flat_leaves(t, g, d, fd[i]), fd[i]);
1140 }
1141 }
1142 }
1143 return 0;
1144}
1145#endif
1146
1147#ifndef ZXC_HUF_NO_ENCODER
1154static void zxc_pivco_counts(const zxc_pivco_tree_t* RESTRICT t, const uint32_t* RESTRICT freq,
1155 uint32_t* RESTRICT count) {
1156 count[t->node_base[t->max_depth + 1]] = 0;
1157 for (int d = t->max_depth; d >= 0; d--) {
1158 const int L = zxc_pivco_leaves(t, d);
1159 const int N = t->node_base[d + 1] - t->node_base[d];
1160 uint32_t* const cnt = count + t->node_base[d];
1161 const uint32_t* const ccnt = count + t->node_base[d + 1];
1162 const uint8_t* const sym = t->syms + t->leaf_base[d];
1163 for (int i = 0; i < L; i++) cnt[i] = freq[sym[i]];
1164 for (int i = L; i < N; i++) cnt[i] = ccnt[2 * (i - L)] + ccnt[2 * (i - L) + 1];
1165 }
1166}
1167
1169static void zxc_pivco_codes(const zxc_pivco_tree_t* RESTRICT t, uint32_t* RESTRICT codes) {
1170 for (int d = 1; d <= t->max_depth; d++)
1171 for (int i = 0; i < zxc_pivco_leaves(t, d); i++)
1172 codes[t->syms[t->leaf_base[d] + i]] = (uint32_t)(t->node_base[d] + i - t->base[d]);
1173}
1174#endif /* !ZXC_HUF_NO_ENCODER */
1175
1176#if !defined(ZXC_HUF_NO_ENCODER) || !defined(ZXC_HUF_NO_DECODER)
1199static ZXC_ALWAYS_INLINE size_t zxc_pivco_run_bytes(const uint32_t count, const uint8_t flat_d) {
1200 return flat_d ? ((size_t)count * flat_d + 7) / 8 : ((size_t)count + 7) / 8;
1201}
1202#endif
1203
1204#ifndef ZXC_HUF_NO_ENCODER
1211static size_t zxc_pivco_layout(const zxc_pivco_tree_t* RESTRICT t, const uint32_t* RESTRICT count,
1212 uint32_t* RESTRICT cur) {
1213 size_t total = 0;
1214 for (int d = 0; d < t->max_depth; d++) {
1215 for (int g = t->node_base[d] + zxc_pivco_leaves(t, d); g < t->node_base[d + 1]; g++) {
1216 if (t->flat_d[g] == ZXC_PIVCO_COVERED) continue;
1217 if (cur) cur[g] = (uint32_t)(total << 3);
1218 total += zxc_pivco_run_bytes(count[g], t->flat_d[g]);
1219 }
1220 }
1221 return total;
1222}
1223
1224size_t zxc_huf_calc_size(const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1225 const int with_header) {
1227 if (UNLIKELY(zxc_pivco_tree_build(code_len, &t) != 0)) return SIZE_MAX;
1228 const size_t body = zxc_huf_calc_size_dict(freq, code_len, &t);
1229 if (UNLIKELY(body == SIZE_MAX)) return SIZE_MAX;
1230 return body + (with_header ? (size_t)ZXC_HUF_TABLE_SIZE : 0);
1231}
1232
1238size_t zxc_huf_calc_size_dict(const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1239 const zxc_pivco_tree_t* RESTRICT tree) {
1240 // Encodability is part of the estimate: a histogram symbol the table has no
1241 // code for would be silently ignored below and undercount. Report the
1242 // candidate unencodable instead.
1243 for (int k = 0; k < ZXC_HUF_NUM_SYMBOLS; k++)
1244 if (UNLIKELY(freq[k] != 0 && code_len[k] == 0)) return SIZE_MAX;
1245 uint32_t count[ZXC_PIVCO_NODE_SLOTS];
1246 zxc_pivco_counts(tree, freq, count);
1247 return zxc_pivco_layout(tree, count, NULL);
1248}
1249
1257static int zxc_pivco_encode_core(const uint8_t* RESTRICT literals, const size_t n_literals,
1258 const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1259 const zxc_pivco_tree_t* RESTRICT t, const uint32_t* RESTRICT codes,
1260 uint8_t* RESTRICT dst, const size_t dst_cap,
1261 const int with_header) {
1262 if (UNLIKELY(n_literals == 0)) return ZXC_ERROR_CORRUPT_DATA;
1263 // Every literal present in the histogram must have a code (a dict table
1264 // may lack codes for symbols unseen in training: the caller then falls
1265 // back to a per-block table, but a direct call must fail loudly).
1266 for (int k = 0; k < ZXC_HUF_NUM_SYMBOLS; k++)
1267 if (UNLIKELY(freq[k] != 0 && code_len[k] == 0)) return ZXC_ERROR_CORRUPT_DATA;
1268
1269 uint32_t count[ZXC_PIVCO_NODE_SLOTS];
1270 zxc_pivco_counts(t, freq, count);
1271 uint32_t cur[ZXC_PIVCO_MAX_NODES]; /* per-node write cursor, in payload bits */
1272 const size_t payload = zxc_pivco_layout(t, count, cur);
1273 const size_t hdr = with_header ? (size_t)ZXC_HUF_TABLE_SIZE : 0;
1274 // +2: the packed-code emitter uses a 3-byte read-modify-write that may
1275 // touch up to 2 bytes past the payload end.
1276 if (UNLIKELY(hdr + payload + 2 > dst_cap)) return ZXC_ERROR_DST_TOO_SMALL;
1277
1278 if (with_header) zxc_huf_pack_lengths(code_len, dst);
1279 uint8_t* const out = dst + hdr;
1280 ZXC_MEMSET(out, 0, payload + 2);
1281
1282 // Emit MSB-first while descending. At a flat root, emit the code's last D
1283 // bits, its packed code, in one shot and stop. Batching the per-bit
1284 // read-modify-write buys nothing: accumulators would still touch memory
1285 // once per bit, and flat roots absorb the dense levels.
1286 for (size_t i = 0; i < n_literals; i++) {
1287 const uint8_t s = literals[i];
1288 const uint32_t c = codes[s];
1289 const int l = code_len[s];
1290 for (int d = 0; d < l; d++) {
1291 const int g = t->base[d] + (int)(c >> (l - d));
1292 const int fd = t->flat_d[g];
1293 if (fd) {
1294 const uint32_t p = cur[g];
1295 cur[g] += (uint32_t)fd;
1296 uint8_t* q = out + (p >> 3);
1297 const uint32_t sh = p & 7U;
1298 uint32_t w = (uint32_t)q[0] | ((uint32_t)q[1] << 8) | ((uint32_t)q[2] << 16);
1299 w |= (c & ((1U << fd) - 1U)) << sh; /* fd <= 8, sh <= 7: fits 24 bits */
1300 q[0] = (uint8_t)w;
1301 q[1] = (uint8_t)(w >> 8);
1302 q[2] = (uint8_t)(w >> 16);
1303 break;
1304 }
1305 const uint32_t bit = (c >> (l - 1 - d)) & 1U;
1306 const uint32_t p = cur[g]++;
1307 out[p >> 3] |= (uint8_t)(bit << (p & 7));
1308 }
1309 }
1310 return (int)(hdr + payload);
1311}
1312
1330int zxc_huf_encode_section(const uint8_t* RESTRICT literals, const size_t n_literals,
1331 const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1332 uint8_t* RESTRICT dst, const size_t dst_cap) {
1334 uint32_t codes[ZXC_HUF_NUM_SYMBOLS];
1335 if (UNLIKELY(zxc_pivco_tree_build(code_len, &t) != 0)) return ZXC_ERROR_CORRUPT_DATA;
1336 zxc_pivco_codes(&t, codes);
1337 return zxc_pivco_encode_core(literals, n_literals, freq, code_len, &t, codes, dst, dst_cap, 1);
1338}
1339
1340#ifndef ZXC_HUF_NO_DICT_SECTIONS
1349int zxc_huf_encode_section_dict(const uint8_t* RESTRICT literals, const size_t n_literals,
1350 const uint32_t* RESTRICT freq, const uint8_t* RESTRICT code_len,
1351 const zxc_pivco_tree_t* RESTRICT tree,
1352 const uint32_t* RESTRICT codes, uint8_t* RESTRICT dst,
1353 const size_t dst_cap) {
1354 return zxc_pivco_encode_core(literals, n_literals, freq, code_len, tree, codes, dst, dst_cap,
1355 0);
1356}
1357#endif /* !ZXC_HUF_NO_DICT_SECTIONS */
1358#endif /* !ZXC_HUF_NO_ENCODER */
1359
1360// ISA-independent cold dict setup
1361#if defined(ZXC_VARIANT_PRIMARY)
1362
1369int zxc_huf_dict_tree_build(const uint8_t* RESTRICT packed_lengths, zxc_pivco_tree_t* RESTRICT tree,
1370 uint32_t* RESTRICT codes, uint8_t* RESTRICT code_len) {
1371 const int rc = zxc_huf_unpack_lengths(packed_lengths, code_len);
1372 if (UNLIKELY(rc != ZXC_OK)) return rc;
1373 if (UNLIKELY(zxc_pivco_tree_build(code_len, tree) != 0)) return ZXC_ERROR_CORRUPT_DATA;
1374 zxc_pivco_codes(tree, codes);
1375 return ZXC_OK;
1376}
1377#endif /* ZXC_VARIANT_PRIMARY */
1378
1379#ifndef ZXC_HUF_NO_DECODER
1387#define ZXC_PIVCO_MERGE_STEP(w, pc) \
1388 do { \
1389 rp += (size_t)(pc); \
1390 lp += (size_t)((w) - (pc)); \
1391 i += (w); \
1392 } while (0)
1393
1403static ZXC_ALWAYS_INLINE void zxc_pivco_merge(uint8_t* RESTRICT out, const uint8_t* RESTRICT src,
1404 const size_t nl, const size_t nr,
1405 const uint8_t* RESTRICT bits) {
1406 const uint8_t* L = src;
1407 const uint8_t* R = src + nl;
1408 const size_t n = nl + nr;
1409 size_t i = 0;
1410 size_t lp = 0;
1411 size_t rp = 0;
1412#if defined(ZXC_USE_NEON64)
1413 // 16 outputs per step: two-register TBL over {L[0..15], R[0..15]} with the
1414 // signed-index tables (see zxc_pivco_tables.h).
1415 while (i + 16 <= n) {
1416 const uint8_t b0 = bits[i >> 3];
1417 const uint8_t b1 = bits[(i >> 3) + 1];
1418 uint8x16x2_t tb;
1419 tb.val[0] = vld1q_u8(L + lp);
1420 tb.val[1] = vld1q_u8(R + rp);
1421 const int pc0 = zxc_pivco_popcnt32(b0);
1422 const uint8x8_t ia = vld1_u8(zxc_pivco_idxa_u8[b0]);
1423 const uint8x8_t ib = vld1_u8(zxc_pivco_idxb_pre[pc0][b1]);
1424 vst1q_u8(out + i, vqtbl2q_u8(tb, vcombine_u8(ia, ib)));
1425 const int pc = pc0 + zxc_pivco_popcnt32(b1);
1426 ZXC_PIVCO_MERGE_STEP(16, pc);
1427 }
1428#else /* x86 tiers */
1429#if defined(ZXC_USE_AVX512) && defined(__AVX512VBMI2__)
1430 // 64 outputs per step: the merge IS a pair of byte expands - L's bytes fill
1431 // the control word's 0-bit lanes, R's the 1-bit lanes. The masked expand
1432 // loads only touch the bytes they consume, so the speculative reads stay
1433 // fault-safe without extra buffer slack.
1434 const __m512i zero = _mm512_setzero_si512();
1435 while (i + 64 <= n) {
1436 uint64_t ctrl;
1437 ZXC_MEMCPY(&ctrl, bits + (i >> 3), 8);
1438 const __m512i vl =
1439 _mm512_mask_expandloadu_epi8(zero, (__mmask64)~ctrl, (const void*)(L + lp));
1440 const __m512i outv =
1441 _mm512_mask_expandloadu_epi8(vl, (__mmask64)ctrl, (const void*)(R + rp));
1442 _mm512_storeu_si512((void*)(out + i), outv);
1443 const int pc = zxc_pivco_popcnt64(ctrl);
1444 ZXC_PIVCO_MERGE_STEP(64, pc);
1445 }
1446#endif
1447#if defined(ZXC_USE_AVX512) || defined(ZXC_USE_AVX2) || \
1448 (defined(ZXC_USE_SSE2) && defined(__SSSE3__))
1449 // 16 outputs/step: pshufb(L, ix+0x70) | pshufb(R, ix-16) selects L[ix] or
1450 // R[ix-16] (out-of-range lanes zero out); 32/step unrolls it twice.
1451#if defined(ZXC_USE_AVX2)
1452 // Same thing at 256 bits, 32 outputs/step. Both selects take the index
1453 // unbiased: table lanes all sit in [0, 31], so pshufb masks to 4 bits and
1454 // bit 4 is the L/R selector - shifted into the sign it drives the blend,
1455 // and both bias vectors go away. L and R stay two 128-bit loads: the
1456 // second cursor is lp + (16 - pcA), never lp + 16.
1457 while (i + 32 <= n) {
1458 const uint8_t* cb = bits + (i >> 3);
1459 const int pcA0 = zxc_pivco_popcnt32(cb[0]);
1460 const int pcA = pcA0 + zxc_pivco_popcnt32(cb[1]);
1461 const int pcB0 = zxc_pivco_popcnt32(cb[2]);
1462 const int pcB = pcB0 + zxc_pivco_popcnt32(cb[3]);
1463 const size_t lpB = lp + (size_t)(16 - pcA);
1464 const size_t rpB = rp + (size_t)pcA;
1465 const __m256i vl = _mm256_inserti128_si256(
1466 _mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(const void*)(L + lp))),
1467 _mm_loadu_si128((const __m128i*)(const void*)(L + lpB)), 1);
1468 const __m256i vr = _mm256_inserti128_si256(
1469 _mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(const void*)(R + rp))),
1470 _mm_loadu_si128((const __m128i*)(const void*)(R + rpB)), 1);
1471 const __m128i ixA = _mm_unpacklo_epi64(
1472 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxa_u8[cb[0]]),
1473 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxb_pre[pcA0][cb[1]]));
1474 const __m128i ixB = _mm_unpacklo_epi64(
1475 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxa_u8[cb[2]]),
1476 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxb_pre[pcB0][cb[3]]));
1477 const __m256i ix = _mm256_inserti128_si256(_mm256_castsi128_si256(ixA), ixB, 1);
1478 _mm256_storeu_si256(
1479 (__m256i*)(void*)(out + i),
1480 _mm256_blendv_epi8(_mm256_shuffle_epi8(vl, ix), _mm256_shuffle_epi8(vr, ix),
1481 _mm256_slli_epi16(ix, 3)));
1482 lp = lpB + (size_t)(16 - pcB);
1483 rp = rpB + (size_t)pcB;
1484 i += 32;
1485 }
1486#else
1487 while (i + 32 <= n) {
1488 const uint8_t* cb = bits + (i >> 3);
1489 const int pcA0 = zxc_pivco_popcnt32(cb[0]);
1490 const int pcA = pcA0 + zxc_pivco_popcnt32(cb[1]);
1491 const int pcB0 = zxc_pivco_popcnt32(cb[2]);
1492 const int pcB = pcB0 + zxc_pivco_popcnt32(cb[3]);
1493 const size_t lpB = lp + (size_t)(16 - pcA);
1494 const size_t rpB = rp + (size_t)pcA;
1495 const __m128i vlA = _mm_loadu_si128((const __m128i*)(const void*)(L + lp));
1496 const __m128i vrA = _mm_loadu_si128((const __m128i*)(const void*)(R + rp));
1497 const __m128i vlB = _mm_loadu_si128((const __m128i*)(const void*)(L + lpB));
1498 const __m128i vrB = _mm_loadu_si128((const __m128i*)(const void*)(R + rpB));
1499 const __m128i iaA = _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxa_u8[cb[0]]);
1500 const __m128i ibA =
1501 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxb_pre[pcA0][cb[1]]);
1502 const __m128i iaB = _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxa_u8[cb[2]]);
1503 const __m128i ibB =
1504 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxb_pre[pcB0][cb[3]]);
1505 const __m128i ixA = _mm_unpacklo_epi64(iaA, ibA);
1506 const __m128i ixB = _mm_unpacklo_epi64(iaB, ibB);
1507 const __m128i selA =
1508 _mm_or_si128(_mm_shuffle_epi8(vlA, _mm_add_epi8(ixA, _mm_set1_epi8(0x70))),
1509 _mm_shuffle_epi8(vrA, _mm_sub_epi8(ixA, _mm_set1_epi8(16))));
1510 const __m128i selB =
1511 _mm_or_si128(_mm_shuffle_epi8(vlB, _mm_add_epi8(ixB, _mm_set1_epi8(0x70))),
1512 _mm_shuffle_epi8(vrB, _mm_sub_epi8(ixB, _mm_set1_epi8(16))));
1513 _mm_storeu_si128((__m128i*)(void*)(out + i), selA);
1514 _mm_storeu_si128((__m128i*)(void*)(out + i + 16), selB);
1515 lp = lpB + (size_t)(16 - pcB);
1516 rp = rpB + (size_t)pcB;
1517 i += 32;
1518 }
1519#endif
1520 while (i + 16 <= n) {
1521 const uint8_t b0 = bits[i >> 3];
1522 const uint8_t b1 = bits[(i >> 3) + 1];
1523 const __m128i vl = _mm_loadu_si128((const __m128i*)(const void*)(L + lp));
1524 const __m128i vr = _mm_loadu_si128((const __m128i*)(const void*)(R + rp));
1525 const int pc0 = zxc_pivco_popcnt32(b0);
1526 const __m128i ia = _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxa_u8[b0]);
1527 const __m128i ib =
1528 _mm_loadl_epi64((const __m128i*)(const void*)zxc_pivco_idxb_pre[pc0][b1]);
1529 const __m128i ix = _mm_unpacklo_epi64(ia, ib);
1530 const __m128i sell = _mm_shuffle_epi8(vl, _mm_add_epi8(ix, _mm_set1_epi8(0x70)));
1531 const __m128i selr = _mm_shuffle_epi8(vr, _mm_sub_epi8(ix, _mm_set1_epi8(16)));
1532 _mm_storeu_si128((__m128i*)(void*)(out + i), _mm_or_si128(sell, selr));
1533 const int pc = pc0 + zxc_pivco_popcnt32(b1);
1534 ZXC_PIVCO_MERGE_STEP(16, pc);
1535 }
1536#elif defined(ZXC_USE_NEON32)
1537 // 8 outputs per step: four-register VTBL over {L[0..7], -, R[0..7], -}. The
1538 // shared index tables address a 32-lane view, and an 8-output step only
1539 // touches lanes 0..7 and 16..23, so the two spare d-registers stay zero.
1540 while (i + 8 <= n) {
1541 const uint8_t b = bits[i >> 3];
1542 uint8x8x4_t tb;
1543 tb.val[0] = vld1_u8(L + lp);
1544 tb.val[1] = vdup_n_u8(0);
1545 tb.val[2] = vld1_u8(R + rp);
1546 tb.val[3] = vdup_n_u8(0);
1547 vst1_u8(out + i, vtbl4_u8(tb, vld1_u8(zxc_pivco_idxa_u8[b])));
1548 const int pc = zxc_pivco_popcnt32(b);
1549 ZXC_PIVCO_MERGE_STEP(8, pc);
1550 }
1551#endif
1552#endif /* x86 tiers */
1553 // Portable 8-output path: byte selects from a 24-byte scratch laid out
1554 // as the low half of the 32-lane view the shared index tables assume
1555 // (L at offset 0, R at offset 16).
1556 while (i + 8 <= n) {
1557 const uint8_t b = bits[i >> 3];
1558 uint8_t comb[24];
1559 ZXC_MEMCPY(comb, L + lp, 8);
1560 ZXC_MEMCPY(comb + 16, R + rp, 8);
1561 const uint8_t* ix = zxc_pivco_idxa_u8[b];
1562 for (int j = 0; j < 8; j++) out[i + (size_t)j] = comb[ix[j]];
1563 const int pc = zxc_pivco_popcnt32(b);
1564 ZXC_PIVCO_MERGE_STEP(8, pc);
1565 }
1566 while (i < n) {
1567 const int bit = (bits[i >> 3] >> (i & 7)) & 1;
1568 out[i++] = bit ? R[rp++] : L[lp++];
1569 }
1570}
1571
1572#undef ZXC_PIVCO_MERGE_STEP
1573
1582static void zxc_pivco_unpack_flat(uint8_t* RESTRICT out, const size_t n, const int D,
1583 const uint8_t* RESTRICT bits, const uint8_t* RESTRICT c2s) {
1584 size_t i = 0;
1585#if defined(ZXC_USE_NEON64)
1586 if (D == 2) {
1587 uint8_t c2s16[16];
1588 for (int k = 0; k < 16; k++) c2s16[k] = c2s[k & 3];
1589 const uint8x16_t vc2s = vld1q_u8(c2s16);
1590 static const uint8_t rep4[16] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};
1591 static const int8_t sh2[16] = {0, -2, -4, -6, 0, -2, -4, -6, 0, -2, -4, -6, 0, -2, -4, -6};
1592 const uint8x16_t vrep = vld1q_u8(rep4);
1593 const int8x16_t vsh = vld1q_s8(sh2);
1594 const uint8x16_t vmask = vdupq_n_u8(0x03);
1595 while (i + 16 <= n) {
1596 uint8x16_t raw = vdupq_n_u8(0);
1597 raw = vreinterpretq_u8_u32(
1598 vsetq_lane_u32(zxc_le32(bits + ((i * 2) >> 3)), vreinterpretq_u32_u8(raw), 0));
1599 const uint8x16_t rep = vqtbl1q_u8(raw, vrep);
1600 const uint8x16_t codes = vandq_u8(vshlq_u8(rep, vsh), vmask);
1601 vst1q_u8(out + i, vqtbl1q_u8(vc2s, codes));
1602 i += 16;
1603 }
1604 } else if (D == 3) {
1605 // Odd D straddle bytes: build a 16-bit window {byte_j,byte_j+1} per lane
1606 // (byte_j = Di>>3), right-shift by Di&7, mask D bits. 16/step, two u16x8
1607 // halves sharing the shift vector. D=3: 6 source bytes.
1608 uint8_t c2s16[16];
1609 for (int k = 0; k < 16; k++) c2s16[k] = c2s[k & 7];
1610 const uint8x16_t vc2s = vld1q_u8(c2s16); /* 8 entries, padded to 16 */
1611 static const uint8_t idxA[16] = {0, 1, 0, 1, 0, 1, 1, 2, 1, 2, 1, 2, 2, 3, 2, 3};
1612 static const uint8_t idxB[16] = {3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6};
1613 static const int16_t sh8[8] = {0, -3, -6, -1, -4, -7, -2, -5};
1614 const uint8x16_t vidxA = vld1q_u8(idxA);
1615 const uint8x16_t vidxB = vld1q_u8(idxB);
1616 const int16x8_t vsh = vld1q_s16(sh8);
1617 const uint16x8_t vmask = vdupq_n_u16(0x07);
1618 while (i + 16 <= n) {
1619 const size_t off = (i * 3) >> 3;
1620 uint32_t w0;
1621 uint16_t w1;
1622 ZXC_MEMCPY(&w0, bits + off, 4);
1623 ZXC_MEMCPY(&w1, bits + off + 4, 2); /* exactly 6 bytes read */
1624 uint8x16_t raw = vdupq_n_u8(0);
1625 raw = vreinterpretq_u8_u32(vsetq_lane_u32(w0, vreinterpretq_u32_u8(raw), 0));
1626 raw = vreinterpretq_u8_u16(vsetq_lane_u16(w1, vreinterpretq_u16_u8(raw), 2));
1627 const uint16x8_t winA = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxA));
1628 const uint16x8_t winB = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxB));
1629 const uint8x8_t cA = vmovn_u16(vandq_u16(vshlq_u16(winA, vsh), vmask));
1630 const uint8x8_t cB = vmovn_u16(vandq_u16(vshlq_u16(winB, vsh), vmask));
1631 vst1q_u8(out + i, vqtbl1q_u8(vc2s, vcombine_u8(cA, cB)));
1632 i += 16;
1633 }
1634 } else if (D == 4) {
1635 const uint8x16_t vc2s = vld1q_u8(c2s); /* 16 entries */
1636 static const uint8_t rep2[16] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7};
1637 static const int8_t sh4[16] = {0, -4, 0, -4, 0, -4, 0, -4, 0, -4, 0, -4, 0, -4, 0, -4};
1638 const uint8x16_t vrep = vld1q_u8(rep2);
1639 const int8x16_t vsh = vld1q_s8(sh4);
1640 const uint8x16_t vmask = vdupq_n_u8(0x0F);
1641 while (i + 16 <= n) {
1642 uint8x16_t raw = vdupq_n_u8(0);
1643 raw = vreinterpretq_u8_u64(
1644 vsetq_lane_u64(zxc_le64(bits + ((i * 4) >> 3)), vreinterpretq_u64_u8(raw), 0));
1645 const uint8x16_t rep = vqtbl1q_u8(raw, vrep);
1646 const uint8x16_t codes = vandq_u8(vshlq_u8(rep, vsh), vmask);
1647 vst1q_u8(out + i, vqtbl1q_u8(vc2s, codes));
1648 i += 16;
1649 }
1650 } else if (D == 5) {
1651 // Same window scheme as D=3; c2s has 32 entries (vqtbl2q). 10 bytes.
1652 const uint8x16x2_t vc2s = vld1q_u8_x2(c2s);
1653 static const uint8_t idxA[16] = {0, 1, 0, 1, 1, 2, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5};
1654 static const uint8_t idxB[16] = {5, 6, 5, 6, 6, 7, 6, 7, 7, 8, 8, 9, 8, 9, 9, 10};
1655 static const int16_t sh8[8] = {0, -5, -2, -7, -4, -1, -6, -3};
1656 const uint8x16_t vidxA = vld1q_u8(idxA);
1657 const uint8x16_t vidxB = vld1q_u8(idxB);
1658 const int16x8_t vsh = vld1q_s16(sh8);
1659 const uint16x8_t vmask = vdupq_n_u16(0x1F);
1660 while (i + 16 <= n) {
1661 const size_t off = (i * 5) >> 3;
1662 uint64_t w0;
1663 uint16_t w1;
1664 ZXC_MEMCPY(&w0, bits + off, 8);
1665 ZXC_MEMCPY(&w1, bits + off + 8, 2);
1666 uint8x16_t raw = vdupq_n_u8(0);
1667 raw = vreinterpretq_u8_u64(vsetq_lane_u64(w0, vreinterpretq_u64_u8(raw), 0));
1668 raw = vreinterpretq_u8_u16(vsetq_lane_u16(w1, vreinterpretq_u16_u8(raw), 4));
1669 const uint16x8_t winA = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxA));
1670 const uint16x8_t winB = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxB));
1671 const uint8x8_t cA = vmovn_u16(vandq_u16(vshlq_u16(winA, vsh), vmask));
1672 const uint8x8_t cB = vmovn_u16(vandq_u16(vshlq_u16(winB, vsh), vmask));
1673 vst1q_u8(out + i, vqtbl2q_u8(vc2s, vcombine_u8(cA, cB)));
1674 i += 16;
1675 }
1676 } else if (D == 6) {
1677 // Same window scheme as D=3; c2s has 64 entries (vqtbl4q). 12 bytes.
1678 const uint8x16x4_t vc2s = vld1q_u8_x4(c2s);
1679 static const uint8_t idxA[16] = {0, 1, 0, 1, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5, 5, 6};
1680 static const uint8_t idxB[16] = {6, 7, 6, 7, 7, 8, 8, 9, 9, 10, 9, 10, 10, 11, 11, 12};
1681 static const int16_t sh8[8] = {0, -6, -4, -2, 0, -6, -4, -2};
1682 const uint8x16_t vidxA = vld1q_u8(idxA);
1683 const uint8x16_t vidxB = vld1q_u8(idxB);
1684 const int16x8_t vsh = vld1q_s16(sh8);
1685 const uint16x8_t vmask = vdupq_n_u16(0x3F);
1686 while (i + 16 <= n) {
1687 const size_t off = (i * 6) >> 3;
1688 uint64_t w0;
1689 uint32_t w1;
1690 ZXC_MEMCPY(&w0, bits + off, 8);
1691 ZXC_MEMCPY(&w1, bits + off + 8, 4);
1692 uint8x16_t raw = vdupq_n_u8(0);
1693 raw = vreinterpretq_u8_u64(vsetq_lane_u64(w0, vreinterpretq_u64_u8(raw), 0));
1694 raw = vreinterpretq_u8_u32(vsetq_lane_u32(w1, vreinterpretq_u32_u8(raw), 2));
1695 const uint16x8_t winA = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxA));
1696 const uint16x8_t winB = vreinterpretq_u16_u8(vqtbl1q_u8(raw, vidxB));
1697 const uint8x8_t cA = vmovn_u16(vandq_u16(vshlq_u16(winA, vsh), vmask));
1698 const uint8x8_t cB = vmovn_u16(vandq_u16(vshlq_u16(winB, vsh), vmask));
1699 vst1q_u8(out + i, vqtbl4q_u8(vc2s, vcombine_u8(cA, cB)));
1700 i += 16;
1701 }
1702 }
1703#elif defined(ZXC_USE_NEON32)
1704 // d-register mirrors of the AArch64 kernels: 8 codes per step, c2s lookup
1705 // via VTBL (16-entry table = two d-registers).
1706 if (D == 2) {
1707 uint8_t c2s8[8];
1708 for (int k = 0; k < 8; k++) c2s8[k] = c2s[k & 3];
1709 const uint8x8_t vc2s = vld1_u8(c2s8);
1710 static const uint8_t rep4[8] = {0, 0, 0, 0, 1, 1, 1, 1};
1711 static const int8_t sh2[8] = {0, -2, -4, -6, 0, -2, -4, -6};
1712 const uint8x8_t vrep = vld1_u8(rep4);
1713 const int8x8_t vsh = vld1_s8(sh2);
1714 const uint8x8_t vmask = vdup_n_u8(0x03);
1715 while (i + 8 <= n) {
1716 const uint16_t w = (uint16_t)((uint16_t)bits[(i * 2) >> 3] |
1717 ((uint16_t)bits[((i * 2) >> 3) + 1] << 8));
1718 const uint8x8_t raw = vreinterpret_u8_u16(vdup_n_u16(w));
1719 const uint8x8_t rep = vtbl1_u8(raw, vrep);
1720 const uint8x8_t codes = vand_u8(vshl_u8(rep, vsh), vmask);
1721 vst1_u8(out + i, vtbl1_u8(vc2s, codes));
1722 i += 8;
1723 }
1724 } else if (D == 3) {
1725 // 8 codes/step. 3-bit codes straddle bytes, so build a 16-bit window
1726 // {byte_j, byte_j+1} per lane via two VTBLs, then extract bits [s,s+3)
1727 // by multiply-by-2^(13-s) then >>13 - ARMv7 has no per-lane u16 variable
1728 // shift. 8 codes fit in 3 source bytes.
1729 const uint8x8_t vc2s = vld1_u8(c2s); /* 8 entries (2^3) */
1730 static const uint8_t idxlo[8] = {0, 1, 0, 1, 0, 1, 1, 2};
1731 static const uint8_t idxhi[8] = {1, 2, 1, 2, 2, 3, 2, 3};
1732 static const uint16_t mul8[8] = {8192, 1024, 128, 4096, 512, 64, 2048, 256};
1733 const uint8x8_t vidxlo = vld1_u8(idxlo);
1734 const uint8x8_t vidxhi = vld1_u8(idxhi);
1735 const uint16x8_t vmul = vld1q_u16(mul8);
1736 const uint16x8_t vmask = vdupq_n_u16(0x07);
1737 while (i + 8 <= n) {
1738 const size_t off = (i * 3) >> 3;
1739 const uint32_t w = (uint32_t)bits[off] | ((uint32_t)bits[off + 1] << 8) |
1740 ((uint32_t)bits[off + 2] << 16); /* exactly 3 bytes */
1741 const uint8x8_t raw = vreinterpret_u8_u32(vdup_n_u32(w));
1742 const uint8x8_t wlo = vtbl1_u8(raw, vidxlo);
1743 const uint8x8_t whi = vtbl1_u8(raw, vidxhi);
1744 const uint16x8_t win = vreinterpretq_u16_u8(vcombine_u8(wlo, whi));
1745 const uint16x8_t codes16 = vandq_u16(vshrq_n_u16(vmulq_u16(win, vmul), 13), vmask);
1746 vst1_u8(out + i, vtbl1_u8(vc2s, vmovn_u16(codes16)));
1747 i += 8;
1748 }
1749 } else if (D == 4) {
1750 /* Register by register: GCC has no AArch32 vld1_u8_x2/_x4 before 14.
1751 * Loaded once per call, so the tuple form bought nothing anyway. */
1752 uint8x8x2_t vc2s;
1753 vc2s.val[0] = vld1_u8(c2s);
1754 vc2s.val[1] = vld1_u8(c2s + 8);
1755 static const uint8_t rep2[8] = {0, 0, 1, 1, 2, 2, 3, 3};
1756 static const int8_t sh4[8] = {0, -4, 0, -4, 0, -4, 0, -4};
1757 const uint8x8_t vrep = vld1_u8(rep2);
1758 const int8x8_t vsh = vld1_s8(sh4);
1759 const uint8x8_t vmask = vdup_n_u8(0x0F);
1760 while (i + 8 <= n) {
1761 uint32_t w;
1762 ZXC_MEMCPY(&w, bits + ((i * 4) >> 3), 4);
1763 const uint8x8_t raw = vreinterpret_u8_u32(vdup_n_u32(w));
1764 const uint8x8_t rep = vtbl1_u8(raw, vrep);
1765 const uint8x8_t codes = vand_u8(vshl_u8(rep, vsh), vmask);
1766 vst1_u8(out + i, vtbl2_u8(vc2s, codes));
1767 i += 8;
1768 }
1769 } else if (D == 5) {
1770 // Same window scheme as D=3; c2s has 32 entries (VTBL4). 5 source bytes.
1771 // Register by register: see D == 4.
1772 uint8x8x4_t vc2s;
1773 vc2s.val[0] = vld1_u8(c2s);
1774 vc2s.val[1] = vld1_u8(c2s + 8);
1775 vc2s.val[2] = vld1_u8(c2s + 16);
1776 vc2s.val[3] = vld1_u8(c2s + 24);
1777 static const uint8_t idxlo[8] = {0, 1, 0, 1, 1, 2, 1, 2};
1778 static const uint8_t idxhi[8] = {2, 3, 3, 4, 3, 4, 4, 5};
1779 static const uint16_t mul8[8] = {2048, 64, 512, 16, 128, 1024, 32, 256};
1780 const uint8x8_t vidxlo = vld1_u8(idxlo);
1781 const uint8x8_t vidxhi = vld1_u8(idxhi);
1782 const uint16x8_t vmul = vld1q_u16(mul8);
1783 const uint16x8_t vmask = vdupq_n_u16(0x1F);
1784 while (i + 8 <= n) {
1785 uint64_t w = 0;
1786 ZXC_MEMCPY(&w, bits + ((i * 5) >> 3), 5);
1787 const uint8x8_t raw = vcreate_u8(w);
1788 const uint16x8_t win =
1789 vreinterpretq_u16_u8(vcombine_u8(vtbl1_u8(raw, vidxlo), vtbl1_u8(raw, vidxhi)));
1790 const uint8x8_t codes =
1791 vmovn_u16(vandq_u16(vshrq_n_u16(vmulq_u16(win, vmul), 11), vmask));
1792 vst1_u8(out + i, vtbl4_u8(vc2s, codes));
1793 i += 8;
1794 }
1795 } else if (D == 6) {
1796 // Same window scheme; c2s has 64 entries: two VTBL4 halves, select by
1797 // code bit 5. 6 source bytes.
1798 uint8x8x4_t lo, hi; // register by register: see D == 4
1799 lo.val[0] = vld1_u8(c2s);
1800 lo.val[1] = vld1_u8(c2s + 8);
1801 lo.val[2] = vld1_u8(c2s + 16);
1802 lo.val[3] = vld1_u8(c2s + 24);
1803 hi.val[0] = vld1_u8(c2s + 32);
1804 hi.val[1] = vld1_u8(c2s + 40);
1805 hi.val[2] = vld1_u8(c2s + 48);
1806 hi.val[3] = vld1_u8(c2s + 56);
1807 static const uint8_t idxlo[8] = {0, 1, 0, 1, 1, 2, 2, 3};
1808 static const uint8_t idxhi[8] = {3, 4, 3, 4, 4, 5, 5, 6};
1809 static const uint16_t mul8[8] = {1024, 16, 64, 256, 1024, 16, 64, 256};
1810 const uint8x8_t vidxlo = vld1_u8(idxlo);
1811 const uint8x8_t vidxhi = vld1_u8(idxhi);
1812 const uint16x8_t vmul = vld1q_u16(mul8);
1813 const uint16x8_t vmask = vdupq_n_u16(0x3F);
1814 while (i + 8 <= n) {
1815 uint64_t w = 0;
1816 ZXC_MEMCPY(&w, bits + ((i * 6) >> 3), 6);
1817 const uint8x8_t raw = vcreate_u8(w);
1818 const uint16x8_t win =
1819 vreinterpretq_u16_u8(vcombine_u8(vtbl1_u8(raw, vidxlo), vtbl1_u8(raw, vidxhi)));
1820 const uint8x8_t codes =
1821 vmovn_u16(vandq_u16(vshrq_n_u16(vmulq_u16(win, vmul), 10), vmask));
1822 const uint8x8_t sel =
1823 vbsl_u8(vcge_u8(codes, vdup_n_u8(32)), vtbl4_u8(hi, vsub_u8(codes, vdup_n_u8(32))),
1824 vtbl4_u8(lo, codes));
1825 vst1_u8(out + i, sel);
1826 i += 8;
1827 }
1828 }
1829#elif defined(ZXC_USE_AVX512) || defined(ZXC_USE_AVX2) || \
1830 (defined(ZXC_USE_SSE2) && defined(__SSE4_1__))
1831#if defined(ZXC_USE_AVX512) && defined(__AVX512VBMI__)
1832 /* vpmultishiftqb reads an 8-bit field at an arbitrary bit offset: the
1833 * unaligned D-bit read, in one instruction. Two facts carry the rest -
1834 * 64 codes are exactly 8*D bytes and byte-aligned, so the tables are the
1835 * same every step; and only the low D bits of a field survive, so bytes
1836 * past 8*D are irrelevant and both accesses can be clamped to the run.
1837 * Clamping the store also ends the run, hence nothing narrower below. */
1838 if (D >= 2 && D <= 6) {
1839 uint8_t arr[64];
1840 uint8_t shf[64];
1841 for (int k = 0; k < 8; k++) {
1842 for (int j = 0; j < 8; j++) {
1843 arr[k * 8 + j] = (uint8_t)(k * D + j);
1844 shf[k * 8 + j] = (uint8_t)(j * D);
1845 }
1846 }
1847 const __m512i varr = _mm512_loadu_si512((const void*)arr);
1848 const __m512i vshf = _mm512_loadu_si512((const void*)shf);
1849 const __m512i vand = _mm512_set1_epi8((char)((1 << D) - 1));
1850 /* c2s holds 2^D entries and nothing is guaranteed past them. */
1851 const __mmask64 tm = (D == 6) ? ~(__mmask64)0 : (((__mmask64)1 << (1 << D)) - 1);
1852 const __m512i vc2s = _mm512_maskz_loadu_epi8(tm, (const void*)c2s);
1853 const size_t nbytes = zxc_pivco_run_bytes((uint32_t)n, (uint8_t)D);
1854 while (i < n) {
1855 const size_t off = ((size_t)i * (size_t)D) >> 3;
1856 const size_t avail = nbytes - off;
1857 const size_t left = n - i;
1858 const __mmask64 lm = (avail >= 64) ? ~(__mmask64)0 : (((__mmask64)1 << avail) - 1);
1859 const __mmask64 sm = (left >= 64) ? ~(__mmask64)0 : (((__mmask64)1 << left) - 1);
1860 const __m512i raw = _mm512_maskz_loadu_epi8(lm, (const void*)(bits + off));
1861 const __m512i q = _mm512_permutexvar_epi8(varr, raw);
1862 const __m512i codes = _mm512_and_si512(_mm512_multishift_epi64_epi8(vshf, q), vand);
1863 _mm512_mask_storeu_epi8((void*)(out + i), sm, _mm512_permutexvar_epi8(codes, vc2s));
1864 i += 64;
1865 }
1866 if (i > n) i = n;
1867 }
1868#else
1869#if defined(ZXC_USE_AVX2)
1870 /* Codes 16..31 start exactly 2*D bytes in, so the upper half runs the same
1871 * pattern over a shifted source: one shuffle vector serves both, and packus
1872 * leaves each half's codes in order in its own lane - no cross-lane fixup.
1873 * The bound keeps both 16-byte reads inside the run; the exact-length
1874 * 16-wide loops below take the tail. */
1875 if (D >= 2 && D <= 6) {
1876 uint8_t sa[16];
1877 uint8_t sb[16];
1878 uint16_t mu[8];
1879 for (int q = 0; q < 8; q++) {
1880 const int ba = (q * D) >> 3;
1881 sa[2 * q] = (uint8_t)ba;
1882 sa[2 * q + 1] = (uint8_t)(ba + 1);
1883 sb[2 * q] = (uint8_t)(ba + D); /* code q+8 sits D bytes further */
1884 sb[2 * q + 1] = (uint8_t)(ba + D + 1);
1885 mu[q] = (uint16_t)(1U << (16 - D - ((q * D) & 7)));
1886 }
1887 const __m256i vsa = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)sa));
1888 const __m256i vsb = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)sb));
1889 const __m256i vmu = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)mu));
1890 const __m256i vand = _mm256_set1_epi8((char)((1 << D) - 1));
1891 uint8_t tab[64];
1892 for (int e = 0; e < 64; e++) tab[e] = c2s[e & ((1 << D) - 1)];
1893 const __m256i t0 = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)tab));
1894 const __m256i t1 =
1895 _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)(tab + 16)));
1896 const __m256i t2 =
1897 _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)(tab + 32)));
1898 const __m256i t3 =
1899 _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*)(void*)(tab + 48)));
1900 const size_t nbytes = zxc_pivco_run_bytes((uint32_t)n, (uint8_t)D);
1901 while (i + 32 <= n && ((size_t)i * (size_t)D >> 3) + (size_t)(2 * D) + 16 <= nbytes) {
1902 const uint8_t* src = bits + ((size_t)i * (size_t)D >> 3);
1903 const __m256i raw = _mm256_inserti128_si256(
1904 _mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(const void*)src)),
1905 _mm_loadu_si128((const __m128i*)(const void*)(src + 2 * D)), 1);
1906 const __m256i ca =
1907 _mm256_srli_epi16(_mm256_mullo_epi16(_mm256_shuffle_epi8(raw, vsa), vmu), 16 - D);
1908 const __m256i cb =
1909 _mm256_srli_epi16(_mm256_mullo_epi16(_mm256_shuffle_epi8(raw, vsb), vmu), 16 - D);
1910 const __m256i codes = _mm256_and_si256(_mm256_packus_epi16(ca, cb), vand);
1911 __m256i sym;
1912 if (D <= 4) {
1913 sym = _mm256_shuffle_epi8(t0, codes);
1914 } else {
1915 const __m256i b4 = _mm256_slli_epi16(codes, 3); /* code bit 4 -> sign */
1916 const __m256i lo = _mm256_blendv_epi8(_mm256_shuffle_epi8(t0, codes),
1917 _mm256_shuffle_epi8(t1, codes), b4);
1918 if (D == 5) {
1919 sym = lo;
1920 } else {
1921 const __m256i hi = _mm256_blendv_epi8(_mm256_shuffle_epi8(t2, codes),
1922 _mm256_shuffle_epi8(t3, codes), b4);
1923 sym = _mm256_blendv_epi8(lo, hi, _mm256_slli_epi16(codes, 2));
1924 }
1925 }
1926 _mm256_storeu_si256((__m256i*)(void*)(out + i), sym);
1927 i += 32;
1928 }
1929 }
1930#endif
1931 if (D == 4) {
1932 const __m128i vc2s = _mm_loadu_si128((const __m128i*)(const void*)c2s);
1933 const __m128i vrep = _mm_setr_epi8(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
1934 const __m128i vmask = _mm_set1_epi8(0x0F);
1935 // even lanes keep low nibble, odd lanes take the high nibble: shift the
1936 // replicated bytes right by 4 via a 16-bit shift + odd-lane select.
1937 const __m128i vodd = _mm_set1_epi16(0x0F00 - 0x0F00 + (short)0xFF00);
1938 while (i + 16 <= n) {
1939 const __m128i raw =
1940 _mm_loadl_epi64((const __m128i*)(const void*)(bits + ((i * 4) >> 3)));
1941 const __m128i rep = _mm_shuffle_epi8(raw, vrep);
1942 const __m128i hi = _mm_and_si128(_mm_srli_epi16(rep, 4), _mm_set1_epi8(0x0F));
1943 const __m128i lo = _mm_and_si128(rep, vmask);
1944 const __m128i codes = _mm_blendv_epi8(lo, hi, vodd);
1945 _mm_storeu_si128((__m128i*)(void*)(out + i), _mm_shuffle_epi8(vc2s, codes));
1946 i += 16;
1947 }
1948 } else if (D == 2) {
1949 // 16 codes from 4 bytes. SSE has no per-lane byte shift, so shift by
1950 // multiply: (b << (6 - 2j)) >> 6 keeps bits [2j+1:2j]. Bytes spread to
1951 // u16 lanes, times {64,16,4,1}, shifted, then packed back.
1952 uint8_t c2s16[16];
1953 for (int k = 0; k < 16; k++) c2s16[k] = c2s[k & 3];
1954 const __m128i vc2s = _mm_loadu_si128((const __m128i*)(const void*)c2s16);
1955 const __m128i vspreadA =
1956 _mm_setr_epi8(0, (char)0x80, 0, (char)0x80, 0, (char)0x80, 0, (char)0x80, 1, (char)0x80,
1957 1, (char)0x80, 1, (char)0x80, 1, (char)0x80);
1958 const __m128i vspreadB =
1959 _mm_setr_epi8(2, (char)0x80, 2, (char)0x80, 2, (char)0x80, 2, (char)0x80, 3, (char)0x80,
1960 3, (char)0x80, 3, (char)0x80, 3, (char)0x80);
1961 const __m128i vmul = _mm_setr_epi16(64, 16, 4, 1, 64, 16, 4, 1);
1962 while (i + 16 <= n) {
1963 const __m128i raw = _mm_cvtsi32_si128(
1964 (int)((uint32_t)bits[(i * 2) >> 3] | ((uint32_t)bits[((i * 2) >> 3) + 1] << 8) |
1965 ((uint32_t)bits[((i * 2) >> 3) + 2] << 16) |
1966 ((uint32_t)bits[((i * 2) >> 3) + 3] << 24)));
1967 const __m128i a16 =
1968 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, vspreadA), vmul), 6);
1969 const __m128i b16 =
1970 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, vspreadB), vmul), 6);
1971 const __m128i codes = _mm_and_si128(_mm_packus_epi16(a16, b16), _mm_set1_epi8(3));
1972 _mm_storeu_si128((__m128i*)(void*)(out + i), _mm_shuffle_epi8(vc2s, codes));
1973 i += 16;
1974 }
1975 } else if (D == 3) {
1976 // 16-bit window {byte_j,byte_j+1} per lane (byte_j = Di>>3); SSE has no
1977 // per-lane u16 shift, so extract bits [s,s+D) of window w by w*2^(16-D-s)
1978 // (field lands in the top D bits) then >>(16-D); s_j = Dj&7. D=3: 6 bytes.
1979 uint8_t c2s16[16];
1980 for (int k = 0; k < 16; k++) c2s16[k] = c2s[k & 7];
1981 const __m128i vc2s = _mm_loadu_si128((const __m128i*)(const void*)c2s16);
1982 const __m128i shufA = _mm_setr_epi8(0, 1, 0, 1, 0, 1, 1, 2, 1, 2, 1, 2, 2, 3, 2, 3);
1983 const __m128i shufB = _mm_setr_epi8(3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6);
1984 const __m128i vmul = _mm_setr_epi16(8192, 1024, 128, 4096, 512, 64, 2048, 256);
1985 while (i + 16 <= n) {
1986 const size_t off = (i * 3) >> 3;
1987 uint32_t w0;
1988 uint16_t w1;
1989 ZXC_MEMCPY(&w0, bits + off, 4);
1990 ZXC_MEMCPY(&w1, bits + off + 4, 2); /* exactly 6 bytes read */
1991 const __m128i raw = _mm_insert_epi16(_mm_cvtsi32_si128((int)w0), (int16_t)w1, 2);
1992 const __m128i cA =
1993 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufA), vmul), 13);
1994 const __m128i cB =
1995 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufB), vmul), 13);
1996 const __m128i codes = _mm_and_si128(_mm_packus_epi16(cA, cB), _mm_set1_epi8(7));
1997 _mm_storeu_si128((__m128i*)(void*)(out + i), _mm_shuffle_epi8(vc2s, codes));
1998 i += 16;
1999 }
2000 } else if (D == 5) {
2001 // c2s has 32 entries: pshufb does 16, so select lo/hi by code bit 4.
2002 const __m128i vlo = _mm_loadu_si128((const __m128i*)(const void*)c2s);
2003 const __m128i vhi = _mm_loadu_si128((const __m128i*)(const void*)(c2s + 16));
2004 const __m128i shufA = _mm_setr_epi8(0, 1, 0, 1, 1, 2, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5);
2005 const __m128i shufB = _mm_setr_epi8(5, 6, 5, 6, 6, 7, 6, 7, 7, 8, 8, 9, 8, 9, 9, 10);
2006 const __m128i vmul = _mm_setr_epi16(2048, 64, 512, 16, 128, 1024, 32, 256);
2007 while (i + 16 <= n) {
2008 const size_t off = (i * 5) >> 3;
2009 uint16_t w1;
2010 ZXC_MEMCPY(&w1, bits + off + 8, 2); /* 10 source bytes */
2011 const __m128i raw = _mm_insert_epi16(
2012 _mm_loadl_epi64((const __m128i*)(const void*)(bits + off)), (int16_t)w1, 4);
2013 const __m128i cA =
2014 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufA), vmul), 11);
2015 const __m128i cB =
2016 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufB), vmul), 11);
2017 const __m128i codes = _mm_and_si128(_mm_packus_epi16(cA, cB), _mm_set1_epi8(0x1F));
2018 const __m128i sel =
2019 _mm_blendv_epi8(_mm_shuffle_epi8(vlo, codes), _mm_shuffle_epi8(vhi, codes),
2020 _mm_slli_epi16(codes, 3));
2021 _mm_storeu_si128((__m128i*)(void*)(out + i), sel);
2022 i += 16;
2023 }
2024 } else if (D == 6) {
2025 // c2s has 64 entries: 4 pshufb sub-tables, select by code bits 4-5.
2026 const __m128i t0 = _mm_loadu_si128((const __m128i*)(const void*)c2s);
2027 const __m128i t1 = _mm_loadu_si128((const __m128i*)(const void*)(c2s + 16));
2028 const __m128i t2 = _mm_loadu_si128((const __m128i*)(const void*)(c2s + 32));
2029 const __m128i t3 = _mm_loadu_si128((const __m128i*)(const void*)(c2s + 48));
2030 const __m128i shufA = _mm_setr_epi8(0, 1, 0, 1, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5, 5, 6);
2031 const __m128i shufB = _mm_setr_epi8(6, 7, 6, 7, 7, 8, 8, 9, 9, 10, 9, 10, 10, 11, 11, 12);
2032 const __m128i vmul = _mm_setr_epi16(1024, 16, 64, 256, 1024, 16, 64, 256);
2033 while (i + 16 <= n) {
2034 const size_t off = (i * 6) >> 3;
2035 uint32_t w1;
2036 ZXC_MEMCPY(&w1, bits + off + 8, 4); /* 12 source bytes */
2037 const __m128i raw = _mm_insert_epi32(
2038 _mm_loadl_epi64((const __m128i*)(const void*)(bits + off)), (int)w1, 2);
2039 const __m128i cA =
2040 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufA), vmul), 10);
2041 const __m128i cB =
2042 _mm_srli_epi16(_mm_mullo_epi16(_mm_shuffle_epi8(raw, shufB), vmul), 10);
2043 const __m128i codes = _mm_and_si128(_mm_packus_epi16(cA, cB), _mm_set1_epi8(0x3F));
2044 const __m128i m4 = _mm_slli_epi16(codes, 3);
2045 const __m128i lo =
2046 _mm_blendv_epi8(_mm_shuffle_epi8(t0, codes), _mm_shuffle_epi8(t1, codes), m4);
2047 const __m128i hi =
2048 _mm_blendv_epi8(_mm_shuffle_epi8(t2, codes), _mm_shuffle_epi8(t3, codes), m4);
2049 _mm_storeu_si128((__m128i*)(void*)(out + i),
2050 _mm_blendv_epi8(lo, hi, _mm_slli_epi16(codes, 2)));
2051 i += 16;
2052 }
2053 }
2054#endif /* AVX-512 VBMI, else AVX2 + SSE */
2055#endif
2056 // Generic scalar bit-reader (any D).
2057 {
2058 uint64_t bitpos = i * (uint64_t)D;
2059 const uint32_t m = (1U << D) - 1U;
2060 const size_t fbytes = (size_t)(((uint64_t)n * (uint64_t)D + 7U) >> 3);
2061 while (i < n) {
2062 const size_t byte = (size_t)(bitpos >> 3);
2063 uint32_t w = bits[byte];
2064 if (byte + 1 < fbytes) w |= (uint32_t)bits[byte + 1] << 8;
2065 if (D > 8 && byte + 2 < fbytes) w |= (uint32_t)bits[byte + 2] << 16;
2066 out[i++] = c2s[(w >> (bitpos & 7U)) & m];
2067 bitpos += (uint64_t)D;
2068 }
2069 }
2070}
2071
2080static ZXC_ALWAYS_INLINE void zxc_pivco_emit_leaf_pair(uint8_t* RESTRICT out, const size_t n,
2081 const uint8_t sym0, const uint8_t sym1,
2082 const uint8_t* RESTRICT bits) {
2083 size_t i = 0;
2084#if defined(ZXC_USE_NEON64)
2085 const uint8x16_t vsym0 = vdupq_n_u8(sym0);
2086 const uint8x16_t vdelta = vdupq_n_u8((uint8_t)(sym0 ^ sym1));
2087 static const uint8_t rep_idx[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1};
2088 static const uint8_t bit_sel[16] = {1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128};
2089 const uint8x16_t vrep = vld1q_u8(rep_idx);
2090 const uint8x16_t vsel = vld1q_u8(bit_sel);
2091 while (i + 16 <= n) {
2092 uint8x16_t ctrl = vdupq_n_u8(0);
2093 ctrl = vsetq_lane_u8(bits[i >> 3], ctrl, 0);
2094 ctrl = vsetq_lane_u8(bits[(i >> 3) + 1], ctrl, 1);
2095 const uint8x16_t rep = vqtbl1q_u8(ctrl, vrep);
2096 const uint8x16_t mask = vtstq_u8(rep, vsel);
2097 vst1q_u8(out + i, veorq_u8(vsym0, vandq_u8(vdelta, mask)));
2098 i += 16;
2099 }
2100#elif defined(ZXC_USE_NEON32)
2101 const uint8x8_t vsym0 = vdup_n_u8(sym0);
2102 const uint8x8_t vdelta = vdup_n_u8((uint8_t)(sym0 ^ sym1));
2103 static const uint8_t bit_sel8[8] = {1, 2, 4, 8, 16, 32, 64, 128};
2104 const uint8x8_t vsel = vld1_u8(bit_sel8);
2105 while (i + 8 <= n) {
2106 const uint8x8_t mask = vtst_u8(vdup_n_u8(bits[i >> 3]), vsel);
2107 vst1_u8(out + i, veor_u8(vsym0, vand_u8(vdelta, mask)));
2108 i += 8;
2109 }
2110#elif defined(ZXC_USE_AVX512) || defined(ZXC_USE_AVX2) || \
2111 (defined(ZXC_USE_SSE2) && defined(__SSSE3__))
2112#if defined(ZXC_USE_AVX512)
2113 /* The control word is already the blend mask; the masked store takes the
2114 * tail, hence nothing narrower below. */
2115 {
2116 const __m512i z0 = _mm512_set1_epi8((char)sym0);
2117 const __m512i z1 = _mm512_set1_epi8((char)sym1);
2118 while (i < n) {
2119 const size_t left = n - i;
2120 const size_t cb = (left + 7) >> 3;
2121 uint64_t ctrl = 0;
2122 ZXC_MEMCPY(&ctrl, bits + (i >> 3), cb < 8 ? cb : 8); /* not past the run */
2123 const __mmask64 sm = (left >= 64) ? ~(__mmask64)0 : (((__mmask64)1 << left) - 1);
2124 _mm512_mask_storeu_epi8((void*)(out + i), sm,
2125 _mm512_mask_blend_epi8((__mmask64)ctrl, z0, z1));
2126 i += 64;
2127 }
2128 if (i > n) i = n;
2129 }
2130#else
2131#if defined(ZXC_USE_AVX2)
2132 /* Broadcasting the control dword lets each 128-bit half pick its own two
2133 * bytes out of it. */
2134 {
2135 const __m256i y0 = _mm256_set1_epi8((char)sym0);
2136 const __m256i ydelta = _mm256_set1_epi8((char)(uint8_t)(sym0 ^ sym1));
2137 const __m256i yrep = _mm256_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
2138 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3);
2139 const __m256i ysel =
2140 _mm256_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char)128, 1, 2, 4, 8, 16, 32, 64, (char)128,
2141 1, 2, 4, 8, 16, 32, 64, (char)128, 1, 2, 4, 8, 16, 32, 64, (char)128);
2142 while (i + 32 <= n) {
2143 uint32_t c4;
2144 ZXC_MEMCPY(&c4, bits + (i >> 3), 4);
2145 const __m256i rep = _mm256_shuffle_epi8(_mm256_set1_epi32((int)c4), yrep);
2146 const __m256i mask = _mm256_cmpeq_epi8(_mm256_and_si256(rep, ysel), ysel);
2147 _mm256_storeu_si256((__m256i*)(void*)(out + i),
2148 _mm256_xor_si256(y0, _mm256_and_si256(ydelta, mask)));
2149 i += 32;
2150 }
2151 }
2152#endif
2153 const __m128i vsym0 = _mm_set1_epi8((char)sym0);
2154 const __m128i vdelta = _mm_set1_epi8((char)(uint8_t)(sym0 ^ sym1));
2155 const __m128i vrep = _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
2156 const __m128i vsel =
2157 _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char)128, 1, 2, 4, 8, 16, 32, 64, (char)128);
2158 while (i + 16 <= n) {
2159 const __m128i ctrl = _mm_cvtsi32_si128(bits[i >> 3] | ((int)bits[(i >> 3) + 1] << 8));
2160 const __m128i rep = _mm_shuffle_epi8(ctrl, vrep);
2161 // lanes where the selected bit is set -> 0xFF
2162 const __m128i mask = _mm_cmpeq_epi8(_mm_and_si128(rep, vsel), vsel);
2163 _mm_storeu_si128((__m128i*)(void*)(out + i),
2164 _mm_xor_si128(vsym0, _mm_and_si128(vdelta, mask)));
2165 i += 16;
2166 }
2167#endif /* AVX-512, else AVX2 + SSE */
2168#endif
2169 while (i < n) {
2170 const int bit = (bits[i >> 3] >> (i & 7)) & 1;
2171 out[i++] = bit ? sym1 : sym0;
2172 }
2173}
2174
2185static int zxc_pivco_decode_core(const uint8_t* RESTRICT payload, const size_t payload_size,
2186 uint8_t* RESTRICT dst, const size_t n,
2187 const zxc_pivco_tree_t* RESTRICT t, uint8_t* RESTRICT scratch) {
2188 if (UNLIKELY(n == 0)) return ZXC_ERROR_CORRUPT_DATA;
2189
2190 // Pass 1, in wire order: node counts from the partition bits, and where
2191 // each depth's runs start. Leaf-pair children (emitted by their parent) and
2192 // a flat root's inside get count 0: empty runs, nothing to flag.
2193 uint32_t count[ZXC_PIVCO_NODE_SLOTS];
2194 const uint8_t* lvl_run[ZXC_HUF_MAX_CODE_LEN_ULTRA];
2195 const int slot = t->node_base[t->max_depth + 1];
2196 count[0] = (uint32_t)n;
2197 count[slot] = 0;
2198 const uint8_t* p = payload;
2199 const uint8_t* const pend = payload + payload_size;
2200 for (int d = 0; d < t->max_depth; d++) {
2201 lvl_run[d] = p;
2202 const int L = zxc_pivco_leaves(t, d);
2203 const int N = t->node_base[d + 1] - t->node_base[d];
2204 const int Lc = zxc_pivco_leaves(t, d + 1);
2205 const uint32_t* const cnt = count + t->node_base[d];
2206 uint32_t* const ccnt = count + t->node_base[d + 1];
2207 const uint8_t* const fd = t->flat_d + t->node_base[d];
2208 for (int i = L; i < N; i++) {
2209 const uint32_t c = cnt[i];
2210 const int k2 = 2 * (i - L); /* first child */
2211 if (fd[i]) {
2212 // Packed-code run: no partition below, nothing to popcount.
2213 const size_t fbytes = zxc_pivco_run_bytes(c, fd[i]);
2214 if (UNLIKELY((size_t)(pend - p) < fbytes)) return ZXC_ERROR_CORRUPT_DATA;
2215 p += fbytes;
2216 ccnt[k2] = 0;
2217 ccnt[k2 + 1] = 0;
2218 continue;
2219 }
2220 const size_t nbytes = zxc_pivco_run_bytes(c, 0); /* merge node: c partition bits */
2221 if (UNLIKELY((size_t)(pend - p) < nbytes)) return ZXC_ERROR_CORRUPT_DATA;
2222 // popcount of the c valid bits = the right child's count. All but the
2223 // last byte counted fast, the last one with its padding masked - if the
2224 // 8-byte loop swallowed it unmasked, padding bits would inflate `ones`.
2225 uint32_t ones = 0;
2226 if (nbytes) {
2227 const size_t full = nbytes - 1;
2228 size_t k = 0;
2229 for (; k + 8 <= full; k += 8) {
2230 uint64_t w;
2231 ZXC_MEMCPY(&w, p + k, 8);
2232 ones += (uint32_t)zxc_pivco_popcnt64(w);
2233 }
2234 for (; k < full; k++) ones += (uint32_t)zxc_pivco_popcnt32(p[k]);
2235 uint8_t last = p[full];
2236 if (c & 7U) last &= (uint8_t)((1U << (c & 7U)) - 1U);
2237 ones += (uint32_t)zxc_pivco_popcnt32(last);
2238 }
2239 p += nbytes;
2240 if (UNLIKELY(ones > c)) return ZXC_ERROR_CORRUPT_DATA;
2241 const int leaf_pair = k2 + 1 < Lc;
2242 ccnt[k2] = leaf_pair ? 0 : c - ones;
2243 ccnt[k2 + 1] = leaf_pair ? 0 : ones;
2244 }
2245 }
2246 // The slot stands for the lone-symbol root's missing child: no 1 bits.
2247 if (UNLIKELY(count[slot] != 0)) return ZXC_ERROR_CORRUPT_DATA;
2248
2249 // Pass 2, bottom-up. Runs and children follow position order, so two
2250 // running offsets replace per-node tables.
2251 for (int d = t->max_depth; d >= 0; d--) {
2252 uint8_t* const buf_d = (d & 1) ? scratch : dst;
2253 const uint8_t* const buf_c = (d & 1) ? dst : scratch; /* children at d+1 (read-only) */
2254 const int L = zxc_pivco_leaves(t, d);
2255 const int N = t->node_base[d + 1] - t->node_base[d];
2256 const uint32_t* const cnt = count + t->node_base[d];
2257 const uint8_t* const sym = t->syms + t->leaf_base[d];
2258 size_t off = 0;
2259 for (int i = 0; i < L; i++) {
2260 if (cnt[i]) ZXC_MEMSET(buf_d + off, sym[i], cnt[i]);
2261 off += cnt[i];
2262 }
2263 if (d == t->max_depth) continue; /* leaves only, as in pass 1 */
2264 const uint8_t* run = lvl_run[d];
2265 const uint32_t* const ccnt = count + t->node_base[d + 1];
2266 const uint8_t* const csym = t->syms + t->leaf_base[d + 1];
2267 const int Lc = zxc_pivco_leaves(t, d + 1);
2268 const uint8_t* const fd = t->flat_d + t->node_base[d];
2269 size_t coff = 0;
2270 for (int i = L; i < N; i++) {
2271 const uint32_t c = cnt[i];
2272 const int k2 = 2 * (i - L);
2273 if (c) {
2274 if (fd[i]) {
2275 const int D = fd[i];
2276 const int leaves = zxc_pivco_flat_leaves(t, t->node_base[d] + i, d, D);
2277 zxc_pivco_unpack_flat(buf_d + off, c, D, run, t->syms + leaves);
2278 } else if (k2 + 1 < Lc) {
2279 zxc_pivco_emit_leaf_pair(buf_d + off, c, csym[k2], csym[k2 + 1], run);
2280 } else {
2281 const uint32_t nl = ccnt[k2];
2282 zxc_pivco_merge(buf_d + off, buf_c + coff, nl, c - nl, run);
2283 }
2284 }
2285 run += zxc_pivco_run_bytes(c, fd[i]);
2286 off += c;
2287 coff += ccnt[k2] + ccnt[k2 + 1];
2288 }
2289 }
2290 return ZXC_OK;
2291}
2292
2308int zxc_huf_decode_section(const uint8_t* RESTRICT payload, const size_t payload_size,
2309 uint8_t* RESTRICT dst, const size_t n, uint8_t* RESTRICT scratch) {
2310 if (UNLIKELY(payload_size < (size_t)ZXC_HUF_TABLE_SIZE)) return ZXC_ERROR_CORRUPT_DATA;
2311 uint8_t code_len[ZXC_HUF_NUM_SYMBOLS];
2312 const int rc = zxc_huf_unpack_lengths(payload, code_len);
2313 if (UNLIKELY(rc != ZXC_OK)) return rc;
2315 if (UNLIKELY(zxc_pivco_tree_build(code_len, &t) != 0)) return ZXC_ERROR_CORRUPT_DATA;
2316 return zxc_pivco_decode_core(payload + ZXC_HUF_TABLE_SIZE, payload_size - ZXC_HUF_TABLE_SIZE,
2317 dst, n, &t, scratch);
2318}
2319
2320#ifndef ZXC_HUF_NO_DICT_SECTIONS
2328int zxc_huf_decode_section_dict(const uint8_t* RESTRICT payload, const size_t payload_size,
2329 uint8_t* RESTRICT dst, const size_t n,
2330 const zxc_pivco_tree_t* RESTRICT tree, uint8_t* RESTRICT scratch) {
2331 return zxc_pivco_decode_core(payload, payload_size, dst, n, tree, scratch);
2332}
2333#endif /* !ZXC_HUF_NO_DICT_SECTIONS */
2334#endif /* !ZXC_HUF_NO_DECODER */
#define ZXC_HUF_TABLE_SIZE
Size of a packed literal Huffman code-lengths table (256 symbols, 4 bits each): the shared table in a...
@ ZXC_ERROR_CORRUPT_DATA
Corrupted compressed data.
Definition zxc_error.h:56
@ ZXC_ERROR_MEMORY
Memory allocation failure.
Definition zxc_error.h:41
@ 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_MALLOC(size)
Heap allocator.
Definition zxc_deps.h:68
#define ZXC_ALWAYS_INLINE
Forces a function to be inlined (fallback for non-GCC/Clang/MSVC compilers).
#define ZXC_CALLOC(nmemb, size)
Zero-initialised heap allocator.
Definition zxc_deps.h:74
#define ZXC_FREE(ptr)
Heap deallocator.
Definition zxc_deps.h:86
Workspace of zxc_huf_nudge_code_lengths: tables and DP planes, once a 10 KiB frame and a per-block al...
int16_t sym_order[256]
Symbols by descending frequency.
uint64_t pfg[64+1]
Group-mass prefix sums.
uint64_t jcur[(64+1) *(64+1)]
DP plane.
uint64_t pf_rank[256+1]
Frequency-rank prefix sums.
uint64_t pf[256+1]
Canonical-order prefix sums.
uint8_t arrive[(11+1) *(64+1) *(64+1)]
Per-level arrival choice, c <= ZXC_HUF_NUDGE_DP_M.
zxc_huf_pm_leaf_t leaves[256]
Live symbols, sorted.
uint64_t jnxt[(64+1) *(64+1)]
Next plane.
uint8_t cand[4][256]
Candidate code lengths.
Trace-back stack frame for the package-merge code-length recovery.
int16_t idx
Item index within that level.
int8_t lvl
Package-merge level being traced back.
Boundary package-merge work item.
int16_t right
Right child index, or -1 for a leaf.
int16_t sym
Symbol index for a leaf, or -1 for an internal node.
int16_t left
Left child index, or -1 for a leaf.
A live symbol and its weight, the package-merge sort key.
uint32_t w
Frequency.
int16_t sym
Byte value.
A PivCo code tree: its canonical shape, by depth.
Error codes and error-name lookup for the ZXC library.
static void zxc_pivco_merge(uint8_t *out, const uint8_t *src, const size_t nl, const size_t nr, const uint8_t *bits)
Merge two adjacent child sequences under control bits.
static size_t zxc_pivco_layout(const zxc_pivco_tree_t *t, const uint32_t *count, uint32_t *cur)
Payload size, and each run's first bit as a cursor if cur is set.
static void zxc_huf_nudge_pf_canonical(const uint8_t *code_len, const uint32_t *freq, const uint32_t *blc, uint64_t *pf)
Frequency prefix sums over the leaves in canonical (length, symbol) order: pf[i] = mass of the first ...
static int zxc_huf_nudge_classes(const uint8_t *code_len, uint32_t *blc)
Per-length class counts of a code-length vector.
static void zxc_huf_nudge_eval(const uint32_t *blc, const uint64_t *pf, zxc_huf_nudge_cost_t *out)
Modeled (bits, level-touches) of one class-count histogram.
static void zxc_huf_nudge_walk(const uint32_t *blc0, const uint64_t *pf_rank, const int n, const int cap, uint32_t *out_blc)
Greedy shallow-to-deep walk over the slot ledger.
static int zxc_pivco_encode_core(const uint8_t *literals, const size_t n_literals, const uint32_t *freq, const uint8_t *code_len, const zxc_pivco_tree_t *t, const uint32_t *codes, uint8_t *dst, const size_t dst_cap, const int with_header)
Shared PivCo section encoder body.
static void zxc_huf_nudge_assign(const uint32_t *blc, const int16_t *sym_order, uint8_t *cand_len)
Assign a class-count multiset to symbols: frequency rank r takes the r-th shortest slot (rearrangemen...
size_t zxc_huf_calc_size(const uint32_t *freq, const uint8_t *code_len, const int with_header)
Exact encoded size (bytes) of a PivCo section for this histogram and code lengths; includes the 128-b...
static int zxc_huf_nudge_dp_solve(zxc_huf_nudge_ws_t *ws, const uint64_t *pfg, const int m, const int cap_c, const int lu, const int g_log2, uint32_t *out_cblc)
Slot-ledger dynamic program: optimal class counts for the model.
static int zxc_pivco_leaves(const zxc_pivco_tree_t *t, const int d)
Leaves at depth d.
static uint64_t zxc_huf_nudge_j(const zxc_huf_nudge_cost_t *c)
Candidate cost J = 256*bits + lambda*touches (Q8 bit units).
static void zxc_pivco_emit_leaf_pair(uint8_t *out, const size_t n, const uint8_t sym0, const uint8_t sym1, const uint8_t *bits)
Direct emission for a node whose two children are BOTH leaves.
static void zxc_pivco_bitrev_permute(uint8_t *s, const int D)
Reorders s[0, 2^D) by bit-reversed index (an involution).
static uint64_t zxc_huf_nudge_dp_run_j(const int lu, const int lc, const int g_log2, const uint32_t s, const uint32_t c, const uint64_t *pfg, const uint32_t k)
Exact rank-weighted J of one leaf run placed at coarse level lc.
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 shared-dictionary literal section (no inline header).
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.
int zxc_huf_build_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, const int max_code_len)
Build length-limited canonical Huffman code lengths.
static void pm_leaves_sort(pm_leaf_t *leaves, const int n)
Sort pm_leaf_t array by ascending weight, ties broken by ascending symbol.
size_t zxc_huf_calc_size_dict(const uint32_t *freq, const uint8_t *code_len, const zxc_pivco_tree_t *tree)
Sizing core shared with zxc_huf_calc_size: exact payload size of one PivCo section for a prebuilt tre...
void zxc_huf_nudge_cost(const uint8_t *code_len, const uint32_t *freq, uint64_t *bits, uint64_t *touches)
Modeled (bits, level-touches) decode cost of one code-length vector.
static int zxc_pivco_tree_build(const uint8_t *code_len, zxc_pivco_tree_t *t)
Build the canonical code tree from per-symbol lengths.
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 literal section against a shared dictionary table.
static void zxc_pivco_unpack_flat(uint8_t *out, const size_t n, const int D, const uint8_t *bits, const uint8_t *c2s)
Decode a flat subtree's packed D-bit code run into symbols.
static void zxc_pivco_counts(const zxc_pivco_tree_t *t, const uint32_t *freq, uint32_t *count)
Per-node symbol counts from the histogram (encoder / size estimate).
static uint32_t zxc_huf_nudge_clamp(const uint32_t want, const uint32_t s, const uint32_t n_rem, const int l, const int cap)
Clamp a desired class count into the feasible set at one walk level.
#define ZXC_PIVCO_MERGE_STEP(w, pc)
Advances the merge cursors past one fixed-width step.
static int zxc_pivco_flat_leaves(const zxc_pivco_tree_t *t, const int g, const int d, const int D)
syms index of flat root g's first leaf: its prefix, then D zero bits.
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 literal/token section (PivCo layout, inline lengths header).
static void zxc_huf_nudge_complete(uint32_t *blc, const int l, uint32_t s, uint32_t n_rem, const uint32_t *blc0, const int cap)
Baseline-following completion: fill levels l+1..cap with the baseline class counts clamped into feasi...
static size_t zxc_pivco_run_bytes(const uint32_t count, const uint8_t flat_d)
Byte size of one PivCo node's on-wire bit run.
void zxc_huf_pack_lengths(const uint8_t *code_len, uint8_t *out)
Pack per-symbol code lengths into the 128-byte (4-bit nibble) header.
int zxc_huf_dict_tree_build(const uint8_t *packed_lengths, zxc_pivco_tree_t *tree, uint32_t *codes, uint8_t *code_len)
Prebuild a dict table's decode/encode state (tree-at-attach).
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 literal/token section (PivCo layout, inline lengths header).
int zxc_huf_unpack_lengths(const uint8_t *in, uint8_t *code_len)
Unpack and structurally validate a 128-byte packed lengths header.
static int zxc_pivco_decode_core(const uint8_t *payload, const size_t payload_size, uint8_t *dst, const size_t n, const zxc_pivco_tree_t *t, uint8_t *scratch)
Shared PivCo section decoder body (code lengths already unpacked).
static void zxc_pivco_codes(const zxc_pivco_tree_t *t, uint32_t *codes)
Code of every leaf: the prefix of its slot (see zxc_pivco_tree_t).
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.
#define ZXC_HUF_NUDGE_DP_M
Slot-ledger DP bound, coarse symbols per plane axis; the nudge groups symbols to stay under it.
static uint32_t zxc_le32(const void *p)
Reads a little-endian 32-bit value from a possibly unaligned address.
#define ZXC_HUF_NUDGE_SCRATCH_OFF
Offset of the zxc_huf_nudge_ws_t inside a nudge scratch.
#define ZXC_HUF_NUDGE_SCRATCH_SIZE
Scratch size (bytes) for zxc_huf_nudge_code_lengths: builder's, then workspace.
#define ZXC_HUF_NUDGE_LEVEL_COST
Fixed per-pass overhead (occurrence-equivalents) charged per merge level, modeling the pass-loop and ...
#define ZXC_HUF_NUDGE_DEEP_FLAT_PENALTY
Extra level-touches charged per occurrence under a flat root deeper than ZXC_PIVCO_UNPACK_FLAT_SIMD_M...
#define ZXC_HUF_NUDGE_MERGE_Q8
Adoption guard, speed side (Q8): adopt only while touches' * 256 <= touches0 * ZXC_HUF_NUDGE_MERGE_Q8...
#define ZXC_HUF_MAX_CODE_LEN_ULTRA
Maximum Huffman code length, in bits: the ceiling the decoder's on-wire validation accepts (and the l...
static uint32_t zxc_log2_u32(const uint32_t v)
Integer log-base-2 for a 32-bit value.
#define ZXC_HUF_PM_LEVEL_BOUND
Per-level item bound: at most leaves + paired packages from the previous level.
#define ZXC_PIVCO_MAX_NODES
Upper bound on PivCo tree nodes (full binary tree over the alphabet).
#define ZXC_HUF_NUDGE_BITS_PERMIL
Adoption guard, ratio side (permil): adopt only while bits' * 1000 <= bits0 * ZXC_HUF_NUDGE_BITS_PERM...
#define ZXC_PIVCO_UNPACK_FLAT_SIMD_MAX
Deepest flat subtree zxc_pivco_unpack_flat unpacks with a SIMD kernel (its D == 2....
#define ZXC_PIVCO_COVERED
flat_d of a node inside a flat root: no run, no children.
#define ZXC_PIVCO_NODE_SLOTS
Node-indexed array size: every node, plus a slot for the lone-symbol root's missing child.
#define ZXC_HUF_NUDGE_LAMBDA_Q8
Exchange rate (Q8 bits per modeled level-touch) in the candidate cost J = 256*bits + lambda*touches; ...
#define ZXC_HUF_NUM_SYMBOLS
Alphabet size: one entry per possible byte value.
Shuffle-index tables for the PivCo merge routines (declarations).