ZXC 1.0.3
High-performance asymmetric lossless compression library
Loading...
Searching...
No Matches
zxc_common.c
Go to the documentation of this file.
1// SPDX-License-Identifier: BSD-3-Clause
2/*
3 * ZXC - High-performance lossless compression
4 *
5 * Copyright (c) Bertrand Lebonnois and contributors.
6 */
7
16
19#include "zxc_internal.h"
20
21// ============================================================================
22// CONTEXT MANAGEMENT
23// ============================================================================
24
30// cppcheck-suppress unusedFunction
31size_t zxc_frame_info_size(void) { return sizeof(zxc_frame_info_t); }
32
33// Offset table of the persistent buffer carved by every cctx/dctx init. Both
34// modes compute it identically, for the workspace sizer and the in-place init.
35typedef struct {
36 size_t total;
37 // mode == 0 (decompress)
38 size_t off_work;
39 size_t off_lit_dctx;
40 // mode == 0: scratch for a Huffman-coded SPL token section (enc_tok == HUFFMAN).
41 size_t off_tok_dctx;
42 size_t sz_tok_dctx;
43 // mode == 0: PivCo decode level scratch (one chunk-sized ping-pong buffer).
44 size_t off_pivco_dctx;
45 size_t sz_pivco_dctx;
46 // mode == 1 (compress)
47 size_t off_hash_pos;
48 size_t off_hash_tags;
49 size_t off_chain;
50 size_t off_seq_union;
51 size_t off_split_hist;
52 size_t off_extras;
53 size_t off_lit_cctx;
54 // meaningful only when sz_opt > 0 (level >= ZXC_LEVEL_DENSITY).
55 size_t off_opt;
56 // both modes: [dict | data] concat scratch, present only when dict_size > 0.
57 size_t off_dict;
58 // both modes: dict Huffman tree-at-attach state, present only when dict_size > 0.
59 size_t off_dict_huf;
60 // Sub-buffer sizes (re-used by the partitioning step + zero-init).
61 size_t sz_hash_pos;
62 size_t sz_hash_tags;
63 size_t sz_opt;
64 size_t sz_dict; /* 0 = no dictionary buffer. */
65 size_t max_seq;
66} zxc_cctx_layout_t;
67
74static ZXC_ALWAYS_INLINE size_t zxc_cctx_max_seq(const size_t chunk_size) {
75 return chunk_size / ZXC_LZ_MIN_MATCH_LEN + 16;
76}
77
85static void zxc_dctx_entropy_sizes(const size_t chunk_size, size_t* RESTRICT sz_tok,
86 size_t* RESTRICT sz_pivco) {
87 *sz_tok = zxc_cctx_max_seq(chunk_size) + ZXC_PAD_SIZE;
88 *sz_pivco = chunk_size + ZXC_PIVCO_SCRATCH_PAD;
89}
90
120static zxc_cctx_layout_t compute_cctx_layout(const size_t chunk_size, const int mode,
121 const int level, const size_t dict_size,
122 const int defer_entropy_scratch) {
123 zxc_cctx_layout_t layout = {0};
124
125 const size_t max_seq = zxc_cctx_max_seq(chunk_size);
126
127 if (mode == 0) {
128 // Decompress: work_buf + lit_buffer, padded for wild-copy overshoot and
129 // sized worst-case. lit_buffer is provisioned at every level - the decoder
130 // cannot predict a block's literal encoding (RAW / RLE / HUFFMAN).
131 const size_t sz_work = chunk_size + ZXC_DECOMPRESS_TAIL_PAD;
132 const size_t sz_lit = chunk_size + ZXC_PAD_SIZE;
133
134 layout.off_work = layout.total;
135 layout.total += ZXC_ALIGN_CL(sz_work);
136 layout.off_lit_dctx = layout.total;
137 layout.total += ZXC_ALIGN_CL(sz_lit);
138 // Token-section decode scratch (level-7 SPL Huffman-codes the tokens) +
139 // PivCo ping-pong scratch. enc_lit/enc_tok are unpredictable, so static
140 // workspaces provision both up front (no-alloc contract); heap contexts
141 // defer them to the first entropy section, sparing L1-5 archives ~1.2x
142 // chunk_size. See zxc_cctx_alloc_entropy_scratch.
143 if (!defer_entropy_scratch) {
144 size_t sz_tok = 0;
145 size_t sz_pivco = 0;
146 zxc_dctx_entropy_sizes(chunk_size, &sz_tok, &sz_pivco);
147 layout.sz_tok_dctx = sz_tok;
148 layout.off_tok_dctx = layout.total;
149 layout.total += ZXC_ALIGN_CL(layout.sz_tok_dctx);
150 layout.sz_pivco_dctx = sz_pivco;
151 layout.off_pivco_dctx = layout.total;
152 layout.total += ZXC_ALIGN_CL(layout.sz_pivco_dctx);
153 }
154 } else {
155 // Compress: 7 partitions + optional opt_scratch at level >= ZXC_LEVEL_DENSITY.
156 const uint32_t offset_bits = zxc_log2_u32((uint32_t)chunk_size);
157 layout.max_seq = max_seq;
158 layout.sz_hash_pos = ZXC_LZ_HASH_SIZE * sizeof(uint32_t);
159 layout.sz_hash_tags = ZXC_LZ_HASH_SIZE * sizeof(uint8_t);
160 const size_t sz_chain = ZXC_LZ_WINDOW_SIZE * sizeof(uint16_t);
161 // buf_sequences (PAK, level <= ZXC_LEVEL_FAST) aliases buf_offsets, buf_tokens and
162 // buf_split (SPL, level >= ZXC_LEVEL_DEFAULT): 4 bytes per sequence either way.
163 const size_t sz_seq_union = layout.max_seq * sizeof(uint32_t);
164 const size_t vbyte_len = (offset_bits + 6) / 7;
165 const size_t sz_extras = layout.max_seq * 2 * vbyte_len;
166 const size_t sz_lit = chunk_size + ZXC_PAD_SIZE;
167
168 // opt_scratch (level >= ZXC_LEVEL_DENSITY): the optimal parser's DP arrays,
169 // reused transiently by the code-length builder and its nudge, so sized to
170 // the larger demand. Keep in sync with zxc_estimate_cctx_size() and its
171 // consumer in zxc_compress.c.
172 if (level >= ZXC_LEVEL_DENSITY) {
173 size_t sz_dp;
174 size_t sz_pl;
175 size_t sz_po;
176 size_t sz_bm;
177 zxc_opt_dp_sizes(chunk_size, &sz_dp, &sz_pl, &sz_po, &sz_bm);
178 const size_t dp_needed = sz_dp + sz_pl + sz_po + sz_bm;
179 layout.sz_opt =
180 (dp_needed > ZXC_HUF_NUDGE_SCRATCH_SIZE) ? dp_needed : ZXC_HUF_NUDGE_SCRATCH_SIZE;
181 }
182
183 layout.off_hash_pos = layout.total;
184 layout.total += ZXC_ALIGN_CL(layout.sz_hash_pos);
185 layout.off_hash_tags = layout.total;
186 layout.total += ZXC_ALIGN_CL(layout.sz_hash_tags);
187 layout.off_chain = layout.total;
188 layout.total += ZXC_ALIGN_CL(sz_chain);
189 layout.off_seq_union = layout.total;
190 layout.total += ZXC_ALIGN_CL(sz_seq_union);
191 layout.off_split_hist = layout.total;
192 layout.total += ZXC_ALIGN_CL(sizeof(zxc_spl_match_split_hist_t));
193 layout.off_extras = layout.total;
194 layout.total += ZXC_ALIGN_CL(sz_extras);
195 layout.off_lit_cctx = layout.total;
196 layout.total += ZXC_ALIGN_CL(sz_lit);
197 // opt_scratch is appended last so it is absent for levels 1..5 (zero
198 // waste on the common path) and only inflates the workspace at level 6.
199 if (layout.sz_opt) {
200 layout.off_opt = layout.total;
201 layout.total += ZXC_ALIGN_CL(layout.sz_opt);
202 }
203 }
204
205 // [dict | data] concat scratch (dict only). Compress chunk_size already
206 // spans [dict | block]; decompress prepends dict to a (chunk + PAD) region.
207 if (dict_size > 0) {
208 layout.sz_dict = (mode == 1) ? (chunk_size + ZXC_DECOMPRESS_TAIL_PAD)
209 : (dict_size + chunk_size + ZXC_DECOMPRESS_TAIL_PAD);
210 layout.off_dict = layout.total;
211 layout.total += ZXC_ALIGN_CL(layout.sz_dict);
212 layout.off_dict_huf = layout.total;
213 layout.total += ZXC_ALIGN_CL(sizeof(zxc_dict_huf_state_t));
214 }
215 return layout;
216}
217
225size_t zxc_cctx_compute_workspace_size(const size_t chunk_size, const int mode, const int level,
226 const size_t dict_size) {
227 if (UNLIKELY(chunk_size == 0)) return 0;
228 return compute_cctx_layout(chunk_size, mode, level, dict_size, 0).total;
229}
230
240int zxc_cctx_init_in_workspace(zxc_cctx_t* RESTRICT ctx, void* RESTRICT workspace,
241 const size_t workspace_size, const size_t chunk_size, const int mode,
242 const int level, const int checksum_enabled, const size_t dict_size,
243 const int defer_entropy_scratch) {
244 if (UNLIKELY(!ctx || !workspace || chunk_size == 0)) return ZXC_ERROR_NULL_INPUT;
245
246 const zxc_cctx_layout_t layout =
247 compute_cctx_layout(chunk_size, mode, level, dict_size, defer_entropy_scratch);
248 if (UNLIKELY(workspace_size < layout.total)) return ZXC_ERROR_DST_TOO_SMALL;
249
250 ZXC_MEMSET(ctx, 0, sizeof(zxc_cctx_t));
251 ctx->checksum_enabled = checksum_enabled;
252 ctx->chunk_size = chunk_size;
253 const uint32_t offset_bits = zxc_log2_u32((uint32_t)chunk_size);
254 ctx->offset_bits = offset_bits;
255 ctx->offset_mask = (uint32_t)((1ULL << offset_bits) - 1);
256 ctx->max_epoch = (uint32_t)(1ULL << (32 - offset_bits));
257
258 // memory_block stays NULL on the static-init path so zxc_cctx_free does
259 // not try to free the caller's workspace. Sub-buffer pointers carry the
260 // partition; ownership is implicit (the caller owns @p workspace).
261 uint8_t* const mem = (uint8_t*)workspace;
262
263 // Dictionary concat scratch (both modes); init owns dict_size now so callers
264 // no longer assign ctx->dict_size after init.
265 ctx->dict_size = dict_size;
266 if (dict_size > 0) {
267 ctx->dict_buffer = mem + layout.off_dict;
268 ctx->dict_buffer_cap = layout.sz_dict;
269 ctx->dict_huf = (zxc_dict_huf_state_t*)(void*)(mem + layout.off_dict_huf);
270 }
271
272 if (mode == 0) {
273 ctx->work_buf = mem + layout.off_work;
274 ctx->work_buf_cap = chunk_size + ZXC_DECOMPRESS_TAIL_PAD;
275 ctx->lit_buffer = mem + layout.off_lit_dctx;
276 ctx->lit_buffer_cap = chunk_size + ZXC_PAD_SIZE;
277 if (layout.sz_pivco_dctx) {
278 ctx->tok_buffer = mem + layout.off_tok_dctx;
279 ctx->tok_buffer_cap = layout.sz_tok_dctx;
280 ctx->pivco_scratch = mem + layout.off_pivco_dctx;
281 ctx->pivco_scratch_cap = layout.sz_pivco_dctx;
282 }
283 return ZXC_OK;
284 }
285
286 ctx->hash_table = (uint32_t*)(mem + layout.off_hash_pos);
287 ctx->hash_tags = mem + layout.off_hash_tags;
288 ctx->chain_table = (uint16_t*)(mem + layout.off_chain);
289 ctx->buf_sequences = (uint32_t*)(mem + layout.off_seq_union);
290 ctx->buf_offsets = (uint16_t*)(mem + layout.off_seq_union);
291 ctx->buf_tokens = mem + layout.off_seq_union + layout.max_seq * sizeof(uint16_t);
292 ctx->buf_split = ctx->buf_tokens + layout.max_seq;
293 ctx->buf_split_hist = (zxc_spl_match_split_hist_t*)(void*)(mem + layout.off_split_hist);
294 ctx->buf_extras = mem + layout.off_extras;
295 ctx->literals = mem + layout.off_lit_cctx;
296 if (layout.sz_opt) {
297 ctx->opt_scratch = mem + layout.off_opt;
298 ctx->opt_scratch_cap = layout.sz_opt;
299 }
300
301 ctx->compression_level = level;
302 ctx->epoch = 1;
303
304 ZXC_MEMSET(ctx->hash_table, 0, layout.sz_hash_pos);
305 ZXC_MEMSET(ctx->hash_tags, 0, layout.sz_hash_tags);
306 return ZXC_OK;
307}
308
319int zxc_cctx_init(zxc_cctx_t* RESTRICT ctx, const size_t chunk_size, const int mode,
320 const int level, const int checksum_enabled, const size_t dict_size) {
321 // Cleared first, so that zxc_cctx_free is safe after a failure.
322 ZXC_MEMSET(ctx, 0, sizeof(*ctx));
323 if (UNLIKELY(chunk_size == 0)) return ZXC_ERROR_NULL_INPUT;
324 // Heap contexts defer the decode-side entropy scratch to the first entropy
325 // section; static workspaces must have it already, they may never allocate.
326 const int defer_entropy = (mode == 0);
327 const size_t total =
328 compute_cctx_layout(chunk_size, mode, level, dict_size, defer_entropy).total;
329 if (UNLIKELY(total == 0)) return ZXC_ERROR_NULL_INPUT;
330
331 uint8_t* const mem = (uint8_t*)ZXC_ALIGNED_MALLOC(total, ZXC_CACHE_LINE_SIZE);
332 if (UNLIKELY(!mem)) return ZXC_ERROR_MEMORY;
333
334 const int rc = zxc_cctx_init_in_workspace(ctx, mem, total, chunk_size, mode, level,
335 checksum_enabled, dict_size, defer_entropy);
336 if (UNLIKELY(rc != ZXC_OK)) {
337 // LCOV_EXCL_START
338 ZXC_ALIGNED_FREE(mem);
339 return rc;
340 // LCOV_EXCL_STOP
341 }
342 // Library-owned buffer: record the allocation so zxc_cctx_free frees it.
343 ctx->memory_block = mem;
344 return ZXC_OK;
345}
346
356 if (LIKELY(ctx->pivco_scratch)) return ZXC_OK;
357
358 // Sized for the block the context was carved for, not chunk_size: a reader
359 // over frames of several block sizes lowers chunk_size per block.
360 size_t sz_tok = 0;
361 size_t sz_pivco = 0;
363 const size_t total = ZXC_ALIGN_CL(sz_tok) + ZXC_ALIGN_CL(sz_pivco);
364
365 uint8_t* const mem = (uint8_t*)ZXC_ALIGNED_MALLOC(total, ZXC_CACHE_LINE_SIZE);
366 if (UNLIKELY(!mem)) return ZXC_ERROR_MEMORY; // LCOV_EXCL_LINE
367
368 ctx->entropy_block = mem;
369 ctx->tok_buffer = mem;
370 ctx->tok_buffer_cap = sz_tok;
371 ctx->pivco_scratch = mem + ZXC_ALIGN_CL(sz_tok);
372 ctx->pivco_scratch_cap = sz_pivco;
373 return ZXC_OK;
374}
375
383 if (ctx->memory_block) {
385 ctx->memory_block = NULL;
386 }
387 if (ctx->entropy_block) {
389 ctx->entropy_block = NULL;
390 }
391
392 ctx->lit_buffer = NULL;
393 ctx->hash_table = NULL;
394 ctx->hash_tags = NULL;
395 ctx->chain_table = NULL;
396 ctx->buf_sequences = NULL;
397 ctx->buf_tokens = NULL;
398 ctx->buf_offsets = NULL;
399 ctx->buf_extras = NULL;
400 ctx->buf_split = NULL;
401 ctx->buf_split_hist = NULL;
402 ctx->literals = NULL;
403 ctx->work_buf = NULL;
404 ctx->tok_buffer = NULL;
405 ctx->pivco_scratch = NULL;
406 ctx->opt_scratch = NULL;
407 ctx->dict_buffer = NULL;
408 ctx->dict_huf = NULL;
409
410 ctx->epoch = 0;
411 ctx->lit_buffer_cap = 0;
412 ctx->work_buf_cap = 0;
413 ctx->tok_buffer_cap = 0;
414 ctx->pivco_scratch_cap = 0;
415 ctx->opt_scratch_cap = 0;
416 ctx->dict_buffer_cap = 0;
417 ctx->dict_size = 0;
418 ctx->dict_huf_tree_ok = 0;
419 ctx->lit_freq_acc = NULL;
420}
421
435int zxc_cctx_attach_dict_huf(zxc_cctx_t* RESTRICT ctx, const uint8_t* RESTRICT lengths) {
436 if (UNLIKELY(!ctx)) return ZXC_ERROR_NULL_INPUT;
437 ctx->dict_huf_tree_ok = 0;
438 if (!lengths) return ZXC_OK;
439
440 // Empty (all-zero) table from a low-entropy corpus: treat it as "no shared table".
441 int empty = 1;
442 for (size_t i = 0; i < ZXC_HUF_TABLE_SIZE; i++) {
443 if (lengths[i]) {
444 empty = 0;
445 break;
446 }
447 }
448 if (UNLIKELY(empty || !ctx->dict_huf)) return ZXC_OK;
449
450 // Tree-at-attach: built once, reused by every block.
451 const int rc = zxc_huf_dict_tree_build(lengths, &ctx->dict_huf->tree, ctx->dict_huf->codes,
452 ctx->dict_huf->code_len);
453 if (UNLIKELY(rc != ZXC_OK)) return rc;
454 ctx->dict_huf_tree_ok = 1;
455 return ZXC_OK;
456}
457
458// ============================================================================
459// HEADER I/O
460// ============================================================================
461
468int zxc_write_file_header(uint8_t* RESTRICT dst, const size_t dst_capacity, const size_t chunk_size,
469 const int has_checksum, const int has_dict, const uint32_t dict_id,
470 const int has_seek) {
471 if (UNLIKELY(dst_capacity < ZXC_FILE_HEADER_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
472
475
476 // Block size stored as log2 exponent (e.g. 18 = 256 KB)
477 dst[5] = (uint8_t)zxc_log2_u32((uint32_t)chunk_size);
478
479 uint8_t flags = has_checksum ? (ZXC_FILE_FLAG_HAS_CHECKSUM | ZXC_CHECKSUM_RAPIDHASH) : 0;
480 if (has_dict) flags |= ZXC_FILE_FLAG_HAS_DICTIONARY;
481 if (has_seek) flags |= ZXC_FILE_FLAG_HAS_SEEK_TABLE;
482 dst[6] = flags;
483
484 // Bytes 7-13: Reserved / Dictionary ID
485 ZXC_MEMSET(dst + 7, 0, 7);
486 if (has_dict) zxc_store_le32(dst + 7, dict_id);
487
488 // Bytes 14-15: Header Checksum (16-bit)
490
492}
493
499int zxc_read_file_header(const uint8_t* RESTRICT src, const size_t src_size,
500 size_t* RESTRICT out_block_size, int* RESTRICT out_has_checksum,
501 int* RESTRICT out_has_dict, uint32_t* RESTRICT out_dict_id,
502 int* RESTRICT out_has_seek) {
503 if (UNLIKELY(src_size < ZXC_FILE_HEADER_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
504 if (UNLIKELY(zxc_le32(src) != ZXC_MAGIC_WORD)) return ZXC_ERROR_BAD_MAGIC;
505 if (UNLIKELY(src[4] != ZXC_FILE_FORMAT_VERSION)) return ZXC_ERROR_BAD_VERSION;
506
507 uint8_t temp[ZXC_FILE_HEADER_SIZE];
508 ZXC_MEMCPY(temp, src, ZXC_FILE_HEADER_SIZE);
509 // Zero out checksum bytes (14-15) before hash check
510 temp[14] = 0;
511 temp[15] = 0;
512 // Header checksum (integrity), then the checksum-algorithm id in flags bits 0-3
513 // (only 0 = RapidHash is defined). It is checked first via short-circuit.
514 if (UNLIKELY(zxc_le16(src + 14) != zxc_hash16(temp) ||
517 // Reserved: flag bit 4, bytes 7-13 minus the dict_id (7-10).
518 if (UNLIKELY(src[6] & ZXC_FILE_FLAG_RESERVED)) return ZXC_ERROR_BAD_HEADER;
519 uint8_t rsv = 0;
520 const int has_dict = (src[6] & ZXC_FILE_FLAG_HAS_DICTIONARY) ? 1 : 0;
521 for (size_t i = has_dict ? 11 : 7; i < 14; i++) rsv |= src[i];
522 if (UNLIKELY(rsv != 0)) return ZXC_ERROR_BAD_HEADER;
523
524 if (out_block_size) {
525 const uint8_t code = src[5];
526 if (UNLIKELY(code < ZXC_BLOCK_SIZE_MIN_LOG2 || code > ZXC_BLOCK_SIZE_MAX_LOG2))
528 // Exponent encoding: block_size = 2^code (4 KB - 2 MB)
529 *out_block_size = (size_t)1U << code;
530 }
531 if (out_has_checksum) *out_has_checksum = (src[6] & ZXC_FILE_FLAG_HAS_CHECKSUM) ? 1 : 0;
532 // The flag alone tells whether a dictionary is needed: its id may be 0.
533 if (out_has_dict) *out_has_dict = has_dict;
534 if (out_dict_id) *out_dict_id = has_dict ? zxc_le32(src + 7) : 0;
535 if (out_has_seek) *out_has_seek = (src[6] & ZXC_FILE_FLAG_HAS_SEEK_TABLE) ? 1 : 0;
536
537 return ZXC_OK;
538}
539
541static int zxc_scan_read(const zxc_scan_src_t* src, const uint64_t off, void* dst,
542 const size_t len) {
543 if (UNLIKELY(off > src->size || (uint64_t)len > src->size - off))
545 if (src->read_at) return src->read_at(src, off, dst, len);
546 ZXC_MEMCPY(dst, src->data + off, len);
547 return ZXC_OK;
548}
549
550int zxc_container_next(const zxc_scan_src_t* src, const uint64_t pos) {
551 if (pos == src->size) return 0;
552 uint8_t m[sizeof(uint32_t)];
553 if (src->size - pos >= sizeof(m)) {
554 const int rc = zxc_scan_read(src, pos, m, sizeof(m));
555 if (UNLIKELY(rc != ZXC_OK)) return rc;
556 if (zxc_magic_prefix_ok(m, sizeof(m))) return 1;
557 }
559}
560
561int zxc_scan_frame(const zxc_scan_src_t* src, const uint64_t end, uint64_t* start,
562 zxc_frame_info_t* info, size_t* footer_len, int* has_dict) {
563 uint8_t h[ZXC_FILE_HEADER_SIZE];
564 int rc;
565 // Too short for a frame: what is left starts the input, its header speaks first.
566 if (UNLIKELY(end < ZXC_FRAME_MIN_SIZE)) {
567 const size_t n = end < sizeof(h) ? (size_t)end : sizeof(h);
568 rc = zxc_scan_read(src, 0, h, n);
569 return rc != ZXC_OK ? rc : zxc_short_input_verdict(h, n);
570 }
571 uint8_t tail[ZXC_FOOTER_MAX_SIZE_WITH_DIGEST]; // end > sizeof(tail)
572 rc = zxc_scan_read(src, end - sizeof(tail), tail, sizeof(tail));
573 if (UNLIKELY(rc != ZXC_OK)) return rc;
574 uint64_t dsize = 0;
575 uint64_t frame = 0;
576 size_t sizes = 0;
577 rc = zxc_parse_file_footer(tail + sizeof(tail), sizeof(tail), &dsize, &frame, &sizes);
578 if (UNLIKELY(rc != ZXC_OK)) return rc;
579 if (UNLIKELY(frame < ZXC_FRAME_MIN_SIZE || frame > end)) return ZXC_ERROR_CORRUPT_DATA;
580
581 const uint64_t at = end - frame;
582 rc = zxc_scan_read(src, at, h, sizeof(h));
583 if (UNLIKELY(rc != ZXC_OK)) return rc;
584 const size_t tl = zxc_frame_tail_len(frame);
585 rc = zxc_read_frame_info(h, tail + sizeof(tail) - tl, tl, frame, info, footer_len, has_dict);
586 // Past the first frame, a wrong magic word is a broken container.
587 if (UNLIKELY(rc == ZXC_ERROR_BAD_MAGIC && at != 0)) return ZXC_ERROR_CORRUPT_DATA;
588 if (UNLIKELY(rc != ZXC_OK)) return rc;
589 *start = at;
590 return ZXC_OK;
591}
592
593int zxc_scan_whole_frame(const zxc_scan_src_t* src, zxc_frame_info_t* info, size_t* footer_len) {
594 uint8_t h[ZXC_FILE_HEADER_SIZE];
595 const size_t n = src->size < sizeof(h) ? (size_t)src->size : sizeof(h);
596 int rc = zxc_scan_read(src, 0, h, n);
597 if (UNLIKELY(rc != ZXC_OK)) return rc;
598 rc = zxc_short_input_verdict(h, n); // the header speaks first
599 if (UNLIKELY(rc != ZXC_ERROR_SRC_TOO_SMALL || src->size < ZXC_FRAME_MIN_SIZE)) return rc;
600 uint64_t start = 0;
601 rc = zxc_scan_frame(src, src->size, &start, info, footer_len, NULL);
602 return rc == ZXC_OK && start != 0 ? ZXC_ERROR_CORRUPT_DATA : rc;
603}
604
605int zxc_scan_container(const zxc_scan_src_t* src, const size_t req_chunk,
606 zxc_container_info_t* info) {
607 ZXC_MEMSET(info, 0, sizeof(*info));
608 // The first header speaks first, as for a single frame: junk is a bad magic word.
609 uint8_t h[ZXC_FILE_HEADER_SIZE];
610 const size_t n = src->size < sizeof(h) ? (size_t)src->size : sizeof(h);
611 size_t chunk = 0;
612 int hrc = zxc_scan_read(src, 0, h, n);
613 if (hrc == ZXC_OK) hrc = zxc_read_file_header(h, n, &chunk, NULL, NULL, NULL, NULL);
614 if (UNLIKELY(hrc != ZXC_OK)) return hrc;
615
616 uint64_t end = src->size;
617 do {
619 uint64_t start = 0;
620 int has_dict = 0;
621 const int rc = zxc_scan_frame(src, end, &start, &fi, NULL, &has_dict);
622 if (UNLIKELY(rc != ZXC_OK)) return rc;
623 if (UNLIKELY(req_chunk && fi.block_size != req_chunk)) return ZXC_ERROR_BAD_BLOCK_SIZE;
624 if (UNLIKELY(fi.decompressed_size > UINT64_MAX - info->dsize))
626 info->dsize += fi.decompressed_size;
627 info->frames++;
628 info->uses_dict |= has_dict;
629 end = start;
630 } while (end > 0);
631 return ZXC_OK;
632}
633
640int zxc_read_frame_info(const uint8_t* header, const uint8_t* tail, const size_t tail_len,
641 const uint64_t total, zxc_frame_info_t* info, size_t* footer_len,
642 int* has_dict) {
643 size_t chunk = 0;
644 int cs = 0;
645 int seek = 0;
646 int hd = 0;
647 uint32_t did = 0;
648 const int hrc =
649 zxc_read_file_header(header, ZXC_FILE_HEADER_SIZE, &chunk, &cs, &hd, &did, &seek);
650 if (UNLIKELY(hrc != ZXC_OK)) return hrc;
651
652 uint64_t stored = 0;
653 uint64_t frame = 0;
654 size_t sizes = 0;
655 const int frc = zxc_parse_file_footer(tail + tail_len, tail_len, &stored, &frame, &sizes);
656 if (UNLIKELY(frc != ZXC_OK)) return frc;
657 const size_t flen = sizes + (cs ? (size_t)ZXC_FILE_DIGEST_SIZE : 0U);
658 // All the frame's bytes are there: a footer longer than they allow is forged.
659 if (UNLIKELY(flen > tail_len)) return ZXC_ERROR_CORRUPT_DATA;
660 if (UNLIKELY(frame != total || !zxc_footer_dsize_plausible(stored, chunk, total)))
662
663 ZXC_MEMSET(info, 0, sizeof(*info)); // padding too: zxc_frame_info_copy() hands it out
664 info->decompressed_size = stored;
665 info->compressed_size = frame;
666 info->digest = cs ? zxc_le64(tail + tail_len - flen) : 0;
667 info->block_size = chunk;
668 info->dict_id = did;
669 info->format_version = header[4];
670 info->has_checksum = (uint8_t)cs;
671 info->has_seek_table = (uint8_t)seek;
672 if (footer_len) *footer_len = flen;
673 if (has_dict) *has_dict = hd;
674 return ZXC_OK;
675}
676
680int zxc_write_block_header(uint8_t* RESTRICT dst, const size_t dst_capacity,
681 const zxc_block_header_t* RESTRICT bh) {
682 if (UNLIKELY(dst_capacity < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
683
684 dst[0] = bh->block_type;
685 dst[1] = 0; // Flags not used currently
686 dst[2] = 0; // Reserved
687 zxc_store_le32(dst + 3, bh->comp_size);
688 dst[7] = 0; // Zero before hashing
689 dst[7] = zxc_hash8(dst); // Checksum at the end
690
692}
693
699int zxc_read_block_header(const uint8_t* RESTRICT src, const size_t src_size,
700 zxc_block_header_t* RESTRICT bh) {
701 if (UNLIKELY(src_size < ZXC_BLOCK_HEADER_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
702
703 if (UNLIKELY(!zxc_block_header_ok(src))) return ZXC_ERROR_BAD_HEADER;
704
705 bh->block_type = src[0];
706 bh->block_flags = src[1];
707 bh->reserved = src[2];
708 bh->comp_size = zxc_le32(src + 3);
709 bh->header_checksum = src[7];
710
711 return ZXC_OK;
712}
713
714// =========================================================================
715// SEEK TABLE WRITER (a frame block; zxc_seekable.c is the random-access reader)
716// =========================================================================
717
724size_t zxc_seek_table_size(const uint64_t num_blocks) {
725 if (UNLIKELY(num_blocks > UINT64_MAX / ZXC_SEEK_ANCHOR_SIZE)) return 0;
726 const uint64_t bytes = zxc_seek_table_bytes(num_blocks);
727 if (UNLIKELY(bytes > SIZE_MAX - ZXC_BLOCK_HEADER_SIZE)) return 0;
728 return ZXC_BLOCK_HEADER_SIZE + (size_t)bytes;
729}
730
731int zxc_seek_table_header(uint8_t* dst, const size_t dst_capacity, const uint64_t num_blocks) {
732 // The field keeps the table size modulo 2^32; readers derive the count from the footer.
733 const zxc_block_header_t bh = {
734 .block_type = ZXC_BLOCK_SEK,
735 .block_flags = 0,
736 .reserved = 0,
737 .comp_size = zxc_seek_size_field(zxc_seek_table_bytes(num_blocks))};
738 return zxc_write_block_header(dst, dst_capacity, &bh);
739}
740
741int zxc_check_eof_header(const uint8_t* hdr) {
742 const zxc_block_header_t eof = {
743 .block_type = ZXC_BLOCK_EOF, .block_flags = 0, .reserved = 0, .comp_size = 0};
744 uint8_t want[ZXC_BLOCK_HEADER_SIZE];
745 if (UNLIKELY(zxc_write_block_header(want, sizeof(want), &eof) < 0))
746 return ZXC_ERROR_BAD_HEADER; // LCOV_EXCL_LINE
747 return memcmp(hdr, want, sizeof(want)) == 0 ? ZXC_OK : ZXC_ERROR_BAD_HEADER;
748}
749
750int zxc_check_seek_header(const uint8_t* hdr, const size_t avail, const uint64_t total_out,
751 const size_t block_size, uint64_t* sek_bytes) {
752 const uint64_t n = zxc_seek_block_count(total_out, block_size);
753 uint8_t want[ZXC_BLOCK_HEADER_SIZE];
754 if (UNLIKELY(zxc_seek_table_header(want, sizeof(want), n) < 0))
755 return ZXC_ERROR_CORRUPT_DATA; // LCOV_EXCL_LINE
756 const size_t m = avail < sizeof(want) ? avail : sizeof(want);
757 if (memcmp(hdr, want, m) != 0) return ZXC_ERROR_CORRUPT_DATA;
758 if (avail < sizeof(want)) return ZXC_ERROR_SRC_TOO_SMALL;
759 if (sek_bytes) *sek_bytes = zxc_seek_table_bytes(n);
760 return ZXC_OK;
761}
762
763size_t zxc_seek_write_group(uint8_t* RESTRICT dst, uint64_t* RESTRICT anchor,
764 const uint32_t* RESTRICT sizes, const uint32_t cnt) {
765 zxc_store_le64(dst, *anchor);
766 uint8_t* p = dst + ZXC_SEEK_ANCHOR_SIZE;
767 for (uint32_t k = 0; k < cnt; k++, p += ZXC_SEEK_SIZE_ENTRY) {
768 zxc_store_le32(p, sizes[k]);
769 *anchor += sizes[k];
770 }
771 return (size_t)(p - dst);
772}
773
779int64_t zxc_write_seek_table(uint8_t* dst, const size_t dst_capacity, const uint32_t* comp_sizes,
780 const uint64_t num_blocks) {
781 const size_t total = zxc_seek_table_size(num_blocks);
782 if (UNLIKELY(total == 0)) return ZXC_ERROR_OVERFLOW;
783 if (UNLIKELY(dst_capacity < total)) return ZXC_ERROR_DST_TOO_SMALL;
784 if (UNLIKELY(!dst || !comp_sizes)) return ZXC_ERROR_NULL_INPUT;
785
786 const int hdr_res = zxc_seek_table_header(dst, dst_capacity, num_blocks);
787 if (UNLIKELY(hdr_res < 0)) return hdr_res;
788 uint8_t* p = dst + hdr_res;
789
790 uint64_t anchor = ZXC_FILE_HEADER_SIZE;
791 for (uint64_t i = 0; i < num_blocks; i += ZXC_SEEK_GROUP)
792 p += zxc_seek_write_group(p, &anchor, comp_sizes + i,
793 zxc_seek_group_len(num_blocks, i / ZXC_SEEK_GROUP));
794
795 return (int64_t)(p - dst);
796}
797
799static void zxc_store_le_n(uint8_t* dst, uint64_t v, const size_t n) {
800 for (size_t i = 0; i < n; i++, v >>= 8) dst[i] = (uint8_t)v;
801}
802
804static uint64_t zxc_load_le_n(const uint8_t* src, const size_t n) {
805 uint64_t v = 0;
806 for (size_t i = n; i > 0; i--) v = (v << 8) | src[i - 1];
807 return v;
808}
809
811static void zxc_encode_footer(uint8_t* dst, const zxc_footer_layout_t* l, const uint64_t src_size,
812 const uint64_t digest) {
813 if (l->skip) zxc_store_le64(dst, digest);
814 uint8_t* p = dst + l->skip;
815 zxc_store_le_n(p, src_size, l->nd);
816 p += l->nd;
818 p[l->nf] = (uint8_t)((l->nd - 1) | (l->nf - 1) << 4);
819}
820
825int zxc_write_file_footer(uint8_t* RESTRICT dst, const size_t dst_capacity, const uint64_t prefix,
826 const uint64_t src_size, const uint64_t digest,
827 const int checksum_enabled) {
828 const zxc_footer_layout_t l = zxc_footer_layout(prefix, src_size, checksum_enabled);
829 if (UNLIKELY(dst_capacity < l.len)) return ZXC_ERROR_DST_TOO_SMALL;
830 zxc_encode_footer(dst, &l, src_size, digest);
831 return (int)l.len;
832}
833
840int zxc_check_file_footer(const uint8_t* footer, const size_t avail, const zxc_footer_layout_t* l,
841 const uint64_t src_size, uint64_t* digest) {
843 zxc_encode_footer(want, l, src_size, 0);
844 const size_t n = avail < l->len ? avail : l->len;
845 if (n > l->skip && memcmp(footer + l->skip, want + l->skip, n - l->skip) != 0)
847 if (avail < l->len) return ZXC_ERROR_SRC_TOO_SMALL;
848 if (digest) *digest = l->skip ? zxc_le64(footer) : 0;
849 return ZXC_OK;
850}
851
858int zxc_parse_file_footer(const uint8_t* end, const size_t avail, uint64_t* src_size,
859 uint64_t* compressed_size, size_t* sizes_len) {
860 if (UNLIKELY(avail < ZXC_FILE_FOOTER_MIN_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
861 const uint8_t L = end[-1];
862 if (UNLIKELY(L & 0x88U)) return ZXC_ERROR_CORRUPT_DATA;
863 const size_t nd = (size_t)(L & 0x07U) + 1;
864 const size_t nf = (size_t)(L >> 4) + 1;
865 const size_t need = nd + nf + 1;
866 if (UNLIKELY(avail < need)) return ZXC_ERROR_SRC_TOO_SMALL;
867 const uint64_t d = zxc_load_le_n(end - need, nd);
868 const uint64_t f = zxc_load_le_n(end - 1 - nf, nf);
869 // Minimal lengths: d on exactly nd bytes; f too, and nf the fewest that hold
870 // the total, which one byte less would not (f counts its own bytes).
871 if (UNLIKELY(zxc_uint_bytes(d) != nd || zxc_uint_bytes(f) != nf ||
872 (nf > 1 && zxc_uint_bytes(f - 1) < nf)))
874 *src_size = d;
875 *compressed_size = f;
876 *sizes_len = need;
877 return ZXC_OK;
878}
879
886static ZXC_ALWAYS_INLINE void zxc_write_gnr_header(uint8_t* RESTRICT dst,
887 const zxc_gnr_header_t* RESTRICT gh) {
888 zxc_store_le32(dst, gh->n_sequences);
889 zxc_store_le32(dst + 4, gh->n_literals);
890
891 dst[8] = gh->enc_lit;
892 dst[9] = gh->enc_tok;
893 dst[10] = gh->enc_mlen;
894 dst[11] = gh->enc_off;
895}
896
903static ZXC_ALWAYS_INLINE void zxc_read_gnr_header(const uint8_t* RESTRICT src,
904 zxc_gnr_header_t* RESTRICT gh) {
905 gh->n_sequences = zxc_le32(src);
906 gh->n_literals = zxc_le32(src + 4);
907 gh->enc_lit = src[8];
908 gh->enc_tok = src[9];
909 gh->enc_mlen = src[10];
910 gh->enc_off = src[11];
911}
912
919static ZXC_ALWAYS_INLINE size_t zxc_spl_desc_size(const uint8_t enc_lit, const uint8_t enc_tok) {
920 return ((enc_lit != ZXC_SECTION_ENCODING_RAW) ? sizeof(uint32_t) : 0) +
921 ((enc_tok == ZXC_SECTION_ENCODING_HUFFMAN) ? sizeof(uint32_t) : 0);
922}
923
933int zxc_write_spl_header_and_desc(uint8_t* RESTRICT dst, const size_t rem,
934 const zxc_gnr_header_t* RESTRICT gh, const uint32_t lit_comp,
935 const uint32_t tok_comp) {
936 const size_t desc_sz = zxc_spl_desc_size(gh->enc_lit, gh->enc_tok);
937 const size_t needed = ZXC_SPL_HEADER_BINARY_SIZE + desc_sz;
938
939 if (UNLIKELY(rem < needed)) return ZXC_ERROR_DST_TOO_SMALL;
940
941 zxc_write_gnr_header(dst, gh);
942 uint8_t* p = dst + ZXC_SPL_HEADER_BINARY_SIZE;
943
944 if (gh->enc_lit != ZXC_SECTION_ENCODING_RAW) {
945 zxc_store_le32(p, lit_comp);
946 p += sizeof(uint32_t);
947 }
948 if (gh->enc_tok == ZXC_SECTION_ENCODING_HUFFMAN) {
949 zxc_store_le32(p, tok_comp);
950 }
951
952 return (int)needed;
953}
954
958int zxc_read_spl_header_and_desc(const uint8_t* RESTRICT src, const size_t len,
959 zxc_gnr_header_t* RESTRICT gh, uint32_t* RESTRICT lit_comp,
960 uint32_t* RESTRICT tok_comp) {
961 if (UNLIKELY(len < ZXC_SPL_HEADER_BINARY_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
962
963 zxc_read_gnr_header(src, gh);
964
965 const size_t desc_sz = zxc_spl_desc_size(gh->enc_lit, gh->enc_tok);
966 const size_t needed = ZXC_SPL_HEADER_BINARY_SIZE + desc_sz;
967 if (UNLIKELY(len < needed)) return ZXC_ERROR_SRC_TOO_SMALL;
968
969 const uint8_t* p = src + ZXC_SPL_HEADER_BINARY_SIZE;
970
971 if (gh->enc_lit != ZXC_SECTION_ENCODING_RAW) {
972 *lit_comp = zxc_le32(p);
973 p += sizeof(uint32_t);
974 } else {
975 *lit_comp = gh->n_literals;
976 }
977 *tok_comp = (gh->enc_tok == ZXC_SECTION_ENCODING_HUFFMAN) ? zxc_le32(p) : gh->n_sequences;
978
979 return (int)needed;
980}
981
990int zxc_write_pak_header(uint8_t* RESTRICT dst, const size_t rem,
991 const zxc_gnr_header_t* RESTRICT gh) {
992 if (UNLIKELY(rem < ZXC_PAK_HEADER_BINARY_SIZE)) return ZXC_ERROR_DST_TOO_SMALL;
993
994 zxc_write_gnr_header(dst, gh);
996}
997
1001int zxc_read_pak_header(const uint8_t* RESTRICT src, const size_t len,
1002 zxc_gnr_header_t* RESTRICT gh) {
1003 if (UNLIKELY(len < ZXC_PAK_HEADER_BINARY_SIZE)) return ZXC_ERROR_SRC_TOO_SMALL;
1004
1005 zxc_read_gnr_header(src, gh);
1006 return ZXC_OK;
1007}
1008
1009// ============================================================================
1010// COMPRESS BOUND CALCULATION
1011// ============================================================================
1022size_t zxc_compress_bound(const size_t input_size) {
1023 // n <= 2^52 even for a 64-bit size_t, so the overhead sum fits a uint64.
1024 uint64_t n = (uint64_t)input_size / ZXC_BLOCK_SIZE_MIN + (input_size % ZXC_BLOCK_SIZE_MIN != 0);
1025 if (n == 0) n = 1;
1026 const uint64_t overhead =
1029 ZXC_BLOCK_HEADER_SIZE + /* EOF block */
1030 ZXC_BLOCK_HEADER_SIZE + /* SEK block header (seekable) */
1031 zxc_seek_table_bytes(n) + /* SEK groups (seekable) */
1032 ZXC_FOOTER_MAX_SIZE_WITH_DIGEST; /* optional digest + footer */
1033 // The bound is a buffer size: input + overhead must fit a size_t.
1034 if (UNLIKELY(overhead > (uint64_t)(SIZE_MAX - input_size))) return 0;
1035 return input_size + (size_t)overhead;
1036}
1037
1041size_t zxc_compress_block_bound(const size_t input_size) {
1042 // Mirrors the Block API contract: outside [1, ZXC_BLOCK_SIZE_MAX] the call
1043 // would fail anyway, so the bound is undefined and 0 says "unusable". The cap
1044 // also makes the addition below trivially overflow-free.
1045 if (UNLIKELY(input_size == 0 || input_size > ZXC_BLOCK_SIZE_MAX)) return 0;
1046 // Outer block header + payload (worst case: incompressible, raw bytes)
1047 // + inner format overhead + optional checksum.
1049}
1050
1062size_t zxc_decompress_block_bound(const size_t uncompressed_size) {
1063 if (UNLIKELY(uncompressed_size > ZXC_BLOCK_SIZE_MAX)) return 0;
1064 return uncompressed_size + ZXC_DECOMPRESS_TAIL_PAD;
1065}
1066
1081size_t zxc_estimate_cctx_size(const size_t src_size, const int level) {
1082 if (UNLIKELY(src_size == 0)) return 0;
1083 const size_t chunk_size = zxc_block_size_ceil(src_size);
1084 return zxc_cctx_compute_workspace_size(chunk_size, 1, level, 0);
1085}
1086
1087// ============================================================================
1088// ERROR CODE UTILITIES
1089// ============================================================================
1090
1094const char* zxc_error_name(const int code) {
1095 switch ((zxc_error_t)code) {
1096 case ZXC_OK:
1097 return "ZXC_OK";
1098 case ZXC_ERROR_MEMORY:
1099 return "ZXC_ERROR_MEMORY";
1101 return "ZXC_ERROR_DST_TOO_SMALL";
1103 return "ZXC_ERROR_SRC_TOO_SMALL";
1105 return "ZXC_ERROR_BAD_MAGIC";
1107 return "ZXC_ERROR_BAD_VERSION";
1109 return "ZXC_ERROR_BAD_HEADER";
1111 return "ZXC_ERROR_BAD_CHECKSUM";
1113 return "ZXC_ERROR_CORRUPT_DATA";
1115 return "ZXC_ERROR_BAD_OFFSET";
1116 case ZXC_ERROR_OVERFLOW:
1117 return "ZXC_ERROR_OVERFLOW";
1118 case ZXC_ERROR_IO:
1119 return "ZXC_ERROR_IO";
1121 return "ZXC_ERROR_NULL_INPUT";
1123 return "ZXC_ERROR_BAD_BLOCK_TYPE";
1125 return "ZXC_ERROR_BAD_BLOCK_SIZE";
1127 return "ZXC_ERROR_DICT_REQUIRED";
1129 return "ZXC_ERROR_DICT_MISMATCH";
1131 return "ZXC_ERROR_DICT_TOO_LARGE";
1133 return "ZXC_ERROR_BAD_LEVEL";
1135 return "ZXC_ERROR_DICT_UNSUPPORTED";
1137 return "ZXC_ERROR_BAD_PARAM";
1138 default:
1139 return "ZXC_UNKNOWN_ERROR";
1140 }
1141}
1142
1143// ============================================================================
1144// LIBRARY INFORMATION
1145// ============================================================================
1146
1155
1161int zxc_max_level(void) { return ZXC_LEVEL_ULTRA; }
1162
1169
1176const char* zxc_version_string(void) { return ZXC_LIB_VERSION_STR; }
1177
1178unsigned zxc_version_number(void) { return ZXC_VERSION_NUMBER; }
1179
1180const char* zxc_version_codename(void) { return ZXC_VERSION_CODENAME; }
size_t zxc_estimate_cctx_size(const size_t src_size, const int level)
Estimates the total buffer bytes allocated inside a cctx for a block.
size_t zxc_compress_block_bound(const size_t input_size)
Returns the maximum compressed size for a single block (no file framing).
size_t zxc_decompress_block_bound(const size_t uncompressed_size)
Returns the minimum dst_capacity required by zxc_decompress_block().
#define ZXC_BLOCK_SIZE_MAX_LOG2
log2(ZXC_BLOCK_SIZE_MAX) - exponent code for maximum block size.
#define ZXC_BLOCK_SIZE_MAX
Maximum allowed block size (2 MB = 2^21).
#define ZXC_BLOCK_SIZE_MIN
Minimum allowed block size (4 KB = 2^12).
size_t zxc_frame_info_size(void)
Returns sizeof(zxc_frame_info_t) for ABI-safe mirroring.
Definition zxc_common.c:31
size_t zxc_compress_bound(const size_t input_size)
Returns the maximum compressed size for a given input size.
#define ZXC_HUF_TABLE_SIZE
Size of a packed literal Huffman code-lengths table (256 symbols, 4 bits each): the shared table in a...
const char * zxc_error_name(const int code)
Returns a human-readable string for the given error code.
zxc_error_t
Error codes returned by ZXC library functions.
Definition zxc_error.h:37
@ 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_BAD_BLOCK_TYPE
Unknown or unexpected block type.
Definition zxc_error.h:65
@ ZXC_ERROR_OVERFLOW
Buffer overflow detected during processing.
Definition zxc_error.h:58
@ ZXC_ERROR_BAD_OFFSET
Invalid match offset during decompression.
Definition zxc_error.h:57
@ ZXC_ERROR_CORRUPT_DATA
Corrupted compressed data.
Definition zxc_error.h:56
@ ZXC_ERROR_NULL_INPUT
Required input pointer is NULL.
Definition zxc_error.h:62
@ ZXC_ERROR_IO
Read/write/seek failure on file.
Definition zxc_error.h:61
@ ZXC_ERROR_DICT_MISMATCH
Provided dictionary ID does not match the file header.
Definition zxc_error.h:70
@ 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_DICT_REQUIRED
File requires a dictionary but none was provided.
Definition zxc_error.h:69
@ ZXC_ERROR_DICT_UNSUPPORTED
Dictionary not supported by this context's workspace, or library built without dictionary support.
Definition zxc_error.h:75
@ ZXC_ERROR_BAD_CHECKSUM
A block's decoded bytes fail its checksum, or the archive digest mismatches.
Definition zxc_error.h:51
@ ZXC_ERROR_BAD_PARAM
Unknown parameter, or value out of its bounds (zxc_cctx_set_param(), zxc_dctx_set_param()).
Definition zxc_error.h:77
@ ZXC_ERROR_BAD_LEVEL
Compression level not supported by this context's workspace.
Definition zxc_error.h:74
@ ZXC_OK
Success (no error).
Definition zxc_error.h:38
@ ZXC_ERROR_BAD_BLOCK_SIZE
Invalid block size.
Definition zxc_error.h:66
@ ZXC_ERROR_DICT_TOO_LARGE
Dictionary exceeds maximum allowed size.
Definition zxc_error.h:71
#define ZXC_MAGIC_WORD
Magic word opening every frame, stored little-endian (F5 2E B0 9C).
#define ZXC_FILE_DIGEST_SIZE
Archive digest, opening the footer when the header sets HAS_CHECKSUM.
#define ZXC_FILE_HEADER_SIZE
File header size: Magic(4) + Version(1) + Chunk(1) + Flags(1) + Reserved(7) + Checksum(2).
#define ZXC_FILE_FOOTER_MIN_SIZE
Smallest file footer: original_size(1) + compressed_size(1) + lengths(1).
#define ZXC_FILE_FORMAT_VERSION
Current on-disk file format version.
#define ZXC_FILE_FLAG_HAS_CHECKSUM
Bit flag in the Flags byte indicating checksum presence (bit 7).
static uint32_t zxc_seek_group_len(const uint64_t nblocks, const uint64_t g)
Blocks in group g of nblocks: ZXC_SEEK_GROUP, fewer for the last.
#define ZXC_SEEK_GROUP
Blocks per group.
#define ZXC_ALIGN_CL(x)
Round x up to the next cache-line boundary.
#define ZXC_ALWAYS_INLINE
Forces a function to be inlined (fallback for non-GCC/Clang/MSVC compilers).
#define ZXC_ALIGNED_FREE(ptr)
Counterpart deallocator for ZXC_ALIGNED_MALLOC.
Definition zxc_deps.h:137
#define ZXC_CHECKSUM_RAPIDHASH
Checksum algorithm id for RapidHash (default, sole implementation).
#define ZXC_BLOCK_FORMAT_OVERHEAD
Worst-case format overhead inside a single block beyond the outer 8-byte block header and the optiona...
static uint64_t zxc_seek_table_bytes(const uint64_t nblocks)
Byte size of the groups for nblocks blocks, in 64 bits.
#define ZXC_FILE_FLAG_RESERVED
Reserved bit in the Flags byte (bit 4), must be 0.
#define ZXC_ALIGNED_MALLOC(size, alignment)
Cache-line-aligned allocator.
Definition zxc_deps.h:134
#define ZXC_LZ_HASH_SIZE
Maximum number of entries in the hash table.
#define ZXC_FILE_CHECKSUM_ALGO_MASK
Mask for the checksum algorithm id (bits 0-3).
#define ZXC_SPL_HEADER_BINARY_SIZE
Binary size of a SPL block sub-header.
#define ZXC_SEEK_SIZE_ENTRY
One block's on-disk size, u32.
#define ZXC_LZ_MIN_MATCH_LEN
Minimum match length for an LZ77 match.
#define ZXC_LZ_WINDOW_SIZE
Sliding window size (64 KB).
#define ZXC_PAD_SIZE
Safety padding appended to buffers to tolerate overruns.
#define ZXC_FILE_FLAG_HAS_DICTIONARY
Bit flag in the Flags byte indicating a dictionary is required (bit 6).
static uint32_t zxc_seek_size_field(const uint64_t table_bytes)
SEK header size field: table_bytes with its high half folded onto the low one.
#define ZXC_BLOCK_HEADER_SIZE
Block header size: Type(1)+Flags(1)+Reserved(1)+Checksum(1)+CompSize(4).
#define ZXC_FILE_FLAG_HAS_SEEK_TABLE
Bit flag in the Flags byte: a SEK block sits between the EOF block and the footer (bit 5).
#define ZXC_PAK_HEADER_BINARY_SIZE
Binary size of a PAK block sub-header.
#define ZXC_BLOCK_CHECKSUM_SIZE
Size of the per-block checksum field in bytes.
#define ZXC_SEEK_ANCHOR_SIZE
Group anchor: offset of its first block, u64.
#define ZXC_CACHE_LINE_SIZE
Assumed CPU cache line size for alignment.
static int zxc_magic_prefix_ok(const uint8_t *p, const size_t n)
Whether the first n bytes (up to 4) at p agree with the magic word, so a frame may start there: the c...
#define ZXC_DECOMPRESS_TAIL_PAD
Tail padding required on the decompression destination buffer.
@ ZXC_LEVEL_ULTRA
Maximum density: Huffman-coded literals and sequence tokens.
@ ZXC_LEVEL_DEFAULT
Recommended default: better ratio and decode speed than LZ4.
@ ZXC_LEVEL_FASTEST
Fastest compression; lowest ratio.
@ ZXC_LEVEL_DENSITY
Higher density: adds Huffman-coded literals on top of COMPACT.
const char * zxc_version_string(void)
Returns the human-readable library version string.
int zxc_default_level(void)
Returns the default compression level.
int zxc_max_level(void)
Returns the maximum supported compression level.
unsigned zxc_version_number(void)
Library version as one integer, ZXC_VERSION_NUMBER of the loaded library.
int zxc_min_level(void)
Returns the minimum supported compression level.
const char * zxc_version_codename(void)
Release code name of the loaded library, ZXC_VERSION_CODENAME.
int64_t zxc_write_seek_table(uint8_t *dst, const size_t dst_capacity, const uint32_t *comp_sizes, const uint64_t num_blocks)
Serialises a seek table (a ZXC_BLOCK_SEK block) into dst.
Definition zxc_common.c:779
size_t zxc_seek_table_size(const uint64_t num_blocks)
Byte size of a seek table holding num_blocks blocks: header, then groups.
Definition zxc_common.c:724
#define ZXC_VERSION_CODENAME
Release code name.
#define ZXC_VERSION_NUMBER
Version as one integer, MAJOR * 10000 + MINOR * 100 + PATCH (e.g.
#define ZXC_LIB_VERSION_STR
Human-readable version string in "MAJOR.MINOR.PATCH" form (e.g.
On-disk header structure for a ZXC block (8 bytes, little-endian).
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 * hash_tags
Split tag table for fast match rejection (8-bit tags).
zxc_dict_huf_state_t * dict_huf
Tree-at-attach state (PivCo tree + codes + code lengths), carved from the workspace only when dict_si...
uint8_t * buf_split
Match-splitting scratch, one byte per sequence.
size_t lit_buffer_cap
Current capacity of the scratch buffer.
void * memory_block
Single allocation block owner.
size_t opt_scratch_cap
Current capacity of opt_scratch in bytes.
size_t work_buf_cap
Capacity of the work buffer.
void * entropy_block
Lazy allocation backing tok_buffer + pivco_scratch (heap decode contexts, first entropy block only).
size_t pivco_scratch_cap
Capacity of pivco_scratch in bytes.
uint32_t epoch
Current epoch for lazy hash table invalidation.
uint32_t * buf_sequences
Buffer for sequence records (packed: LL(8)|ML(8)|Offset(16)).
uint8_t * lit_buffer
Scratch buffer for literals (RLE / Huffman).
uint8_t * work_buf
Padded scratch buffer for buffer-API decompression.
uint32_t * hash_table
Hash table for LZ77 match positions (epoch|pos).
size_t tok_buffer_cap
Capacity of tok_buffer in bytes.
zxc_spl_match_split_hist_t * buf_split_hist
Match-splitting escape histograms.
uint8_t * buf_tokens
Buffer for token sequences.
uint8_t * buf_extras
Buffer for extra lengths (vbytes for LL/ML).
uint8_t * dict_buffer
[dict | data] concat scratch carved from memory_block when dict_size > 0 (NULL otherwise).
uint8_t * pivco_scratch
Level ping-pong scratch for PivCo decode.
size_t dict_size
Dictionary prefill size (0 = no dictionary).
uint8_t * literals
Buffer for literal bytes.
uint8_t * opt_scratch
Optimal-parser DP scratch (level >= 6 only, lazy-allocated, packs dp/parent_len/parent_off/actions).
uint16_t * chain_table
Chain table for collision resolution.
int dict_huf_tree_ok
1 when *dict_huf is built and valid.
uint8_t * tok_buffer
Decode scratch for a Huffman-coded SPL token section (enc_tok == HUFFMAN); NULL on compress.
uint16_t * buf_offsets
Buffer for offsets.
size_t dict_buffer_cap
Capacity of dict_buffer in bytes (0 = none).
What zxc_scan_container learns about a container.
int uses_dict
A frame bound to a dictionary.
uint64_t frames
ZXC frames.
uint64_t dsize
Sum of the stored decompressed sizes.
Frame-constant dictionary Huffman state, prebuilt once at attach.
What a frame's header and footer declare, read without decoding.
Definition zxc_buffer.h:275
uint8_t format_version
Format version of the frame.
Definition zxc_buffer.h:281
uint64_t digest
Archive digest; 0 when has_checksum is 0.
Definition zxc_buffer.h:278
uint8_t has_checksum
1 when blocks carry checksums and the footer a digest.
Definition zxc_buffer.h:282
size_t block_size
Block size, 4 KB to 2 MB.
Definition zxc_buffer.h:279
uint64_t decompressed_size
Source bytes the frame decodes to.
Definition zxc_buffer.h:276
uint32_t dict_id
Dictionary ID; 0 is none or ID 0, see zxc_requires_dict().
Definition zxc_buffer.h:280
uint8_t has_seek_table
1 when a seek table precedes the footer.
Definition zxc_buffer.h:283
uint64_t compressed_size
Compressed bytes of the frame, footer included.
Definition zxc_buffer.h:277
Header specific to General (LZ-based) compression blocks.
Where a container scan reads from: memory, or a positioned callback (the FILE* size query).
One-shot buffer compression and decompression.
static uint64_t zxc_load_le_n(const uint8_t *src, const size_t n)
Loads n little-endian bytes.
Definition zxc_common.c:804
int zxc_read_block_header(const uint8_t *src, const size_t src_size, zxc_block_header_t *bh)
Parses and validates a block header from src.
Definition zxc_common.c:699
void zxc_cctx_free(zxc_cctx_t *ctx)
Releases all resources owned by a compression context.
Definition zxc_common.c:382
int zxc_write_block_header(uint8_t *dst, const size_t dst_capacity, const zxc_block_header_t *bh)
Serialises a block header (8 bytes) into dst.
Definition zxc_common.c:680
int zxc_write_pak_header(uint8_t *dst, const size_t rem, const zxc_gnr_header_t *gh)
Serialises a PAK block header.
Definition zxc_common.c:990
int zxc_scan_container(const zxc_scan_src_t *src, const size_t req_chunk, zxc_container_info_t *info)
Measures a whole container without decoding: frames from the last back to the first through zxc_scan_...
Definition zxc_common.c:605
int zxc_seek_table_header(uint8_t *dst, const size_t dst_capacity, const uint64_t num_blocks)
Writes a seek table's block header for num_blocks entries.
Definition zxc_common.c:731
int zxc_parse_file_footer(const uint8_t *end, const size_t avail, uint64_t *src_size, uint64_t *compressed_size, size_t *sizes_len)
Parses the two sizes back from the end of a frame.
Definition zxc_common.c:858
int zxc_scan_frame(const zxc_scan_src_t *src, const uint64_t end, uint64_t *start, zxc_frame_info_t *info, size_t *footer_len, int *has_dict)
Measures the frame ending at end without decoding: its footer's compressed size gives where it starts...
Definition zxc_common.c:561
static size_t zxc_cctx_max_seq(const size_t chunk_size)
Worst-case sequence count for one block.
Definition zxc_common.c:74
int zxc_cctx_alloc_entropy_scratch(zxc_cctx_t *ctx)
Lazily allocates the deferred decode-side entropy scratch.
Definition zxc_common.c:355
int zxc_cctx_init_in_workspace(zxc_cctx_t *ctx, void *workspace, const size_t workspace_size, const size_t chunk_size, const int mode, const int level, const int checksum_enabled, const size_t dict_size, const int defer_entropy_scratch)
Partitions a caller-supplied workspace into a ready-to-use context.
Definition zxc_common.c:240
static void zxc_read_gnr_header(const uint8_t *src, zxc_gnr_header_t *gh)
Reads the 12-byte SPL/PAK sub-header shared by both block types.
Definition zxc_common.c:903
static void zxc_write_gnr_header(uint8_t *dst, const zxc_gnr_header_t *gh)
Writes the 12-byte SPL/PAK sub-header shared by both block types.
Definition zxc_common.c:886
static size_t zxc_spl_desc_size(const uint8_t enc_lit, const uint8_t enc_tok)
Size of the SPL section descriptors, implied by the encoding fields.
Definition zxc_common.c:919
int zxc_scan_whole_frame(const zxc_scan_src_t *src, zxc_frame_info_t *info, size_t *footer_len)
The frame that must span all of src: zxc_get_frame_info() and its FILE* twin.
Definition zxc_common.c:593
size_t zxc_cctx_compute_workspace_size(const size_t chunk_size, const int mode, const int level, const size_t dict_size)
Returns the workspace byte count required for the given parameters.
Definition zxc_common.c:225
static void zxc_dctx_entropy_sizes(const size_t chunk_size, size_t *sz_tok, size_t *sz_pivco)
Decode-side entropy scratch sizes for one block: token scratch (worst-case sequence count + wild-read...
Definition zxc_common.c:85
int zxc_read_frame_info(const uint8_t *header, const uint8_t *tail, const size_t tail_len, const uint64_t total, zxc_frame_info_t *info, size_t *footer_len, int *has_dict)
Validates a frame from its header and the end of its bytes.
Definition zxc_common.c:640
int zxc_read_spl_header_and_desc(const uint8_t *src, const size_t len, zxc_gnr_header_t *gh, uint32_t *lit_comp, uint32_t *tok_comp)
Parses a SPL block header and its section descriptors from src.
Definition zxc_common.c:958
size_t zxc_seek_write_group(uint8_t *dst, uint64_t *anchor, const uint32_t *sizes, const uint32_t cnt)
Writes one group (*anchor, then cnt sizes) into dst, which holds ZXC_SEEK_GROUP_BYTES,...
Definition zxc_common.c:763
int zxc_container_next(const zxc_scan_src_t *src, const uint64_t pos)
Tells whether a frame starts at pos.
Definition zxc_common.c:550
int zxc_check_eof_header(const uint8_t *hdr)
Checks an EOF block header against its one valid form: type 255, every other field zero,...
Definition zxc_common.c:741
int zxc_read_pak_header(const uint8_t *src, const size_t len, zxc_gnr_header_t *gh)
Parses a PAK block header from src.
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
static void zxc_store_le_n(uint8_t *dst, uint64_t v, const size_t n)
Stores the low n bytes of v, little-endian.
Definition zxc_common.c:799
static int zxc_scan_read(const zxc_scan_src_t *src, const uint64_t off, void *dst, const size_t len)
Reads a byte range of a scan source, refusing ranges past its end.
Definition zxc_common.c:541
int zxc_read_file_header(const uint8_t *src, const size_t src_size, size_t *out_block_size, int *out_has_checksum, int *out_has_dict, uint32_t *out_dict_id, int *out_has_seek)
Parses and validates a ZXC file header from src.
Definition zxc_common.c:499
int zxc_write_file_footer(uint8_t *dst, const size_t dst_capacity, const uint64_t prefix, const uint64_t src_size, const uint64_t digest, const int checksum_enabled)
Writes the file footer: the archive digest when checksum_enabled, then the two sizes and their length...
Definition zxc_common.c:825
static zxc_cctx_layout_t compute_cctx_layout(const size_t chunk_size, const int mode, const int level, const size_t dict_size, const int defer_entropy_scratch)
Computes the single-allocation memory layout for a compression / decompression context.
Definition zxc_common.c:120
int zxc_write_file_header(uint8_t *dst, const size_t dst_capacity, const size_t chunk_size, const int has_checksum, const int has_dict, const uint32_t dict_id, const int has_seek)
Serialises a ZXC file header into dst.
Definition zxc_common.c:468
int zxc_cctx_attach_dict_huf(zxc_cctx_t *ctx, const uint8_t *lengths)
Attach the shared dictionary literal Huffman table to a context.
Definition zxc_common.c:435
int zxc_check_file_footer(const uint8_t *footer, const size_t avail, const zxc_footer_layout_t *l, const uint64_t src_size, uint64_t *digest)
Checks a footer against the one the frame implies.
Definition zxc_common.c:840
int zxc_write_spl_header_and_desc(uint8_t *dst, const size_t rem, const zxc_gnr_header_t *gh, const uint32_t lit_comp, const uint32_t tok_comp)
Serialises a SPL block header followed by its section descriptors.
Definition zxc_common.c:933
int zxc_check_seek_header(const uint8_t *hdr, const size_t avail, const uint64_t total_out, const size_t block_size, uint64_t *sek_bytes)
Checks the SEK block header the file header announced, on the avail bytes present.
Definition zxc_common.c:750
static void zxc_encode_footer(uint8_t *dst, const zxc_footer_layout_t *l, const uint64_t src_size, const uint64_t digest)
Encodes the l footer: digest, the two sizes, then L.
Definition zxc_common.c:811
Error codes and error-name lookup for the ZXC library.
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).
Internal definitions, constants, SIMD helpers, and utility functions.
#define ZXC_PIVCO_SCRATCH_PAD
Extra scratch slack required past n by the PivCo decoder.
static uint64_t zxc_le64(const void *p)
Reads a little-endian 64-bit value from a possibly unaligned address.
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_SIZE
Scratch size (bytes) for zxc_huf_nudge_code_lengths: builder's, then workspace.
uint32_t zxc_spl_match_split_hist_t[4][2][1U<< 8]
zxc_spl_match_split_analyze's escape histograms: four rotating lanes of [escape][context] counts,...
static void zxc_store_le64(void *p, const uint64_t v)
Writes a 64-bit value little-endian to a possibly unaligned address.
static uint32_t zxc_log2_u32(const uint32_t v)
Integer log-base-2 for a 32-bit value.
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.
#define ZXC_FRAME_MIN_SIZE
Smallest frame: header, the EOF block and the shortest footer.
static uint64_t zxc_seek_block_count(const uint64_t total_decomp, const size_t block_size)
Blocks in total_decomp bytes of block_size: the seek table's entry count, which the SEK header's fiel...
static uint16_t zxc_le16(const void *p)
Reads a little-endian 16-bit value from a possibly unaligned address.
static uint16_t zxc_hash16(const uint8_t *p)
Computes the 2-byte checksum for file and dictionary headers.
static uint8_t zxc_hash8(const uint8_t *p)
Computes the 1-byte checksum for block headers.
static int zxc_footer_dsize_plausible(const uint64_t dsize, const size_t chunk_size, const uint64_t comp_size)
Whether a footer's decompressed size is reachable for this archive.
static void zxc_store_le32(void *p, const uint32_t v)
Writes a 32-bit value little-endian to a possibly unaligned address.
static size_t zxc_uint_bytes(const uint64_t v)
Fewest little-endian bytes, 1 to 8, that hold v.
static size_t zxc_frame_tail_len(const uint64_t total)
Bytes zxc_read_frame_info() takes from the end of total bytes (at least ZXC_FRAME_MIN_SIZE): all of t...
#define ZXC_FOOTER_MAX_SIZE_WITH_DIGEST
Most bytes a footer spans: the digest and the two longest sizes.
static void zxc_file_header_sign(uint8_t *h)
Writes the file header checksum (bytes 14-15) over the other 14 bytes.
static zxc_footer_layout_t zxc_footer_layout(const uint64_t prefix, const uint64_t src_size, const int checksum_enabled)
The footer of a frame whose first prefix bytes precede it.
static int zxc_short_input_verdict(const uint8_t *p, const size_t n)
The verdict on n bytes too short for a frame: the header speaks first, then ZXC_ERROR_SRC_TOO_SMALL.
static int zxc_block_header_ok(const uint8_t *p)
Block header integrity (FORMAT.md Sec 4.1, 7.1): checksum byte matches, Block Flags and Reserved are ...
static void zxc_opt_dp_sizes(const size_t chunk_size, size_t *sz_dp, size_t *sz_pl, size_t *sz_po, size_t *sz_bm)
The four DP partitions the optimal parser carves out of opt_scratch.