ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_dict.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
12
14
16#include "zxc_internal.h"
17
18// -------------------------------------------------------------------------
19// Dictionary ID
20// -------------------------------------------------------------------------
21
29uint32_t zxc_dict_compute_id(const void* RESTRICT dict, const size_t dict_size,
30 const void* RESTRICT huf_lengths) {
31 if (UNLIKELY(!dict || dict_size == 0)) return 0;
32 const uint32_t base = zxc_checksum(dict, dict_size, 0, ZXC_CHECKSUM_RAPIDHASH);
33 if (!huf_lengths) return base;
34 return zxc_checksum(huf_lengths, ZXC_HUF_TABLE_SIZE, base, ZXC_CHECKSUM_RAPIDHASH);
35}
36
37// -------------------------------------------------------------------------
38// .zxd format: save / load / bound
39//
40// Layout (ZXC_DICT_HEADER_SIZE = 16 bytes + content + Huffman table):
41// 0x00 4 Magic (0x9CB0D1C7 LE)
42// 0x04 1 Version (2)
43// 0x05 1 Flags (bits 0-3: checksum algo id, 0=RapidHash; bits 4-7 reserved)
44// 0x06 2 Content size (u16 LE)
45// 0x08 4 Dictionary ID (u32 LE; covers content AND the Huffman table)
46// 0x0C 2 Reserved (0)
47// 0x0E 2 Header Checksum (zxc_hash16, computed with 0x0E-0x0F zeroed)
48// 0x10 N Content bytes
49// +N 128 Packed Huffman code lengths (always present)
50// -------------------------------------------------------------------------
51
57uint32_t zxc_dict_read_id(const void* buf, const size_t buf_size) {
58 if (UNLIKELY(!buf || buf_size < ZXC_DICT_HEADER_SIZE)) return 0;
59 const uint8_t* p = (const uint8_t*)buf;
60 if (UNLIKELY(zxc_le32(p) != ZXC_DICT_MAGIC)) return 0;
61 return zxc_le32(p + 8);
62}
63
69size_t zxc_dict_save_bound(const size_t content_size) {
70 return ZXC_DICT_HEADER_SIZE + content_size + ZXC_HUF_TABLE_SIZE;
71}
72
79int64_t zxc_dict_save(const void* RESTRICT content, const size_t content_size,
80 const void* RESTRICT huf_lengths, void* RESTRICT buf,
81 const size_t buf_capacity) {
82 if (UNLIKELY(!content || content_size == 0 || !huf_lengths)) return ZXC_ERROR_NULL_INPUT;
83 if (UNLIKELY(content_size > ZXC_DICT_SIZE_MAX)) return ZXC_ERROR_DICT_TOO_LARGE;
84
85 const size_t total = ZXC_DICT_HEADER_SIZE + content_size + ZXC_HUF_TABLE_SIZE;
86 if (UNLIKELY(buf_capacity < total)) return ZXC_ERROR_DST_TOO_SMALL;
87
88 uint8_t* dst = (uint8_t*)buf;
89
91 dst[4] = ZXC_DICT_VERSION;
92 dst[5] = 0; /* flags: reserved */
93 zxc_store_le16(dst + 6, (uint16_t)content_size);
94 zxc_store_le32(dst + 8,
95 zxc_dict_compute_id(content, content_size, (const uint8_t*)huf_lengths));
96 zxc_store_le32(dst + 12, 0); /* reserved (0x0C), checksum (0x0E) zeroed before hashing */
97 const uint16_t sum = zxc_hash16(dst);
98 zxc_store_le16(dst + 14, sum);
99
100 ZXC_MEMCPY(dst + ZXC_DICT_HEADER_SIZE, content, content_size);
101 ZXC_MEMCPY(dst + ZXC_DICT_HEADER_SIZE + content_size, huf_lengths, ZXC_HUF_TABLE_SIZE);
102
103 return (int64_t)total;
104}
105
113int zxc_dict_load(const void* RESTRICT buf, const size_t buf_size,
114 const void** RESTRICT content_out, size_t* RESTRICT content_size_out,
115 const void** RESTRICT huf_out, uint32_t* RESTRICT dict_id_out) {
116 if (UNLIKELY(!buf || !content_out || !content_size_out)) return ZXC_ERROR_NULL_INPUT;
117 if (UNLIKELY(buf_size < ZXC_DICT_HEADER_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
118
119 const uint8_t* src = (const uint8_t*)buf;
120
121 if (UNLIKELY(zxc_le32(src) != ZXC_DICT_MAGIC)) return ZXC_ERROR_BAD_MAGIC;
122 if (UNLIKELY(src[4] != ZXC_DICT_VERSION)) return ZXC_ERROR_BAD_VERSION;
123
124 const size_t content_size = zxc_le16(src + 6);
125 if (UNLIKELY(content_size == 0)) return ZXC_ERROR_CORRUPT_DATA;
126 if (UNLIKELY(content_size > ZXC_DICT_SIZE_MAX)) return ZXC_ERROR_DICT_TOO_LARGE;
127 if (UNLIKELY(buf_size < ZXC_DICT_HEADER_SIZE + content_size + ZXC_HUF_TABLE_SIZE))
128 return ZXC_ERROR_SRC_TOO_SMALL; // LCOV_EXCL_LINE
129
130 uint8_t temp[ZXC_DICT_HEADER_SIZE];
131 ZXC_MEMCPY(temp, src, sizeof(temp));
132 zxc_store_le16(temp + 14, 0); /* checksum (0x0E), zeroed before hashing */
133 const uint16_t expected_sum = zxc_hash16(temp);
134 if (UNLIKELY(zxc_le16(src + 14) != expected_sum)) return ZXC_ERROR_BAD_HEADER;
135 // Flags and Reserved must be 0.
136 if (UNLIKELY(src[5] != ZXC_CHECKSUM_RAPIDHASH || zxc_le16(src + 12) != 0))
138
139 const uint8_t* content = src + ZXC_DICT_HEADER_SIZE;
140 const uint8_t* huf = content + content_size;
141
142 // Verify dict_id matches the (content, table) pair.
143 const uint32_t id = zxc_dict_compute_id(content, content_size, huf);
144 if (UNLIKELY(zxc_le32(src + 8) != id)) return ZXC_ERROR_BAD_CHECKSUM;
145
146 *content_out = content;
147 *content_size_out = content_size;
148 if (huf_out) *huf_out = huf;
149 if (dict_id_out) *dict_id_out = id;
150
151 return ZXC_OK;
152}
153
160const void* zxc_dict_huf(const void* buf, const size_t buf_size) {
161 if (UNLIKELY(!buf || buf_size < ZXC_DICT_HEADER_SIZE)) return NULL;
162 const uint8_t* src = (const uint8_t*)buf;
163 if (UNLIKELY(zxc_le32(src) != ZXC_DICT_MAGIC)) return NULL;
164 if (UNLIKELY(src[4] != ZXC_DICT_VERSION)) return NULL;
165 const size_t content_size = zxc_le16(src + 6);
166 if (UNLIKELY(content_size == 0 ||
167 buf_size < ZXC_DICT_HEADER_SIZE + content_size + ZXC_HUF_TABLE_SIZE))
168 return NULL; // LCOV_EXCL_LINE
169 return src + ZXC_DICT_HEADER_SIZE + content_size;
170}
171
172// -------------------------------------------------------------------------
173// Dictionary training: k-gram frequency selection
174//
175// Algorithm:
176// 1. Concatenate all samples into a corpus.
177// 2. For each position in the corpus, hash the k-gram (k = MIN_MATCH_LEN)
178// and count occurrences in a fixed-size hash map.
179// 3. Build candidate segments: each starts at a frequent k-gram and extends
180// while neighbours stay frequent. Its score is the summed frequency of its
181// k-grams - its coverage of the corpus.
182// 4. Fill the dictionary greedily in descending coverage, zeroing each pick's
183// k-grams: one copy serves all future matches, so segments that collapse
184// are skipped and capacity goes to NEW patterns.
185// -------------------------------------------------------------------------
186
196static uint32_t zxc_dict_hash(const uint8_t* p) {
197 uint32_t v = zxc_le32(p);
198 v ^= (uint32_t)p[4];
199 return (v * ZXC_HASH_MULT32) >> (32 - ZXC_DICT_HASH_BITS);
200}
201
205typedef struct {
206 size_t offset;
207 uint32_t score;
208 uint16_t length;
209} zxc_dict_seg_t;
210
221static void zxc_dict_sift_down(zxc_dict_seg_t* RESTRICT a, size_t root, const size_t n) {
222 for (;;) {
223 size_t child = 2 * root + 1;
224 if (child >= n) break;
225 if (child + 1 < n && a[child + 1].score < a[child].score) child++;
226 if (a[root].score <= a[child].score) break;
227 const zxc_dict_seg_t t = a[root];
228 a[root] = a[child];
229 a[child] = t;
230 root = child;
231 }
232}
233
248static void zxc_dict_sort_segs_desc(zxc_dict_seg_t* RESTRICT a, const size_t n) {
249 if (UNLIKELY(n < 2)) return;
250 for (size_t i = n / 2; i-- > 0;) zxc_dict_sift_down(a, i, n);
251 for (size_t end = n; end > 1;) {
252 end--;
253 const zxc_dict_seg_t t = a[0];
254 a[0] = a[end];
255 a[end] = t;
256 zxc_dict_sift_down(a, 0, end);
257 }
258}
259
264static int zxc_dict_corpus_size(const void* const* samples, const size_t* sample_sizes,
265 const size_t n_samples, size_t* total) {
266 size_t sum = 0;
267 for (size_t i = 0; i < n_samples; i++) {
268 if (UNLIKELY(sample_sizes[i] > 0 && !samples[i])) return ZXC_ERROR_NULL_INPUT;
269 if (UNLIKELY(sample_sizes[i] > SIZE_MAX - sum)) return ZXC_ERROR_OVERFLOW;
270 sum += sample_sizes[i];
271 }
272 *total = sum;
273 return ZXC_OK;
274}
275
283int64_t zxc_dict_train_content(const void* const* RESTRICT samples,
284 const size_t* RESTRICT sample_sizes, const size_t n_samples,
285 void* RESTRICT dict_buf, const size_t dict_capacity) {
286 if (UNLIKELY(!samples || !sample_sizes || n_samples == 0 || !dict_buf || dict_capacity == 0))
287 return ZXC_ERROR_NULL_INPUT; // LCOV_EXCL_LINE
288 if (UNLIKELY(dict_capacity > ZXC_DICT_SIZE_MAX)) return ZXC_ERROR_DICT_TOO_LARGE;
289
290 // Step 1: concatenate samples
291 size_t corpus_size;
292 const int src = zxc_dict_corpus_size(samples, sample_sizes, n_samples, &corpus_size);
293 if (UNLIKELY(src != ZXC_OK)) return src;
294 if (UNLIKELY(corpus_size < ZXC_DICT_KGRAM_LEN)) return ZXC_ERROR_SRC_TOO_SMALL;
295
296 int64_t rc;
297 uint16_t* freq = NULL;
298 zxc_dict_seg_t* segs = NULL;
299 uint8_t* corpus = (uint8_t*)ZXC_MALLOC(corpus_size);
300 if (UNLIKELY(!corpus)) return ZXC_ERROR_MEMORY;
301 {
302 size_t pos = 0;
303 for (size_t i = 0; i < n_samples; i++) {
304 if (sample_sizes[i] > 0) ZXC_MEMCPY(corpus + pos, samples[i], sample_sizes[i]);
305 pos += sample_sizes[i];
306 }
307 }
308
309 // Step 2: count k-gram frequencies
310 freq = (uint16_t*)ZXC_CALLOC(ZXC_DICT_HASH_SIZE, sizeof(uint16_t));
311 if (UNLIKELY(!freq)) {
312 rc = ZXC_ERROR_MEMORY; // LCOV_EXCL_LINE
313 goto done; // LCOV_EXCL_LINE
314 }
315
316 // Sample positions rather than count them all: a full count saturates the
317 // 16-bit counters, the extension test then never stops and segments balloon
318 // into filler.
319 const size_t kgram_limit = corpus_size - ZXC_DICT_KGRAM_LEN + 1;
320 size_t freq_stride = kgram_limit / ZXC_DICT_SAMPLE_TARGET;
321 if (freq_stride < 1) freq_stride = 1;
322 for (size_t i = 0; i < kgram_limit; i += freq_stride) {
323 const uint32_t h = zxc_dict_hash(corpus + i);
324 if (freq[h] < UINT16_MAX) freq[h]++;
325 }
326
327 // Step 3: build candidate segments, scored by coverage. Starts are spread
328 // across the whole corpus - a fixed k-gram stride would exhaust the segment
329 // budget in the prefix and never see a large input's tail.
330 const size_t max_segs = corpus_size / ZXC_DICT_KGRAM_LEN;
331 const size_t seg_alloc = (max_segs < ZXC_DICT_MAX_SEGMENTS) ? max_segs : ZXC_DICT_MAX_SEGMENTS;
332 size_t stride = ZXC_DICT_KGRAM_LEN;
333 if (seg_alloc > 0 && corpus_size / seg_alloc > stride) stride = corpus_size / seg_alloc;
334
335 segs = (zxc_dict_seg_t*)ZXC_MALLOC(seg_alloc * sizeof(zxc_dict_seg_t));
336 if (UNLIKELY(!segs)) {
337 rc = ZXC_ERROR_MEMORY; // LCOV_EXCL_LINE
338 goto done; // LCOV_EXCL_LINE
339 }
340
341 size_t n_segs = 0;
342 for (size_t i = 0; i + ZXC_DICT_KGRAM_LEN <= corpus_size && n_segs < seg_alloc; i += stride) {
343 const uint32_t h = zxc_dict_hash(corpus + i);
344 const uint16_t f = freq[h];
345 if (f < 2) continue;
346
347 // Extend the segment as long as the next k-gram is also frequent, and
348 // accumulate coverage (summed k-gram frequency) as the score.
349 uint32_t coverage = f;
350 size_t end = i + ZXC_DICT_KGRAM_LEN;
351 while (end + ZXC_DICT_KGRAM_LEN <= corpus_size && end - i < ZXC_DICT_SEGMENT_MAX) {
352 const uint16_t nf = freq[zxc_dict_hash(corpus + end)];
353 if (nf < 2) break;
354 coverage += nf;
355 end += ZXC_DICT_KGRAM_LEN;
356 }
357
358 segs[n_segs].offset = i;
359 segs[n_segs].length = (uint16_t)(end - i);
360 segs[n_segs].score = coverage;
361 n_segs++;
362 }
363
364 if (UNLIKELY(n_segs == 0)) {
365 // No frequent patterns. Use tail of corpus as dict.
366 const size_t copy = (corpus_size < dict_capacity) ? corpus_size : dict_capacity;
367 ZXC_MEMCPY(dict_buf, corpus + corpus_size - copy, copy);
368 rc = (int64_t)copy;
369 goto done;
370 }
371
372 // Step 4: pick greedily in descending coverage, zeroing each pick's k-grams
373 // so overlapping patterns aren't copied twice. Picks are compacted in place
374 // into segs[0..n_sel); placement is step 5.
375 zxc_dict_sort_segs_desc(segs, n_segs);
376
377 uint8_t* out = (uint8_t*)dict_buf;
378 size_t n_sel = 0;
379 size_t total = 0;
380
381 for (size_t i = 0; i < n_segs && total < dict_capacity; i++) {
382 const size_t seg_off = segs[i].offset;
383 const size_t seg_end = seg_off + segs[i].length;
384
385 // Recompute coverage from the decrementing table: skip the segment if
386 // earlier picks have already covered more than half of its k-grams.
387 uint32_t cur = 0;
388 for (size_t p = seg_off; p + ZXC_DICT_KGRAM_LEN <= seg_end; p += ZXC_DICT_KGRAM_LEN)
389 cur += freq[zxc_dict_hash(corpus + p)];
390 if (cur * 2 < segs[i].score) continue;
391
392 size_t copy = segs[i].length;
393 if (copy > dict_capacity - total) copy = dict_capacity - total;
394
395 // One copy in the dictionary serves all future matches: mark this
396 // segment's k-grams as covered so later segments cover new ground.
397 for (size_t p = seg_off; p + ZXC_DICT_KGRAM_LEN <= seg_end; p += ZXC_DICT_KGRAM_LEN)
398 freq[zxc_dict_hash(corpus + p)] = 0;
399
400 // Record the pick (n_sel <= i, so this never clobbers an unread entry).
401 segs[n_sel].offset = seg_off;
402 segs[n_sel].length = (uint16_t)copy;
403 n_sel++;
404 total += copy;
405 }
406
407 // Released early: the emit loop below only needs the picks.
408 ZXC_FREE(freq);
409 freq = NULL;
410
411 // Step 5: emit in reverse so the highest-coverage segment lands at the END
412 // of the dict. The dict sits just before the data, so bytes near its end
413 // have the smallest offsets: cheapest to encode, last to fall out of the
414 // 16-bit window. No padding - short picks just make a shorter dict, whereas
415 // padding would raise the offset of everything after it.
416 size_t filled = 0;
417 for (size_t i = n_sel; i-- > 0;) {
418 ZXC_MEMCPY(out + filled, corpus + segs[i].offset, segs[i].length);
419 filled += segs[i].length;
420 }
421
422 // Nothing selected (every segment subsumed by earlier picks): fall back to
423 // the corpus tail so the dict is never empty, like the n_segs == 0 path.
424 if (UNLIKELY(filled == 0)) {
425 const size_t tail = (corpus_size < dict_capacity) ? corpus_size : dict_capacity;
426 ZXC_MEMCPY(out, corpus + corpus_size - tail, tail);
427 filled = tail;
428 }
429
430 rc = (int64_t)filled;
431
432done:
433 ZXC_FREE(segs);
434 ZXC_FREE(freq);
435 ZXC_FREE(corpus);
436 return rc;
437}
438
439// -------------------------------------------------------------------------
440// Shared literal Huffman table training (Tier-2)
441//
442// Compresses the samples with the freshly trained dictionary at level
443// ZXC_LEVEL_DENSITY and histograms the REAL post-LZ literals (cctx
444// lit_freq_acc hook). Raw bytes are a poor proxy: matches against the dict
445// remove most repeated content, so the two distributions differ a lot.
446//
447// Slices are ZXC_DICT_HUF_TRAIN_BLOCK bytes - the small-block regime is where
448// a shared table pays (per-block headers are unaffordable there) and where
449// literal density is highest.
450// -------------------------------------------------------------------------
451
458int zxc_dict_train_huf(const void* const* RESTRICT samples, const size_t* RESTRICT sample_sizes,
459 const size_t n_samples, const void* RESTRICT dict, const size_t dict_size,
460 uint8_t* RESTRICT huf_lengths_out) {
461 if (UNLIKELY(!samples || !sample_sizes || n_samples == 0 || !dict || dict_size == 0 ||
462 !huf_lengths_out))
464 if (UNLIKELY(dict_size > ZXC_DICT_SIZE_MAX)) return ZXC_ERROR_DICT_TOO_LARGE;
465
466 size_t corpus_total;
467 const int src = zxc_dict_corpus_size(samples, sample_sizes, n_samples, &corpus_total);
468 if (UNLIKELY(src != ZXC_OK)) return src;
469
470 const size_t eff_chunk = zxc_block_size_ceil(dict_size + ZXC_DICT_HUF_TRAIN_BLOCK);
471
472 zxc_cctx_t cctx;
473 if (UNLIKELY(zxc_cctx_init(&cctx, eff_chunk, 1, ZXC_LEVEL_DENSITY, 0, dict_size) != ZXC_OK))
474 return ZXC_ERROR_MEMORY; // LCOV_EXCL_LINE
475
476 uint32_t freq[ZXC_HUF_NUM_SYMBOLS] = {0};
477 cctx.lit_freq_acc = freq;
478
479 const size_t out_cap = zxc_compress_bound(eff_chunk);
480 uint8_t* out_scratch = (uint8_t*)ZXC_MALLOC(out_cap);
481 if (UNLIKELY(!out_scratch)) {
482 // LCOV_EXCL_START
483 zxc_cctx_free(&cctx);
484 return ZXC_ERROR_MEMORY;
485 // LCOV_EXCL_STOP
486 }
487
488 // [dict | slice] concat scratch carved by zxc_cctx_init (mode 1).
489 uint8_t* const work = cctx.dict_buffer;
490 ZXC_MEMCPY(work, dict, dict_size);
491
492 // Slice stride: process every slice while the corpus fits the budget,
493 // else 1 slice out of `stride` spread evenly across all samples.
494 const size_t stride = (corpus_total > ZXC_DICT_HUF_SAMPLE_BUDGET)
495 ? (corpus_total - 1) / ZXC_DICT_HUF_SAMPLE_BUDGET + 1
496 : 1;
497
498 int rc = ZXC_OK;
499 size_t slice_idx = 0;
500 for (size_t s = 0; s < n_samples && rc == ZXC_OK; s++) {
501 const uint8_t* sample = (const uint8_t*)samples[s];
502 const size_t sample_size = sample_sizes[s];
503 if (sample_size == 0) continue;
504
505 for (size_t off = 0; off < sample_size; off += ZXC_DICT_HUF_TRAIN_BLOCK, slice_idx++) {
506 if (slice_idx % stride != 0) continue;
507 const size_t slice = (sample_size - off < ZXC_DICT_HUF_TRAIN_BLOCK)
508 ? (sample_size - off)
510 ZXC_MEMCPY(work + dict_size, sample + off, slice);
511 const int r =
512 zxc_compress_chunk_wrapper(&cctx, work, dict_size + slice, out_scratch, out_cap, 0);
513 if (UNLIKELY(r < 0)) {
514 rc = r;
515 break;
516 }
517 }
518 }
519
520 if (rc == ZXC_OK) {
521 // A low-entropy corpus leaves no post-LZ literals - an empty histogram,
522 // not corrupt input. Detected on the histogram itself, so an all-zero
523 // table is emitted and every block falls back to its own; inferring
524 // "empty" from a build error code could mask a real failure.
525 uint32_t any = 0;
526 for (int i = 0; i < ZXC_HUF_NUM_SYMBOLS; i++) any |= freq[i];
527 if (any == 0) {
528 ZXC_MEMSET(huf_lengths_out, 0, ZXC_HUF_TABLE_SIZE);
529 } else {
530 // No coverage smoothing: under an 8-bit cap a code over all 256
531 // symbols can only be the degenerate all-8-bit one (Kraft equality),
532 // which compresses nothing. Unseen symbols stay code-less and their
533 // blocks fall back to a per-block table.
534 uint8_t code_len[ZXC_HUF_NUM_SYMBOLS];
536 if (rc == ZXC_OK) {
537 // Dict tables serve the most literal-bound decode path, so the
538 // flat/length nudge pays off most here.
539 (void)zxc_huf_nudge_code_lengths(freq, code_len, NULL, 0,
541 zxc_huf_pack_lengths(code_len, huf_lengths_out);
542 }
543 }
544 }
545
546 ZXC_FREE(out_scratch);
547 zxc_cctx_free(&cctx);
548 return rc;
549}
550
551// -------------------------------------------------------------------------
552// All-in-one convenience: samples -> ready-to-write .zxd bytes
553// -------------------------------------------------------------------------
554
562int64_t zxc_dict_train(const void* const* RESTRICT samples, const size_t* RESTRICT sample_sizes,
563 const size_t n_samples, void* RESTRICT zxd_buf, const size_t zxd_capacity) {
564 if (UNLIKELY(!samples || !sample_sizes || n_samples == 0 || !zxd_buf || zxd_capacity == 0))
566
567 // Train the content into a temporary buffer (max-content sized), then the
568 // shared table from that content, then serialize both into zxd_buf. The
569 // two-phase training is a real data dependency (the table needs the trained
570 // content to histogram post-LZ literals); this hides it behind one call.
571 uint8_t* content = (uint8_t*)ZXC_MALLOC(ZXC_DICT_SIZE_MAX);
572 if (UNLIKELY(!content)) return ZXC_ERROR_MEMORY;
573
574 int64_t out;
575 const int64_t content_size =
576 zxc_dict_train_content(samples, sample_sizes, n_samples, content, ZXC_DICT_SIZE_MAX);
577 if (UNLIKELY(content_size <= 0)) {
578 out = (content_size < 0) ? content_size : ZXC_ERROR_SRC_TOO_SMALL;
579 goto done;
580 }
581
582 {
583 uint8_t huf[ZXC_HUF_TABLE_SIZE];
584 const int hrc = zxc_dict_train_huf(samples, sample_sizes, n_samples, content,
585 (size_t)content_size, huf);
586 if (UNLIKELY(hrc != ZXC_OK)) {
587 // LCOV_EXCL_START
588 out = hrc;
589 goto done;
590 // LCOV_EXCL_STOP
591 }
592 out = zxc_dict_save(content, (size_t)content_size, huf, zxd_buf, zxd_capacity);
593 }
594
595done:
596 ZXC_FREE(content);
597 return out;
598}
size_t zxc_compress_bound(const size_t input_size)
Maximum compressed size for an input of input_size bytes.
uint32_t zxc_dict_read_id(const void *buf, const size_t buf_size)
Extracts the stored dict_id from a serialized .zxd buffer.
Definition zxc_dict.c:57
int64_t zxc_dict_train(const void *const *samples, const size_t *sample_sizes, const size_t n_samples, void *zxd_buf, const size_t zxd_capacity)
One-shot training: sample buffers in, ready-to-write .zxd bytes out.
Definition zxc_dict.c:562
size_t zxc_dict_save_bound(const size_t content_size)
Worst-case .zxd byte size for a dictionary of content_size bytes.
Definition zxc_dict.c:69
const void * zxc_dict_huf(const void *buf, const size_t buf_size)
Returns a pointer to the packed Huffman table inside a .zxd buffer.
Definition zxc_dict.c:160
int zxc_dict_train_huf(const void *const *samples, const size_t *sample_sizes, const size_t n_samples, const void *dict, const size_t dict_size, uint8_t *huf_lengths_out)
Trains the shared literal Huffman table for a dictionary (Tier-2).
Definition zxc_dict.c:458
uint32_t zxc_dict_compute_id(const void *dict, const size_t dict_size, const void *huf_lengths)
Computes the dictionary identifier for dict (and optional table).
Definition zxc_dict.c:29
int zxc_dict_load(const void *buf, const size_t buf_size, const void **content_out, size_t *content_size_out, const void **huf_out, uint32_t *dict_id_out)
Parses a .zxd buffer, returning in-buffer views of content and table.
Definition zxc_dict.c:113
int64_t zxc_dict_train_content(const void *const *samples, const size_t *sample_sizes, const size_t n_samples, void *dict_buf, const size_t dict_capacity)
Trains a raw dictionary from sample buffers by k-gram coverage.
Definition zxc_dict.c:283
int64_t zxc_dict_save(const void *content, const size_t content_size, const void *huf_lengths, void *buf, const size_t buf_capacity)
Serializes dictionary content + Huffman table into the .zxd format.
Definition zxc_dict.c:79
#define ZXC_DICT_SIZE_MAX
Maximum dictionary content size in bytes (64 KB - 1).
#define ZXC_DICT_MAGIC
Magic word opening a .zxd dictionary file, stored little-endian (C7 D1 B0 9C).
#define ZXC_DICT_HEADER_SIZE
Size of the .zxd dictionary file header in bytes.
#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_BAD_MAGIC
Invalid magic word in file header.
Definition zxc_error.h:48
@ ZXC_ERROR_BAD_VERSION
Unsupported file format version.
Definition zxc_error.h:49
@ ZXC_ERROR_OVERFLOW
Buffer overflow detected during processing.
Definition zxc_error.h:58
@ ZXC_ERROR_CORRUPT_DATA
Corrupted compressed data.
Definition zxc_error.h:56
@ ZXC_ERROR_NULL_INPUT
Required input pointer is NULL.
Definition zxc_error.h:62
@ ZXC_ERROR_MEMORY
Memory allocation failure.
Definition zxc_error.h:41
@ ZXC_ERROR_BAD_HEADER
Corrupted or invalid header (checksum mismatch).
Definition zxc_error.h:50
@ ZXC_ERROR_DST_TOO_SMALL
Destination buffer too small.
Definition zxc_error.h:44
@ ZXC_ERROR_SRC_TOO_SMALL
Source buffer too small or truncated input.
Definition zxc_error.h:45
@ ZXC_ERROR_BAD_CHECKSUM
A block's decoded bytes fail its checksum, or the archive digest mismatches.
Definition zxc_error.h:51
@ ZXC_OK
Success (no error).
Definition zxc_error.h:38
@ ZXC_ERROR_DICT_TOO_LARGE
Dictionary exceeds maximum allowed size.
Definition zxc_error.h:71
#define ZXC_MALLOC(size)
Heap allocator.
Definition zxc_deps.h:68
#define ZXC_CHECKSUM_RAPIDHASH
Checksum algorithm id for RapidHash (default, sole implementation).
#define ZXC_DICT_MAX_SEGMENTS
Maximum number of candidate segments the dictionary trainer keeps.
#define ZXC_DICT_VERSION
Current dictionary file format version.
#define ZXC_DICT_SEGMENT_MAX
Longest trainer segment: one repetitive region cannot take the whole budget.
#define ZXC_CALLOC(nmemb, size)
Zero-initialised heap allocator.
Definition zxc_deps.h:74
#define ZXC_DICT_HASH_SIZE
Number of buckets in the dictionary trainer's frequency table.
#define ZXC_FREE(ptr)
Heap deallocator.
Definition zxc_deps.h:86
#define ZXC_DICT_HUF_TRAIN_BLOCK
Training block size for the shared-table literal statistics.
#define ZXC_DICT_SAMPLE_TARGET
Target number of sampled k-gram positions for the trainer's frequency estimate.
#define ZXC_DICT_HUF_SAMPLE_BUDGET
Cap on the corpus bytes compressed by the literal-table trainer: the histogram converges early,...
#define ZXC_DICT_KGRAM_LEN
K-gram length scanned by the dictionary trainer.
#define ZXC_DICT_HASH_BITS
Address bits for the dictionary trainer's k-gram frequency table.
@ ZXC_LEVEL_DENSITY
Higher density: adds Huffman-coded literals on top of COMPACT.
Compression / decompression context.
uint32_t * lit_freq_acc
Trainer hook: when non-NULL, the SPL encoder accumulates post-LZ literal byte frequencies here (256 e...
uint8_t * dict_buffer
[dict | data] concat scratch carved from memory_block when dict_size > 0 (NULL otherwise).
One-shot buffer compression and decompression.
void zxc_cctx_free(zxc_cctx_t *ctx)
Releases all resources owned by a compression context.
Definition zxc_common.c:382
int zxc_cctx_init(zxc_cctx_t *ctx, const size_t chunk_size, const int mode, const int level, const int checksum_enabled, const size_t dict_size)
Initialises a compression / decompression context, allocating the persistent buffer with ZXC_ALIGNED_...
Definition zxc_common.c:319
int zxc_compress_chunk_wrapper(zxc_cctx_t *ctx, const uint8_t *chunk, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Compresses one chunk into a single ZXC block (the compression hot path).
static int zxc_dict_corpus_size(const void *const *samples, const size_t *sample_sizes, const size_t n_samples, size_t *total)
Sums the sample sizes, refusing a NULL sample of nonzero size and a sum that wraps size_t.
Definition zxc_dict.c:264
static void zxc_dict_sift_down(zxc_dict_seg_t *a, size_t root, const size_t n)
Restore the min-heap property at root over the range a[0..n).
Definition zxc_dict.c:221
static void zxc_dict_sort_segs_desc(zxc_dict_seg_t *a, const size_t n)
Sort a[0..n) by zxc_dict_seg_t::score in descending order.
Definition zxc_dict.c:248
static uint32_t zxc_dict_hash(const uint8_t *p)
Hashes the k-gram at p into a frequency-table bucket index.
Definition zxc_dict.c:196
Pre-trained dictionary API for ZXC compression.
int zxc_huf_build_code_lengths(const uint32_t *freq, uint8_t *code_len, void *scratch, const int max_code_len)
Build length-limited per-symbol Huffman code lengths from frequencies.
void zxc_huf_pack_lengths(const uint8_t *code_len, uint8_t *out)
Pack per-symbol code lengths into the 128-byte nibble 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.
Internal definitions, constants, SIMD helpers, and utility functions.
static uint32_t zxc_le32(const void *p)
Reads a little-endian 32-bit value from a possibly unaligned address.
static size_t zxc_block_size_ceil(const size_t v)
Branchless bit_ceil: smallest power of two >= v, clamped to ZXC_BLOCK_SIZE_MIN.
static uint16_t zxc_le16(const void *p)
Reads a little-endian 16-bit value from a possibly unaligned address.
static uint16_t zxc_hash16(const uint8_t *p)
Computes the 2-byte checksum for file and dictionary headers.
static void zxc_store_le16(void *p, const uint16_t v)
Writes a 16-bit value little-endian to a possibly unaligned address.
#define ZXC_HASH_MULT32
Marsaglia 32-bit multiplier: the 4-byte LZ and dictionary hash.
#define ZXC_HUF_MAX_CODE_LEN_DENSITY
Encoder code-length cap for levels up to ZXC_LEVEL_DENSITY (below ZXC_LEVEL_ULTRA): shallow 8-bit tre...
static void zxc_store_le32(void *p, const uint32_t v)
Writes a 32-bit value little-endian to a possibly unaligned address.
static uint32_t zxc_checksum(const void *input, const size_t len, const uint64_t seed, const uint8_t hash_method)
Calculates a 32-bit hash for a given input buffer.
#define ZXC_HUF_NUM_SYMBOLS
Alphabet size: one entry per possible byte value.