zxc_sys/lib.rs
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#![doc = include_str!("../README.md")]
9#![allow(non_camel_case_types)]
10#![allow(non_upper_case_globals)]
11
12use std::ffi::c_int;
13use std::os::raw::{c_char, c_uint, c_void};
14
15// =============================================================================
16// ZXC Version Constants
17// =============================================================================
18
19// Version constants - automatically extracted from zxc_constants.h by build.rs
20const fn parse_version(s: &str) -> u32 {
21 let bytes = s.as_bytes();
22 let mut result = 0u32;
23 let mut i = 0;
24 while i < bytes.len() {
25 let digit = bytes[i];
26 if digit >= b'0' && digit <= b'9' {
27 result = result * 10 + (digit - b'0') as u32;
28 }
29 i += 1;
30 }
31 result
32}
33
34pub const ZXC_VERSION_MAJOR: u32 = parse_version(env!("ZXC_VERSION_MAJOR"));
35pub const ZXC_VERSION_MINOR: u32 = parse_version(env!("ZXC_VERSION_MINOR"));
36pub const ZXC_VERSION_PATCH: u32 = parse_version(env!("ZXC_VERSION_PATCH"));
37
38// =============================================================================
39// Compression Levels
40// =============================================================================
41
42// Helper function to parse integer from string literal at compile time
43const fn parse_i32(s: &str) -> i32 {
44 let bytes = s.as_bytes();
45 let mut result = 0i32;
46 let mut i = 0;
47 let mut sign = 1;
48
49 if i < bytes.len() && bytes[i] == b'-' {
50 sign = -1;
51 i += 1;
52 }
53
54 while i < bytes.len() {
55 let digit = bytes[i];
56 if digit >= b'0' && digit <= b'9' {
57 result = result * 10 + (digit - b'0') as i32;
58 }
59 i += 1;
60 }
61 result * sign
62}
63
64// Compression level constants - automatically extracted from zxc_constants.h by build.rs
65/// Fastest compression, best for real-time applications
66pub const ZXC_LEVEL_FASTEST: i32 = parse_i32(env!("ZXC_LEVEL_FASTEST"));
67
68/// Fast compression, good for real-time applications
69pub const ZXC_LEVEL_FAST: i32 = parse_i32(env!("ZXC_LEVEL_FAST"));
70
71/// Recommended: ratio > LZ4, decode speed > LZ4
72pub const ZXC_LEVEL_DEFAULT: i32 = parse_i32(env!("ZXC_LEVEL_DEFAULT"));
73
74/// Good ratio, good decode speed
75pub const ZXC_LEVEL_BALANCED: i32 = parse_i32(env!("ZXC_LEVEL_BALANCED"));
76
77/// High density. Best for storage/firmware/assets.
78pub const ZXC_LEVEL_COMPACT: i32 = parse_i32(env!("ZXC_LEVEL_COMPACT"));
79
80/// High density: Huffman-coded literals on top of COMPACT,
81/// price-based optimal LZ77 parser.
82pub const ZXC_LEVEL_DENSITY: i32 = parse_i32(env!("ZXC_LEVEL_DENSITY"));
83
84/// Maximum density: Huffman-coded literals *and* sequence tokens, deep parse.
85/// Slowest compression, best ratio (level 7 / ULTRA).
86pub const ZXC_LEVEL_ULTRA: i32 = parse_i32(env!("ZXC_LEVEL_ULTRA"));
87
88// =============================================================================
89// Error Codes
90// =============================================================================
91
92/// Success (no error)
93pub const ZXC_OK: i32 = 0;
94
95/// Memory allocation failure
96pub const ZXC_ERROR_MEMORY: i32 = -1;
97
98/// Destination buffer too small
99pub const ZXC_ERROR_DST_TOO_SMALL: i32 = -2;
100
101/// Source buffer too small or truncated input
102pub const ZXC_ERROR_SRC_TOO_SMALL: i32 = -3;
103
104/// Invalid magic word in file header
105pub const ZXC_ERROR_BAD_MAGIC: i32 = -4;
106
107/// Unsupported file format version
108pub const ZXC_ERROR_BAD_VERSION: i32 = -5;
109
110/// Corrupted or invalid header (checksum mismatch)
111pub const ZXC_ERROR_BAD_HEADER: i32 = -6;
112
113/// A block's decoded bytes fail its checksum, or the archive digest mismatches
114pub const ZXC_ERROR_BAD_CHECKSUM: i32 = -7;
115
116/// Corrupted compressed data
117pub const ZXC_ERROR_CORRUPT_DATA: i32 = -8;
118
119/// Invalid match offset during decompression
120pub const ZXC_ERROR_BAD_OFFSET: i32 = -9;
121
122/// Buffer overflow detected during processing
123pub const ZXC_ERROR_OVERFLOW: i32 = -10;
124
125/// Read/write/seek failure on file
126pub const ZXC_ERROR_IO: i32 = -11;
127
128/// Required input pointer is NULL
129pub const ZXC_ERROR_NULL_INPUT: i32 = -12;
130
131/// Unknown or unexpected block type
132pub const ZXC_ERROR_BAD_BLOCK_TYPE: i32 = -13;
133
134/// Invalid block size
135pub const ZXC_ERROR_BAD_BLOCK_SIZE: i32 = -14;
136
137/// File requires a dictionary but none was provided
138pub const ZXC_ERROR_DICT_REQUIRED: i32 = -15;
139
140/// Provided dictionary ID does not match the file header
141pub const ZXC_ERROR_DICT_MISMATCH: i32 = -16;
142
143/// Dictionary exceeds maximum allowed size
144pub const ZXC_ERROR_DICT_TOO_LARGE: i32 = -17;
145
146/// Compression level out of range, or not supported by this context's workspace
147pub const ZXC_ERROR_BAD_LEVEL: i32 = -18;
148
149/// Dictionary not supported by this context's workspace (static contexts)
150pub const ZXC_ERROR_DICT_UNSUPPORTED: i32 = -19;
151
152/// Unknown parameter, or value out of its bounds (`zxc_cctx_set_param`,
153/// `zxc_dctx_set_param`)
154pub const ZXC_ERROR_BAD_PARAM: i32 = -20;
155
156// =============================================================================
157// Dictionary Constants
158// =============================================================================
159
160/// Maximum dictionary content size in bytes (65535).
161pub const ZXC_DICT_SIZE_MAX: usize = (1usize << 16) - 1;
162
163/// Fixed size of the `.zxd` file header in bytes.
164pub const ZXC_DICT_HEADER_SIZE: usize = 16;
165
166/// Size in bytes of the shared literal Huffman table carried by a `.zxd` file
167/// (packed 4-bit code lengths for 256 symbols).
168pub const ZXC_HUF_TABLE_SIZE: usize = 128;
169
170// =============================================================================
171// Context Parameters (mirroring zxc_opts.h)
172// =============================================================================
173
174/// Maximum worker thread count accepted by [`ZXC_C_THREADS`] / [`ZXC_D_THREADS`].
175pub const ZXC_MAX_THREADS: i64 = 512;
176
177/// Compression parameter identifier (mirrors the C enum `zxc_cparam_t`).
178///
179/// Set on a [`zxc_cctx`] with [`zxc_cctx_set_param`]; the value 0 restores a
180/// parameter's default, any other value must sit within [`zxc_cparam_bounds`].
181pub type zxc_cparam_t = c_int;
182
183/// Compression level, 1 to 7; default [`ZXC_LEVEL_DEFAULT`].
184pub const ZXC_C_LEVEL: zxc_cparam_t = 1;
185/// Block size in bytes, a power of two in 4 KB..2 MB; default 512 KB.
186pub const ZXC_C_BLOCK_SIZE: zxc_cparam_t = 2;
187/// Worker threads for the `FILE*` pipeline, at most [`ZXC_MAX_THREADS`];
188/// default 0, auto-detect. The buffer, block and push APIs ignore it.
189pub const ZXC_C_THREADS: zxc_cparam_t = 3;
190/// 1 appends the block checksums and the archive digest; default 0.
191pub const ZXC_C_CHECKSUM: zxc_cparam_t = 4;
192/// 1 appends a seek table for random-access decompression; default 0.
193pub const ZXC_C_SEEKABLE: zxc_cparam_t = 5;
194
195/// Decompression parameter identifier (mirrors the C enum `zxc_dparam_t`).
196///
197/// Set on a [`zxc_dctx`] with [`zxc_dctx_set_param`]; same rules as
198/// [`zxc_cparam_t`], bounds from [`zxc_dparam_bounds`].
199pub type zxc_dparam_t = c_int;
200
201/// Worker threads for the `FILE*` pipeline, at most [`ZXC_MAX_THREADS`];
202/// default 0, auto-detect.
203pub const ZXC_D_THREADS: zxc_dparam_t = 1;
204/// 1 verifies the block checksums and the archive digest when the archive
205/// carries them; default 0, no verification.
206pub const ZXC_D_CHECKSUM: zxc_dparam_t = 2;
207
208/// Progress callback (mirrors `zxc_progress_callback_t`), called from the
209/// writer thread of the `FILE*` pipeline after each block or batch of blocks.
210///
211/// Arguments: input bytes processed so far, total input bytes (0 if unknown),
212/// and the `user_data` pointer given to [`zxc_cctx_set_progress`] /
213/// [`zxc_dctx_set_progress`]. Keep it fast and non-blocking.
214pub type zxc_progress_callback_t =
215 Option<unsafe extern "C" fn(bytes_processed: u64, bytes_total: u64, user_data: *const c_void)>;
216
217/// What a frame's header and footer declare (mirrors `zxc_frame_info_t`).
218#[repr(C)]
219#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
220pub struct zxc_frame_info_t {
221 /// Source bytes the frame decodes to.
222 pub decompressed_size: u64,
223 /// Compressed bytes of the frame, footer included.
224 pub compressed_size: u64,
225 /// Archive digest; 0 when `has_checksum` is 0.
226 pub digest: u64,
227 /// Block size, 4 KB to 2 MB.
228 pub block_size: usize,
229 /// Dictionary the frame needs; 0 for none.
230 pub dict_id: u32,
231 /// Format version of the frame.
232 pub format_version: u8,
233 /// 1 when blocks carry checksums and the footer a digest.
234 pub has_checksum: u8,
235 /// 1 when a seek table precedes the footer.
236 pub has_seek_table: u8,
237}
238
239// =============================================================================
240// Opaque Context Handles
241// =============================================================================
242
243/// Opaque compression context. Use [`zxc_create_cctx`] to create.
244#[repr(C)]
245pub struct zxc_cctx {
246 _private: [u8; 0],
247}
248
249/// Opaque decompression context. Use [`zxc_create_dctx`] to create.
250#[repr(C)]
251pub struct zxc_dctx {
252 _private: [u8; 0],
253}
254
255// =============================================================================
256// Library Info Helpers
257// =============================================================================
258
259unsafe extern "C" {
260 /// Returns the minimum supported compression level (currently 1).
261 pub fn zxc_min_level() -> c_int;
262
263 /// Returns the maximum supported compression level (currently 7).
264 pub fn zxc_max_level() -> c_int;
265
266 /// Returns the default compression level (currently 3).
267 pub fn zxc_default_level() -> c_int;
268
269 /// Returns the library version as a null-terminated string.
270 ///
271 /// The returned pointer is a compile-time constant and must not be freed.
272 pub fn zxc_version_string() -> *const c_char;
273
274 /// Returns the library version as `MAJOR * 10000 + MINOR * 100 + PATCH`.
275 ///
276 /// Compare with the crate's `ZXC_VERSION_*` constants to detect a runtime
277 /// library older than the one compiled against.
278 pub fn zxc_version_number() -> c_uint;
279
280 /// Returns the release code name of the library as a null-terminated
281 /// string (e.g. `"Hydrogen"`). Informational only.
282 ///
283 /// The returned pointer is a compile-time constant and must not be freed.
284 pub fn zxc_version_codename() -> *const c_char;
285}
286
287// =============================================================================
288// Buffer-Based API
289// =============================================================================
290
291unsafe extern "C" {
292 /// Calculates the maximum compressed size for a given input.
293 ///
294 /// Useful for allocating output buffers before compression.
295 pub fn zxc_compress_bound(input_size: usize) -> usize;
296
297 /// Compresses a data buffer into a complete ZXC archive, at `level`.
298 ///
299 /// The simple form: one level, every other parameter at its default
300 /// (512 KB blocks, no checksum, no seek table, no dictionary). For
301 /// anything else, configure a [`zxc_cctx`] and call [`zxc_compress_cctx`].
302 ///
303 /// # Safety
304 ///
305 /// - `src` must be a valid pointer to `src_size` bytes.
306 /// - `dst` must be a valid pointer to at least `dst_capacity` bytes.
307 /// - The caller must ensure no data races on the buffers.
308 ///
309 /// # Returns
310 ///
311 /// Number of bytes written to `dst` (>0 on success), or a negative error
312 /// code. `level` 0 selects the default; any other level outside 1..7 is
313 /// `ZXC_ERROR_BAD_LEVEL`.
314 pub fn zxc_compress(
315 src: *const c_void,
316 src_size: usize,
317 dst: *mut c_void,
318 dst_capacity: usize,
319 level: c_int,
320 ) -> i64;
321
322 /// Decompresses a complete ZXC archive.
323 ///
324 /// The simple form: no checksum verification and no dictionary. For
325 /// either, configure a [`zxc_dctx`] and call [`zxc_decompress_dctx`].
326 ///
327 /// # Safety
328 ///
329 /// - `src` must be a valid pointer to `src_size` bytes of compressed data.
330 /// - `dst` must be a valid pointer to at least `dst_capacity` bytes, or
331 /// NULL with `dst_capacity` 0 to probe the archive without decoding.
332 ///
333 /// # Returns
334 ///
335 /// Number of decompressed bytes written to `dst`, 0 for an empty archive,
336 /// or a negative error code.
337 pub fn zxc_decompress(
338 src: *const c_void,
339 src_size: usize,
340 dst: *mut c_void,
341 dst_capacity: usize,
342 ) -> i64;
343
344 /// Returns the decompressed size stored in a ZXC compressed buffer.
345 ///
346 /// Reads the file footer without performing decompression.
347 ///
348 /// # Returns
349 ///
350 /// Original uncompressed size in bytes, or 0 if invalid.
351 pub fn zxc_get_decompressed_size(src: *const c_void, src_size: usize) -> u64;
352
353 /// Reads a frame's header and footer, without decoding.
354 ///
355 /// # Returns
356 ///
357 /// `ZXC_OK` with `*info` filled, or a negative error code.
358 ///
359 /// # Safety
360 /// - `src` must be a valid pointer to `src_size` bytes.
361 /// - `info` must be valid for writes of `info_size` bytes.
362 pub fn zxc_get_frame_info(
363 src: *const c_void,
364 src_size: usize,
365 info: *mut zxc_frame_info_t,
366 info_size: usize,
367 ) -> c_int;
368
369 /// Returns `sizeof(zxc_frame_info_t)` as compiled into the C library.
370 ///
371 /// Layout guard: the Rust [`zxc_frame_info_t`] mirrors the C struct by
372 /// hand; comparing sizes turns silent layout drift into a test failure
373 /// (see the `frame_info_layout_matches_library` test).
374 pub fn zxc_frame_info_size() -> usize;
375
376 /// Returns the minimum single-buffer size for an in-place decompression.
377 ///
378 /// Reads `src`'s header and footer (no decoding) and returns the buffer
379 /// size `zxc_decompress_inplace` needs: decompressed size plus a
380 /// one-block and wild-copy safety margin.
381 ///
382 /// # Returns
383 ///
384 /// Required buffer size in bytes, or 0 if `src` is not a valid archive.
385 pub fn zxc_decompress_inplace_bound(src: *const c_void, src_size: usize) -> usize;
386
387 /// Decompresses in place inside a single caller-owned buffer.
388 ///
389 /// The compressed archive must sit flush-right in `buffer` (its last
390 /// `comp_size` bytes); decoding runs left-to-right into `buffer[0..]`.
391 /// `buffer_capacity` must be at least `zxc_decompress_inplace_bound`.
392 /// No checksum verification and no dictionary: for either, configure a
393 /// [`zxc_dctx`] and call [`zxc_decompress_inplace_dctx`].
394 ///
395 /// # Returns
396 ///
397 /// Decompressed size (>0), 0 for an empty frame, or a negative error
398 /// code (`ZXC_ERROR_DST_TOO_SMALL` if the margin is missing).
399 pub fn zxc_decompress_inplace(
400 buffer: *mut c_void,
401 buffer_capacity: usize,
402 comp_size: usize,
403 ) -> i64;
404
405 /// In-place decompression with a caller-supplied context.
406 ///
407 /// Same contract as `zxc_decompress_inplace`, with `dctx` as the decode
408 /// context and its parameters. With a static context
409 /// (`zxc_init_static_dctx`) the call allocates nothing; it rejects a
410 /// foreign block size and any dictionary.
411 pub fn zxc_decompress_inplace_dctx(
412 dctx: *mut zxc_dctx,
413 buffer: *mut c_void,
414 buffer_capacity: usize,
415 comp_size: usize,
416 ) -> i64;
417
418 /// Returns a human-readable name for the given error code.
419 ///
420 /// # Arguments
421 ///
422 /// * `code` - An error code from zxc_error_t (or any integer)
423 ///
424 /// # Returns
425 ///
426 /// A constant string such as "ZXC_OK" or "ZXC_ERROR_MEMORY".
427 /// Returns "ZXC_UNKNOWN_ERROR" for unrecognized codes.
428 pub fn zxc_error_name(code: c_int) -> *const std::os::raw::c_char;
429
430 /// Returns the dictionary ID a ZXC compressed buffer requires.
431 ///
432 /// Reads the file header without decompressing. Returns 0 if the file
433 /// does not require a dictionary or the buffer is invalid.
434 ///
435 /// # Safety
436 /// - `src` must be a valid pointer to `src_size` bytes.
437 pub fn zxc_get_dict_id(src: *const c_void, src_size: usize) -> u32;
438}
439
440// =============================================================================
441// Dictionary API
442// =============================================================================
443
444unsafe extern "C" {
445 /// Trains a dictionary from a corpus of samples.
446 ///
447 /// # Safety
448 /// - `samples` must point to `n_samples` valid pointers, each valid for
449 /// the corresponding `sample_sizes` entry.
450 /// - `sample_sizes` must point to `n_samples` entries.
451 /// - `dict_buf` must be valid for writes up to `dict_capacity` bytes.
452 ///
453 /// # Returns
454 /// Size of the trained dictionary (>0), or a negative `zxc_error_t` code.
455 pub fn zxc_dict_train_content(
456 samples: *const *const c_void,
457 sample_sizes: *const usize,
458 n_samples: usize,
459 dict_buf: *mut c_void,
460 dict_capacity: usize,
461 ) -> i64;
462
463 /// Computes the dictionary ID: content-only when `huf_lengths` is null,
464 /// else binding the (content, table) pair.
465 ///
466 /// # Safety
467 /// - `dict` must be a valid pointer to `dict_size` bytes.
468 /// - `huf_lengths` must be null or valid for 128 bytes (`ZXC_HUF_TABLE_SIZE`).
469 ///
470 /// Returns 0 if `dict` is NULL or `dict_size` is 0.
471 pub fn zxc_dict_compute_id(
472 dict: *const c_void,
473 dict_size: usize,
474 huf_lengths: *const c_void,
475 ) -> u32;
476
477 /// Returns the dictionary ID stored in a `.zxd` file buffer.
478 ///
479 /// # Safety
480 /// - `buf` must be a valid pointer to `buf_size` bytes.
481 ///
482 /// Returns 0 if the buffer is not a valid `.zxd` file.
483 pub fn zxc_dict_read_id(buf: *const c_void, buf_size: usize) -> u32;
484
485 /// Returns the `.zxd` file size for a given content size
486 /// (= 16 + `content_size` + 128 for the shared Huffman table).
487 pub fn zxc_dict_save_bound(content_size: usize) -> usize;
488
489 /// Trains the shared literal Huffman table for an already-trained dictionary.
490 ///
491 /// # Safety
492 /// - `samples`/`sample_sizes` as in [`zxc_dict_train_content`].
493 /// - `dict` must be valid for `dict_size` bytes.
494 /// - `huf_lengths_out` must be valid for writes of 128 bytes
495 /// (`ZXC_HUF_TABLE_SIZE`).
496 ///
497 /// # Returns
498 /// `ZXC_OK` (0) on success, or a negative `zxc_error_t` code.
499 pub fn zxc_dict_train_huf(
500 samples: *const *const c_void,
501 sample_sizes: *const usize,
502 n_samples: usize,
503 dict: *const c_void,
504 dict_size: usize,
505 huf_lengths_out: *mut u8,
506 ) -> c_int;
507
508 /// Serializes dictionary content plus its shared Huffman table to the
509 /// `.zxd` file format. The table is mandatory.
510 ///
511 /// # Safety
512 /// - `content` must be valid for `content_size` bytes.
513 /// - `huf_lengths` must be valid for 128 bytes (`ZXC_HUF_TABLE_SIZE`).
514 /// - `buf` must be valid for writes up to `buf_capacity` bytes.
515 ///
516 /// # Returns
517 /// Bytes written (>0), or a negative `zxc_error_t` code.
518 pub fn zxc_dict_save(
519 content: *const c_void,
520 content_size: usize,
521 huf_lengths: *const c_void,
522 buf: *mut c_void,
523 buf_capacity: usize,
524 ) -> i64;
525
526 /// Returns a pointer to the 128-byte shared Huffman table inside a `.zxd`
527 /// buffer (zero-copy; aims into `buf`), or NULL if `buf` is not a valid
528 /// `.zxd` file.
529 ///
530 /// # Safety
531 /// - `buf` must be valid for `buf_size` bytes.
532 pub fn zxc_dict_huf(buf: *const c_void, buf_size: usize) -> *const c_void;
533
534 /// Loads and validates a `.zxd` dictionary file from a memory buffer.
535 ///
536 /// On success, `content_out` and `huf_out` (when non-NULL) point INTO `buf`
537 /// (zero-copy); the caller must keep `buf` alive while they are in use.
538 ///
539 /// # Safety
540 /// - `buf` must be valid for `buf_size` bytes.
541 /// - `content_out` and `content_size_out` must be valid pointers.
542 /// - `huf_out` and `dict_id_out` may be NULL.
543 ///
544 /// # Returns
545 /// `ZXC_OK` (0) on success, or a negative `zxc_error_t` code.
546 pub fn zxc_dict_load(
547 buf: *const c_void,
548 buf_size: usize,
549 content_out: *mut *const c_void,
550 content_size_out: *mut usize,
551 huf_out: *mut *const c_void,
552 dict_id_out: *mut u32,
553 ) -> c_int;
554
555 /// One-call dictionary creation: trains content + shared table and
556 /// serializes to ready-to-write `.zxd` bytes in `zxd_buf`.
557 ///
558 /// # Safety
559 /// - `samples`/`sample_sizes` as in [`zxc_dict_train_content`].
560 /// - `zxd_buf` must be valid for writes up to `zxd_capacity` bytes.
561 ///
562 /// # Returns
563 /// Bytes written (>0), or a negative `zxc_error_t` code.
564 pub fn zxc_dict_train(
565 samples: *const *const c_void,
566 sample_sizes: *const usize,
567 n_samples: usize,
568 zxd_buf: *mut c_void,
569 zxd_capacity: usize,
570 ) -> i64;
571}
572
573// =============================================================================
574// Block API (single block, no file framing)
575// =============================================================================
576
577unsafe extern "C" {
578 /// Returns the maximum compressed size for a single block (no file framing).
579 pub fn zxc_compress_block_bound(input_size: usize) -> usize;
580
581 /// Returns the minimum `dst_capacity` required by [`zxc_decompress_block`]
582 /// for a block of `uncompressed_size` bytes. Accounts for the wild-copy
583 /// tail pad used by the fast decoder.
584 pub fn zxc_decompress_block_bound(uncompressed_size: usize) -> usize;
585
586 /// Compresses a single block without file framing, with the parameters
587 /// in force on `cctx` (level, checksum, dictionary).
588 ///
589 /// Output format: `block_header(8B) + payload + optional checksum(4B)`.
590 ///
591 /// # Safety
592 /// - `cctx` must be a valid pointer returned by [`zxc_create_cctx`].
593 /// - `src`, `dst` must point to `src_size` / `dst_capacity` bytes.
594 pub fn zxc_compress_block(
595 cctx: *mut zxc_cctx,
596 src: *const c_void,
597 src_size: usize,
598 dst: *mut c_void,
599 dst_capacity: usize,
600 ) -> i64;
601
602 /// Decompresses a single block produced by [`zxc_compress_block`], with
603 /// the parameters in force on `dctx` (checksum, dictionary).
604 ///
605 /// `dst_capacity` should be at least
606 /// [`zxc_decompress_block_bound(uncompressed_size)`](zxc_decompress_block_bound)
607 /// to enable the fast path.
608 ///
609 /// # Safety
610 /// - `dctx` must be a valid pointer returned by [`zxc_create_dctx`].
611 pub fn zxc_decompress_block(
612 dctx: *mut zxc_dctx,
613 src: *const c_void,
614 src_size: usize,
615 dst: *mut c_void,
616 dst_capacity: usize,
617 ) -> i64;
618
619 /// Strict-sized variant of [`zxc_decompress_block`]: accepts
620 /// `dst_capacity == uncompressed_size` exactly (no tail pad required).
621 /// Slightly slower than the fast path; output is bit-identical.
622 ///
623 /// # Safety
624 /// - `dctx` must be a valid pointer returned by [`zxc_create_dctx`].
625 pub fn zxc_decompress_block_safe(
626 dctx: *mut zxc_dctx,
627 src: *const c_void,
628 src_size: usize,
629 dst: *mut c_void,
630 dst_capacity: usize,
631 ) -> i64;
632
633 /// Estimates the memory reserved by a compression context for a single
634 /// block of `src_size` bytes via [`zxc_compress_block`].
635 ///
636 /// Covers all per-chunk working buffers (chain table, literals,
637 /// sequence/token/offset/extras buffers) plus the fixed hash tables and
638 /// cache-line alignment padding. At `level >= 6` the value also accounts
639 /// for the price-based optimal parser's transient DP scratch (~18 x
640 /// `src_size` bytes), free'd at the end of each block.
641 ///
642 /// Returns the estimated peak memory usage in bytes, or 0 if `src_size == 0`.
643 pub fn zxc_estimate_cctx_size(src_size: usize, level: c_int) -> usize;
644}
645
646// =============================================================================
647// Reusable Context API (opaque, heap-allocated)
648// =============================================================================
649
650unsafe extern "C" {
651 /// Creates a heap-allocated compression context, every parameter at its
652 /// default (level 3, 512 KB blocks, no checksum, no seek table).
653 ///
654 /// Only the handle is allocated here; the working buffers come on the
655 /// first call, sized from the parameters then in force. Configure it with
656 /// [`zxc_cctx_set_param`], [`zxc_cctx_set_dict`] and
657 /// [`zxc_cctx_set_progress`]. Returns NULL on allocation failure. Free
658 /// with [`zxc_free_cctx`].
659 pub fn zxc_create_cctx() -> *mut zxc_cctx;
660
661 /// Frees a compression context. Safe to call with a null pointer.
662 ///
663 /// # Safety
664 /// - `cctx` must be a pointer returned by [`zxc_create_cctx`] (or null).
665 pub fn zxc_free_cctx(cctx: *mut zxc_cctx);
666
667 /// Sets one parameter on `cctx`; 0 restores its default.
668 ///
669 /// Takes effect on the next call. A value outside [`zxc_cparam_bounds`]
670 /// is refused and the parameter keeps its value: `ZXC_ERROR_BAD_LEVEL`
671 /// for [`ZXC_C_LEVEL`], `ZXC_ERROR_BAD_BLOCK_SIZE` for
672 /// [`ZXC_C_BLOCK_SIZE`] (a non-power-of-two included),
673 /// `ZXC_ERROR_BAD_PARAM` otherwise, and for an unknown `param`. On a
674 /// static context the block size is pinned, and a level raise into
675 /// level 6 is refused when the workspace was carved below it.
676 ///
677 /// # Safety
678 /// - `cctx` must be a valid pointer returned by [`zxc_create_cctx`] or
679 /// [`zxc_init_static_cctx`].
680 pub fn zxc_cctx_set_param(cctx: *mut zxc_cctx, param: zxc_cparam_t, value: i64) -> c_int;
681
682 /// Reads one parameter of `cctx` into `*value`.
683 ///
684 /// Returns `ZXC_OK`, `ZXC_ERROR_BAD_PARAM` for an unknown `param`, or
685 /// `ZXC_ERROR_NULL_INPUT`.
686 ///
687 /// # Safety
688 /// - `cctx` must be a valid context; `value` must be valid for writes.
689 pub fn zxc_cctx_get_param(cctx: *const zxc_cctx, param: zxc_cparam_t, value: *mut i64)
690 -> c_int;
691
692 /// Reports the accepted range of a compression parameter.
693 ///
694 /// Returns `ZXC_OK`, or `ZXC_ERROR_BAD_PARAM` for an unknown `param`.
695 ///
696 /// # Safety
697 /// - `min` and `max` must each be NULL or valid for writes.
698 pub fn zxc_cparam_bounds(param: zxc_cparam_t, min: *mut i64, max: *mut i64) -> c_int;
699
700 /// Attaches a pre-trained dictionary to `cctx`; a NULL `dict` detaches.
701 ///
702 /// The context keeps the pointers only: the bytes stay caller-owned and
703 /// must outlive every call that uses them. `dict_huf`, when non-NULL, is
704 /// the [`ZXC_HUF_TABLE_SIZE`]-byte shared literal table.
705 ///
706 /// Returns `ZXC_OK`; `ZXC_ERROR_DICT_TOO_LARGE` above
707 /// [`ZXC_DICT_SIZE_MAX`]; `ZXC_ERROR_DICT_UNSUPPORTED` on a static context.
708 ///
709 /// # Safety
710 /// - `cctx` must be a valid context.
711 /// - `dict` must be NULL or valid for `dict_size` bytes for as long as it
712 /// stays attached; `dict_huf` NULL or valid for 128 bytes likewise.
713 pub fn zxc_cctx_set_dict(
714 cctx: *mut zxc_cctx,
715 dict: *const c_void,
716 dict_size: usize,
717 dict_huf: *const c_void,
718 ) -> c_int;
719
720 /// Sets the progress callback; `None` disables it. Honoured by
721 /// [`zxc_stream_compress`] only.
722 ///
723 /// # Safety
724 /// - `cctx` must be a valid context; `user_data` is handed back to `cb`
725 /// unchanged and must stay valid while the callback is attached.
726 pub fn zxc_cctx_set_progress(
727 cctx: *mut zxc_cctx,
728 cb: zxc_progress_callback_t,
729 user_data: *mut c_void,
730 ) -> c_int;
731
732 /// Restores every parameter to its default, detaches the dictionary and
733 /// the callback. The working buffers are kept. On a static context the
734 /// pinned block size and level are the defaults.
735 ///
736 /// # Safety
737 /// - `cctx` must be a valid context.
738 pub fn zxc_cctx_reset(cctx: *mut zxc_cctx) -> c_int;
739
740 /// Compresses a full file-framed buffer using a reusable context, with
741 /// the parameters in force on it (level, block size, checksum, seek
742 /// table, dictionary).
743 ///
744 /// # Safety
745 /// - `cctx` must be a valid pointer returned by [`zxc_create_cctx`].
746 pub fn zxc_compress_cctx(
747 cctx: *mut zxc_cctx,
748 src: *const c_void,
749 src_size: usize,
750 dst: *mut c_void,
751 dst_capacity: usize,
752 ) -> i64;
753
754 /// Creates a heap-allocated decompression context, every parameter at
755 /// its default (no checksum verification, no dictionary).
756 ///
757 /// Configure it with [`zxc_dctx_set_param`], [`zxc_dctx_set_dict`] and
758 /// [`zxc_dctx_set_progress`]. Returns NULL on allocation failure. Free
759 /// with [`zxc_free_dctx`].
760 pub fn zxc_create_dctx() -> *mut zxc_dctx;
761
762 /// Frees a decompression context. Safe to call with a null pointer.
763 ///
764 /// # Safety
765 /// - `dctx` must be a pointer returned by [`zxc_create_dctx`] (or null).
766 pub fn zxc_free_dctx(dctx: *mut zxc_dctx);
767
768 /// Sets one parameter on `dctx`; 0 restores its default.
769 ///
770 /// A value outside [`zxc_dparam_bounds`] is `ZXC_ERROR_BAD_PARAM`, as is
771 /// an unknown `param`; the parameter keeps its value.
772 ///
773 /// # Safety
774 /// - `dctx` must be a valid pointer returned by [`zxc_create_dctx`] or
775 /// [`zxc_init_static_dctx`].
776 pub fn zxc_dctx_set_param(dctx: *mut zxc_dctx, param: zxc_dparam_t, value: i64) -> c_int;
777
778 /// Reads one parameter of `dctx` into `*value`. See [`zxc_cctx_get_param`].
779 ///
780 /// # Safety
781 /// - `dctx` must be a valid context; `value` must be valid for writes.
782 pub fn zxc_dctx_get_param(dctx: *const zxc_dctx, param: zxc_dparam_t, value: *mut i64)
783 -> c_int;
784
785 /// Reports the accepted range of a decompression parameter. See
786 /// [`zxc_cparam_bounds`].
787 ///
788 /// # Safety
789 /// - `min` and `max` must each be NULL or valid for writes.
790 pub fn zxc_dparam_bounds(param: zxc_dparam_t, min: *mut i64, max: *mut i64) -> c_int;
791
792 /// Attaches the dictionary the archives were compressed with; NULL
793 /// detaches. Same ownership rules as [`zxc_cctx_set_dict`]; the header's
794 /// dict_id is checked against the (dict, table) pair at decode time.
795 ///
796 /// # Safety
797 /// - `dctx` must be a valid context.
798 /// - `dict` must be NULL or valid for `dict_size` bytes for as long as it
799 /// stays attached; `dict_huf` NULL or valid for 128 bytes likewise.
800 pub fn zxc_dctx_set_dict(
801 dctx: *mut zxc_dctx,
802 dict: *const c_void,
803 dict_size: usize,
804 dict_huf: *const c_void,
805 ) -> c_int;
806
807 /// Sets the progress callback; `None` disables it. Honoured by
808 /// [`zxc_stream_decompress`] only.
809 ///
810 /// # Safety
811 /// - `dctx` must be a valid context; `user_data` is handed back to `cb`
812 /// unchanged and must stay valid while the callback is attached.
813 pub fn zxc_dctx_set_progress(
814 dctx: *mut zxc_dctx,
815 cb: zxc_progress_callback_t,
816 user_data: *mut c_void,
817 ) -> c_int;
818
819 /// Restores every parameter to its default, detaches the dictionary and
820 /// the callback. The working buffers are kept.
821 ///
822 /// # Safety
823 /// - `dctx` must be a valid context.
824 pub fn zxc_dctx_reset(dctx: *mut zxc_dctx) -> c_int;
825
826 /// Decompresses a full file-framed buffer using a reusable context, with
827 /// the parameters in force on it (checksum, dictionary).
828 ///
829 /// # Safety
830 /// - `dctx` must be a valid pointer returned by [`zxc_create_dctx`].
831 pub fn zxc_decompress_dctx(
832 dctx: *mut zxc_dctx,
833 src: *const c_void,
834 src_size: usize,
835 dst: *mut c_void,
836 dst_capacity: usize,
837 ) -> i64;
838
839 /// Returns the exact byte count required by a static compression
840 /// workspace for the given `block_size` and `level`.
841 ///
842 /// # Returns
843 ///
844 /// Workspace size in bytes, or 0 if either argument is invalid.
845 pub fn zxc_static_cctx_workspace_size(block_size: usize, level: c_int) -> usize;
846
847 /// Initialises a compression context inside a caller-supplied workspace
848 /// (no heap allocation), carved for `block_size` and `level` (1..7).
849 ///
850 /// Both are pinned: [`zxc_cctx_set_param`] refuses another block size
851 /// and a level raise into level 6 when `level` was below it; checksum,
852 /// seek table and lower levels are honoured. [`zxc_cctx_set_dict`]
853 /// returns `ZXC_ERROR_DICT_UNSUPPORTED`. Returns NULL if the workspace
854 /// is too small or a parameter is invalid.
855 ///
856 /// # Safety
857 /// - `workspace` must be cache-line (64-byte) aligned, at least
858 /// `zxc_static_cctx_workspace_size(block_size, level)` bytes, and
859 /// outlive the handle.
860 /// - `zxc_free_cctx` is a no-op on the returned handle.
861 pub fn zxc_init_static_cctx(
862 workspace: *mut c_void,
863 workspace_size: usize,
864 block_size: usize,
865 level: c_int,
866 ) -> *mut zxc_cctx;
867
868 /// Returns the exact byte count required by a static decompression
869 /// workspace for the given `block_size`.
870 ///
871 /// # Returns
872 ///
873 /// Workspace size in bytes, or 0 if `block_size` is invalid.
874 pub fn zxc_static_dctx_workspace_size(block_size: usize) -> usize;
875
876 /// Initialises a decompression context inside a caller-supplied
877 /// workspace (no heap allocation).
878 ///
879 /// # Safety
880 /// - `workspace` must be cache-line (64-byte) aligned, at least
881 /// `zxc_static_dctx_workspace_size` bytes, and outlive the handle.
882 /// - `zxc_free_dctx` is a no-op on the returned handle.
883 pub fn zxc_init_static_dctx(
884 workspace: *mut c_void,
885 workspace_size: usize,
886 block_size: usize,
887 ) -> *mut zxc_dctx;
888}
889
890// =============================================================================
891// Streaming API (FILE-based)
892// =============================================================================
893
894unsafe extern "C" {
895 /// Compresses data from an input stream to an output stream.
896 ///
897 /// Uses a multi-threaded pipeline architecture for high throughput
898 /// on large files.
899 ///
900 /// # Safety
901 ///
902 /// - `f_in` must be a valid FILE* opened in "rb" mode
903 /// - `f_out` must be a valid FILE* opened in "wb" mode
904 /// - File handles must remain valid for the duration of the call
905 /// - `cfg` must be NULL or a valid [`zxc_cctx`]
906 ///
907 /// # Arguments
908 ///
909 /// * `f_in` - Input file stream
910 /// * `f_out` - Output file stream
911 /// * `cfg` - Configured compression context, read for its parameters
912 /// (level, block size, threads, checksum, seek table, dictionary,
913 /// progress callback), or NULL for defaults. Its buffers are not used:
914 /// it is configuration only and may be freed after the call.
915 ///
916 /// # Returns
917 ///
918 /// Total compressed bytes written, or a negative error code.
919 pub fn zxc_stream_compress(
920 f_in: *mut libc::FILE,
921 f_out: *mut libc::FILE,
922 cfg: *const zxc_cctx,
923 ) -> i64;
924
925 /// Decompresses data from an input stream to an output stream.
926 ///
927 /// Uses the same pipeline architecture as compression for maximum throughput.
928 ///
929 /// # Safety
930 ///
931 /// - `f_in` must be a valid FILE* opened in "rb" mode
932 /// - `f_out` must be a valid FILE* opened in "wb" mode
933 /// - `cfg` must be NULL or a valid [`zxc_dctx`]
934 ///
935 /// # Arguments
936 ///
937 /// * `f_in` - Input file stream (compressed data)
938 /// * `f_out` - Output file stream (decompressed data)
939 /// * `cfg` - Configured decompression context, read for its parameters
940 /// (threads, checksum, dictionary, progress callback), or NULL for
941 /// defaults. Its buffers are not used.
942 ///
943 /// # Returns
944 ///
945 /// Total decompressed bytes written, or a negative error code.
946 pub fn zxc_stream_decompress(
947 f_in: *mut libc::FILE,
948 f_out: *mut libc::FILE,
949 cfg: *const zxc_dctx,
950 ) -> i64;
951
952 /// Returns the decompressed size stored in a ZXC compressed file.
953 ///
954 /// Reads the file footer to extract the original size without decompressing.
955 /// The file position is restored after reading.
956 ///
957 /// # Safety
958 ///
959 /// - `f_in` must be a valid FILE* opened in "rb" mode
960 ///
961 /// # Returns
962 ///
963 /// Original uncompressed size in bytes, or -1 on error.
964 pub fn zxc_stream_get_decompressed_size(f_in: *mut libc::FILE) -> i64;
965}
966
967// =============================================================================
968// Seekable API (random-access decompression)
969// =============================================================================
970
971/// Opaque handle for a seekable ZXC archive.
972///
973/// Created by [`zxc_seekable_open`] or [`zxc_seekable_open_file`].
974/// Must be freed with [`zxc_seekable_free`].
975#[repr(C)]
976pub struct zxc_seekable {
977 _private: [u8; 0],
978}
979
980/// Storage-agnostic reader interface for seekable archives (mirrors
981/// `zxc_reader_t` from `zxc_seekable.h`).
982///
983/// `read_at` is the only primitive the library calls on the backend. It must
984/// return the number of bytes read (`== len` on success) or a negative
985/// `zxc_error_t` on failure. Short reads are treated as errors by the library.
986///
987/// `read_at` MUST be safe to call concurrently from multiple threads when the
988/// resulting handle is used with [`zxc_seekable_decompress_range_mt`]. The
989/// single-threaded path makes no concurrent calls.
990#[repr(C)]
991pub struct zxc_reader_t {
992 /// Positional read callback. NULL is rejected at open time.
993 pub read_at: Option<
994 unsafe extern "C" fn(ctx: *mut c_void, dst: *mut c_void, len: usize, offset: u64) -> i64,
995 >,
996 /// Opaque user context passed unchanged to `read_at`.
997 pub ctx: *mut c_void,
998 /// Total size of the compressed archive in bytes.
999 pub size: u64,
1000}
1001
1002unsafe extern "C" {
1003 /// Opens a seekable archive from a memory buffer.
1004 ///
1005 /// The buffer must remain valid for the lifetime of the handle.
1006 ///
1007 /// # Safety
1008 /// - `src` must be a valid pointer to `src_size` bytes.
1009 ///
1010 /// Returns NULL if the buffer is not a valid seekable archive.
1011 pub fn zxc_seekable_open(src: *const c_void, src_size: usize) -> *mut zxc_seekable;
1012
1013 /// Opens a seekable archive from a `FILE*`. The file must be seekable
1014 /// (not stdin/pipe). The current file position is saved and restored.
1015 /// The FILE* must remain open for the lifetime of the handle.
1016 ///
1017 /// # Safety
1018 /// - `f` must be a valid FILE* opened in "rb" mode.
1019 pub fn zxc_seekable_open_file(f: *mut libc::FILE) -> *mut zxc_seekable;
1020
1021 /// Opens a seekable archive through a user-supplied [`zxc_reader_t`].
1022 ///
1023 /// The reader is invoked to fetch the file header, footer, and EOF/SEK
1024 /// block headers at open time (3 reads), then once per seek table group
1025 /// and once per block during decompression.
1026 /// Use this entry point to back the seekable API with any storage that
1027 /// supports positional reads (mmap, HTTP `Range:`, S3, kernel
1028 /// `vfs_read()`, etc.).
1029 ///
1030 /// # Safety
1031 /// - `r` must point to a valid [`zxc_reader_t`] whose `read_at`,
1032 /// `ctx`, and backing storage remain valid for the lifetime of the
1033 /// returned handle.
1034 ///
1035 /// Returns NULL on any open-time error.
1036 pub fn zxc_seekable_open_reader(r: *const zxc_reader_t) -> *mut zxc_seekable;
1037
1038 /// Attaches a dictionary to a seekable handle. The dictionary content
1039 /// must remain valid for the lifetime of the handle (or until replaced).
1040 ///
1041 /// # Safety
1042 /// - `s` must be a valid handle from [`zxc_seekable_open`] etc.
1043 /// - `dict` must be valid for `dict_size` bytes (or NULL with 0).
1044 /// - `dict_huf` must be NULL or valid for 128 bytes
1045 /// (`ZXC_HUF_TABLE_SIZE`).
1046 ///
1047 /// Returns `ZXC_OK` (0) on success, or a negative `zxc_error_t` code.
1048 pub fn zxc_seekable_set_dict(
1049 s: *mut zxc_seekable,
1050 dict: *const c_void,
1051 dict_size: usize,
1052 dict_huf: *const c_void,
1053 ) -> c_int;
1054
1055 pub fn zxc_seekable_set_checksum(s: *mut zxc_seekable, enabled: c_int) -> c_int;
1056
1057 /// Returns the total number of data blocks in the archive (excluding EOF).
1058 ///
1059 /// Derived from the footer, never stored, so only the archive size bounds it.
1060 pub fn zxc_seekable_get_num_blocks(s: *const zxc_seekable) -> u64;
1061
1062 /// Returns the total decompressed size of the archive in bytes.
1063 pub fn zxc_seekable_get_decompressed_size(s: *const zxc_seekable) -> u64;
1064
1065 /// Returns the on-disk compressed size of a specific block
1066 /// (block header + payload + optional per-block checksum).
1067 ///
1068 /// Returns 0 if `block_idx` is out of range.
1069 pub fn zxc_seekable_get_block_comp_size(s: *const zxc_seekable, block_idx: u64) -> u32;
1070
1071 /// Returns the decompressed size of a specific block.
1072 ///
1073 /// Returns 0 if `block_idx` is out of range.
1074 pub fn zxc_seekable_get_block_decomp_size(s: *const zxc_seekable, block_idx: u64) -> u32;
1075
1076 /// Decompresses `len` bytes starting at byte `offset` in the original
1077 /// uncompressed data. Only the blocks overlapping the requested range
1078 /// are read and decompressed.
1079 ///
1080 /// # Safety
1081 /// - `s` must be a valid handle returned by [`zxc_seekable_open`].
1082 /// - `dst` must point to at least `dst_capacity` bytes.
1083 ///
1084 /// Returns `len` on success, or a negative `zxc_error_t` on failure.
1085 pub fn zxc_seekable_decompress_range(
1086 s: *mut zxc_seekable,
1087 dst: *mut c_void,
1088 dst_capacity: usize,
1089 offset: u64,
1090 len: usize,
1091 ) -> i64;
1092
1093 /// Multi-threaded variant of [`zxc_seekable_decompress_range`].
1094 ///
1095 /// Each worker owns its own decompression context and reads via `pread()`
1096 /// (POSIX) or `ReadFile()` (Windows) for lock-free concurrent I/O.
1097 /// Falls back to single-threaded mode when `n_threads <= 1` or the range
1098 /// spans a single block.
1099 ///
1100 /// # Safety
1101 /// - `s` must be a valid handle returned by [`zxc_seekable_open`].
1102 /// - `dst` must point to at least `dst_capacity` bytes.
1103 pub fn zxc_seekable_decompress_range_mt(
1104 s: *mut zxc_seekable,
1105 dst: *mut c_void,
1106 dst_capacity: usize,
1107 offset: u64,
1108 len: usize,
1109 n_threads: c_int,
1110 ) -> i64;
1111
1112 /// Frees a seekable handle and all associated resources.
1113 /// Safe to call with a null pointer.
1114 ///
1115 /// # Safety
1116 /// - `s` must be a pointer returned by [`zxc_seekable_open`] /
1117 /// [`zxc_seekable_open_file`], or null.
1118 pub fn zxc_seekable_free(s: *mut zxc_seekable);
1119
1120 /// Low-level: writes a seek table (block header + entries) to `dst`.
1121 ///
1122 /// # Safety
1123 /// - `dst` must point to at least `dst_capacity` bytes.
1124 /// - `comp_sizes` must point to at least `num_blocks` entries.
1125 ///
1126 /// Returns bytes written, or a negative `zxc_error_t` on failure.
1127 pub fn zxc_write_seek_table(
1128 dst: *mut u8,
1129 dst_capacity: usize,
1130 comp_sizes: *const u32,
1131 num_blocks: u64,
1132 ) -> i64;
1133
1134 /// Returns the encoded byte size of a seek table for `num_blocks` blocks,
1135 /// or 0 when that size does not fit a `usize`.
1136 pub fn zxc_seek_table_size(num_blocks: u64) -> usize;
1137}
1138
1139// =============================================================================
1140// Push Streaming API (single-threaded, caller-driven)
1141// =============================================================================
1142
1143/// Input buffer descriptor for push streaming
1144/// (mirrors `zxc_inbuf_t` from `zxc_pstream.h`).
1145#[repr(C)]
1146#[derive(Debug)]
1147pub struct zxc_inbuf_t {
1148 /// Caller-owned input bytes.
1149 pub src: *const c_void,
1150 /// Total bytes available in `src`.
1151 pub size: usize,
1152 /// Bytes already consumed by the library (in/out).
1153 pub pos: usize,
1154}
1155
1156/// Output buffer descriptor for push streaming
1157/// (mirrors `zxc_outbuf_t` from `zxc_pstream.h`).
1158#[repr(C)]
1159#[derive(Debug)]
1160pub struct zxc_outbuf_t {
1161 /// Caller-owned output region.
1162 pub dst: *mut c_void,
1163 /// Total capacity available at `dst`.
1164 pub size: usize,
1165 /// Bytes already produced by the library (in/out).
1166 pub pos: usize,
1167}
1168
1169/// Opaque push compression stream. Use [`zxc_cstream_create`] to create.
1170#[repr(C)]
1171pub struct zxc_cstream {
1172 _private: [u8; 0],
1173}
1174
1175/// Opaque push decompression stream. Use [`zxc_dstream_create`] to create.
1176#[repr(C)]
1177pub struct zxc_dstream {
1178 _private: [u8; 0],
1179}
1180
1181unsafe extern "C" {
1182 /// Creates a push compression stream.
1183 ///
1184 /// The parameters are copied from `cfg` at creation; the context may be
1185 /// freed or reused afterwards. Only [`ZXC_C_LEVEL`], [`ZXC_C_BLOCK_SIZE`]
1186 /// and [`ZXC_C_CHECKSUM`] are honoured; threads, seek table and the
1187 /// progress callback are ignored. A dictionary on `cfg` fails creation.
1188 /// Returns NULL on allocation failure or a dictionary on `cfg`. Free with
1189 /// [`zxc_cstream_free`].
1190 ///
1191 /// # Safety
1192 /// - `cfg` must be NULL (all defaults) or a valid [`zxc_cctx`].
1193 pub fn zxc_cstream_create(cfg: *const zxc_cctx) -> *mut zxc_cstream;
1194
1195 /// Releases a push compression stream. Safe to call with null.
1196 ///
1197 /// # Safety
1198 /// - `cs` must be a pointer returned by [`zxc_cstream_create`] (or null).
1199 pub fn zxc_cstream_free(cs: *mut zxc_cstream);
1200
1201 /// Pushes input bytes into the stream and drains compressed output.
1202 ///
1203 /// Returns 0 if `in` was fully consumed and no compressed bytes remain
1204 /// pending; >0 number of bytes still pending; <0 on error.
1205 ///
1206 /// # Safety
1207 /// - `cs` must be a valid stream from [`zxc_cstream_create`].
1208 /// - `out` and `in_` must point to valid `zxc_outbuf_t` / `zxc_inbuf_t`.
1209 pub fn zxc_cstream_compress(
1210 cs: *mut zxc_cstream,
1211 out: *mut zxc_outbuf_t,
1212 in_: *mut zxc_inbuf_t,
1213 ) -> i64;
1214
1215 /// Finalises the stream: flushes pending data, writes EOF block + footer.
1216 ///
1217 /// Returns 0 when finalisation is complete; >0 bytes still pending; <0
1218 /// on error.
1219 ///
1220 /// # Safety
1221 /// - `cs` must be a valid stream from [`zxc_cstream_create`].
1222 /// - `out` must point to a valid `zxc_outbuf_t`.
1223 pub fn zxc_cstream_end(cs: *mut zxc_cstream, out: *mut zxc_outbuf_t) -> i64;
1224
1225 /// Suggested input chunk size for best compressor throughput.
1226 pub fn zxc_cstream_in_size(cs: *const zxc_cstream) -> usize;
1227
1228 /// Suggested output chunk size for the compressor.
1229 pub fn zxc_cstream_out_size(cs: *const zxc_cstream) -> usize;
1230
1231 /// Creates a push decompression stream.
1232 ///
1233 /// The parameters are copied from `cfg` at creation; only
1234 /// [`ZXC_D_CHECKSUM`] is honoured. A dictionary on `cfg` fails creation.
1235 /// Returns NULL on allocation failure or a dictionary on `cfg`. Free with
1236 /// [`zxc_dstream_free`].
1237 ///
1238 /// # Safety
1239 /// - `cfg` must be NULL (all defaults) or a valid [`zxc_dctx`].
1240 pub fn zxc_dstream_create(cfg: *const zxc_dctx) -> *mut zxc_dstream;
1241
1242 /// Releases a push decompression stream. Safe to call with null.
1243 ///
1244 /// # Safety
1245 /// - `ds` must be a pointer returned by [`zxc_dstream_create`] (or null).
1246 pub fn zxc_dstream_free(ds: *mut zxc_dstream);
1247
1248 /// Pushes compressed input and drains decompressed output.
1249 ///
1250 /// Returns >0 number of decompressed bytes written this call; 0 if the
1251 /// stream is complete (DONE) or no progress is possible; <0 on error.
1252 ///
1253 /// # Safety
1254 /// - `ds` must be a valid stream from [`zxc_dstream_create`].
1255 /// - `out` and `in_` must point to valid `zxc_outbuf_t` / `zxc_inbuf_t`.
1256 pub fn zxc_dstream_decompress(
1257 ds: *mut zxc_dstream,
1258 out: *mut zxc_outbuf_t,
1259 in_: *mut zxc_inbuf_t,
1260 ) -> i64;
1261
1262 /// Returns 1 iff the decoder reached and validated the file footer.
1263 pub fn zxc_dstream_finished(ds: *const zxc_dstream) -> c_int;
1264
1265 /// Suggested input chunk size for the decompressor.
1266 pub fn zxc_dstream_in_size(ds: *const zxc_dstream) -> usize;
1267
1268 /// Suggested output chunk size for the decompressor.
1269 pub fn zxc_dstream_out_size(ds: *const zxc_dstream) -> usize;
1270}
1271
1272// =============================================================================
1273// Tests
1274// =============================================================================
1275
1276#[cfg(test)]
1277mod tests {
1278 use super::*;
1279
1280 /// `zxc_frame_info_t` is hand-mirrored from zxc_buffer.h. A C-side field
1281 /// change that is not replicated here silently shifts every later field
1282 /// (undefined behaviour at the FFI boundary); this test turns that drift
1283 /// into a hard failure.
1284 #[test]
1285 fn frame_info_layout_matches_library() {
1286 unsafe {
1287 assert_eq!(
1288 std::mem::size_of::<zxc_frame_info_t>(),
1289 zxc_frame_info_size(),
1290 "zxc_frame_info_t layout drift: update the Rust mirror in zxc-sys"
1291 );
1292 }
1293 }
1294
1295 #[test]
1296 fn test_compress_bound() {
1297 unsafe {
1298 let bound = zxc_compress_bound(1024);
1299 // Should return a reasonable bound (input + overhead)
1300 assert!(bound > 1024);
1301 assert!(bound < 1024 * 2); // Should not be excessively large
1302 }
1303 }
1304
1305 #[test]
1306 fn test_version_number() {
1307 let header = ZXC_VERSION_MAJOR * 10000 + ZXC_VERSION_MINOR * 100 + ZXC_VERSION_PATCH;
1308 assert_eq!(unsafe { zxc_version_number() }, header);
1309 }
1310
1311 #[test]
1312 fn test_version_codename() {
1313 let codename = unsafe { std::ffi::CStr::from_ptr(zxc_version_codename()) };
1314 assert!(!codename.to_bytes().is_empty());
1315 }
1316
1317 #[test]
1318 fn test_roundtrip() {
1319 // Use highly repetitive data that definitely compresses well
1320 let input: Vec<u8> = (0..4096)
1321 .map(|i| ((i % 16) as u8).wrapping_add(b'A'))
1322 .collect();
1323
1324 unsafe {
1325 // Allocate compression buffer
1326 let bound = zxc_compress_bound(input.len());
1327 let mut compressed = vec![0u8; bound];
1328
1329 // Compress with checksums: that needs a configured context.
1330 let cctx = zxc_create_cctx();
1331 assert!(!cctx.is_null());
1332 assert_eq!(
1333 zxc_cctx_set_param(cctx, ZXC_C_LEVEL, ZXC_LEVEL_DEFAULT as i64),
1334 ZXC_OK
1335 );
1336 assert_eq!(zxc_cctx_set_param(cctx, ZXC_C_CHECKSUM, 1), ZXC_OK);
1337 let compressed_size = zxc_compress_cctx(
1338 cctx,
1339 input.as_ptr() as *const c_void,
1340 input.len(),
1341 compressed.as_mut_ptr() as *mut c_void,
1342 compressed.len(),
1343 );
1344 zxc_free_cctx(cctx);
1345 assert!(compressed_size > 0, "Compression failed");
1346 // Highly repetitive data should compress significantly
1347 assert!(
1348 (compressed_size as usize) < input.len() / 2,
1349 "Data should compress well"
1350 );
1351
1352 // Get decompressed size
1353 let decompressed_size = zxc_get_decompressed_size(
1354 compressed.as_ptr() as *const c_void,
1355 compressed_size as usize,
1356 );
1357 assert_eq!(decompressed_size as usize, input.len());
1358
1359 // Decompress, verifying the checksums.
1360 let mut decompressed = vec![0u8; decompressed_size as usize];
1361 let dctx = zxc_create_dctx();
1362 assert!(!dctx.is_null());
1363 assert_eq!(zxc_dctx_set_param(dctx, ZXC_D_CHECKSUM, 1), ZXC_OK);
1364 let result_size = zxc_decompress_dctx(
1365 dctx,
1366 compressed.as_ptr() as *const c_void,
1367 compressed_size as usize,
1368 decompressed.as_mut_ptr() as *mut c_void,
1369 decompressed.len(),
1370 );
1371 zxc_free_dctx(dctx);
1372 assert_eq!(result_size, input.len() as i64);
1373 assert_eq!(&decompressed[..], &input[..]);
1374
1375 // The simple forms agree with the configured ones.
1376 let simple_size = zxc_compress(
1377 input.as_ptr() as *const c_void,
1378 input.len(),
1379 compressed.as_mut_ptr() as *mut c_void,
1380 compressed.len(),
1381 ZXC_LEVEL_DEFAULT,
1382 );
1383 assert!(simple_size > 0, "zxc_compress failed");
1384 let result_size = zxc_decompress(
1385 compressed.as_ptr() as *const c_void,
1386 simple_size as usize,
1387 decompressed.as_mut_ptr() as *mut c_void,
1388 decompressed.len(),
1389 );
1390 assert_eq!(result_size, input.len() as i64);
1391 assert_eq!(&decompressed[..], &input[..]);
1392 }
1393 }
1394
1395 #[test]
1396 fn test_all_levels() {
1397 let input = b"Test data for all compression levels - with some repetition \
1398 to ensure compression works: BBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
1399
1400 for level in [
1401 ZXC_LEVEL_FASTEST,
1402 ZXC_LEVEL_FAST,
1403 ZXC_LEVEL_DEFAULT,
1404 ZXC_LEVEL_BALANCED,
1405 ZXC_LEVEL_COMPACT,
1406 ZXC_LEVEL_DENSITY,
1407 ZXC_LEVEL_ULTRA,
1408 ] {
1409 unsafe {
1410 let bound = zxc_compress_bound(input.len());
1411 let mut compressed = vec![0u8; bound];
1412
1413 let compressed_size = zxc_compress(
1414 input.as_ptr() as *const c_void,
1415 input.len(),
1416 compressed.as_mut_ptr() as *mut c_void,
1417 compressed.len(),
1418 level,
1419 );
1420 assert!(compressed_size > 0, "Compression failed at level {}", level);
1421 }
1422 }
1423 }
1424
1425 /// The parameter contract the safe crate relies on: bounds, set/get, 0
1426 /// restores the default, out-of-range refused with the documented code,
1427 /// unknown identifier refused, reset.
1428 #[test]
1429 fn test_context_params() {
1430 unsafe {
1431 let (mut lo, mut hi) = (0i64, 0i64);
1432 assert_eq!(zxc_cparam_bounds(ZXC_C_LEVEL, &mut lo, &mut hi), ZXC_OK);
1433 assert_eq!((lo, hi), (ZXC_LEVEL_FASTEST as i64, ZXC_LEVEL_ULTRA as i64));
1434 assert_eq!(zxc_cparam_bounds(ZXC_C_THREADS, &mut lo, &mut hi), ZXC_OK);
1435 assert_eq!((lo, hi), (0, ZXC_MAX_THREADS));
1436 assert_eq!(
1437 zxc_cparam_bounds(99, std::ptr::null_mut(), std::ptr::null_mut()),
1438 ZXC_ERROR_BAD_PARAM
1439 );
1440 assert_eq!(zxc_dparam_bounds(ZXC_D_CHECKSUM, &mut lo, &mut hi), ZXC_OK);
1441 assert_eq!((lo, hi), (0, 1));
1442 assert_eq!(
1443 zxc_dparam_bounds(99, std::ptr::null_mut(), std::ptr::null_mut()),
1444 ZXC_ERROR_BAD_PARAM
1445 );
1446
1447 let cctx = zxc_create_cctx();
1448 assert!(!cctx.is_null());
1449 let mut v = -1i64;
1450 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_LEVEL, &mut v), ZXC_OK);
1451 assert_eq!(v, ZXC_LEVEL_DEFAULT as i64);
1452 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_BLOCK_SIZE, &mut v), ZXC_OK);
1453 assert_eq!(v, 512 * 1024);
1454
1455 assert_eq!(zxc_cctx_set_param(cctx, ZXC_C_LEVEL, 5), ZXC_OK);
1456 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_LEVEL, &mut v), ZXC_OK);
1457 assert_eq!(v, 5);
1458 assert_eq!(
1459 zxc_cctx_set_param(cctx, ZXC_C_LEVEL, 8),
1460 ZXC_ERROR_BAD_LEVEL
1461 );
1462 assert_eq!(
1463 zxc_cctx_set_param(cctx, ZXC_C_BLOCK_SIZE, 3000),
1464 ZXC_ERROR_BAD_BLOCK_SIZE
1465 );
1466 assert_eq!(
1467 zxc_cctx_set_param(cctx, ZXC_C_CHECKSUM, 2),
1468 ZXC_ERROR_BAD_PARAM
1469 );
1470 assert_eq!(zxc_cctx_set_param(cctx, 99, 1), ZXC_ERROR_BAD_PARAM);
1471 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_LEVEL, &mut v), ZXC_OK);
1472 assert_eq!(v, 5, "a refused value must not change the parameter");
1473
1474 assert_eq!(zxc_cctx_set_param(cctx, ZXC_C_LEVEL, 0), ZXC_OK);
1475 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_LEVEL, &mut v), ZXC_OK);
1476 assert_eq!(v, ZXC_LEVEL_DEFAULT as i64, "0 restores the default");
1477
1478 assert_eq!(zxc_cctx_set_param(cctx, ZXC_C_SEEKABLE, 1), ZXC_OK);
1479 assert_eq!(zxc_cctx_reset(cctx), ZXC_OK);
1480 assert_eq!(zxc_cctx_get_param(cctx, ZXC_C_SEEKABLE, &mut v), ZXC_OK);
1481 assert_eq!(v, 0, "reset restores the defaults");
1482 zxc_free_cctx(cctx);
1483
1484 let dctx = zxc_create_dctx();
1485 assert!(!dctx.is_null());
1486 assert_eq!(zxc_dctx_set_param(dctx, ZXC_D_CHECKSUM, 1), ZXC_OK);
1487 assert_eq!(zxc_dctx_get_param(dctx, ZXC_D_CHECKSUM, &mut v), ZXC_OK);
1488 assert_eq!(v, 1);
1489 assert_eq!(
1490 zxc_dctx_set_param(dctx, ZXC_D_THREADS, ZXC_MAX_THREADS + 1),
1491 ZXC_ERROR_BAD_PARAM
1492 );
1493 assert_eq!(zxc_dctx_set_param(dctx, 99, 1), ZXC_ERROR_BAD_PARAM);
1494 assert_eq!(zxc_dctx_reset(dctx), ZXC_OK);
1495 assert_eq!(zxc_dctx_get_param(dctx, ZXC_D_CHECKSUM, &mut v), ZXC_OK);
1496 assert_eq!(v, 0);
1497 zxc_free_dctx(dctx);
1498 }
1499 }
1500}