zexc 1.2.0

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! C ABI for embedding ZEX in other languages.
//!
//! SPDX-License-Identifier: GPL-3.0-only
//! Copyright (C) 2026 Ali Zain <alizain@zainiumdynamics.tech>
//! Website: https://zainiumdynamics.tech
//!
//! Build with:
//! ```bash
//! cargo build --release --features c-api
//! # produces target/release/libzexc.so / libzexc.a / zexc.dll
//! ```
//!
//! Header: [`include/zexc.h`](../../include/zexc.h).
//!
//! **License:** GPL-3.0-only (strict GPLv3). Distributing linked binaries
//! generally requires providing source under the same terms.

#![allow(clippy::missing_safety_doc)]

use crate::ZEX_VERSION;
use crate::core::decoder::{DecompressOptions, decompress, decompress_with_options};
use crate::core::encoder::{CompressOptions, compress};
use crate::format::header::CompressionMode;
use alloc::vec::Vec;
use core::ffi::{c_char, c_int, c_void};
use core::ptr;
use core::slice;

/// Success.
pub const ZEXC_OK: c_int = 0;
/// Generic error.
pub const ZEXC_ERROR: c_int = -1;
/// Null pointer argument.
pub const ZEXC_ERR_NULL: c_int = -2;
/// Invalid parameter.
pub const ZEXC_ERR_PARAM: c_int = -3;
/// Buffer too small / allocation failure.
pub const ZEXC_ERR_NOMEM: c_int = -4;
/// Corrupt or invalid data.
pub const ZEXC_ERR_DATA: c_int = -5;

/// Library version string (static, do not free).
#[unsafe(no_mangle)]
pub extern "C" fn zexc_version() -> *const c_char {
    // Ensure NUL-terminated static
    static VER: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
    VER.as_ptr() as *const c_char
}

/// Free a buffer returned by `zexc_compress` / `zexc_decompress`.
///
/// `len` must be the length written to `*out_len` at allocation time
/// (capacity was set equal to length).
///
/// # Safety
/// `p` must be null or a pointer previously returned by this library with `len`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zexc_free(p: *mut c_void, len: usize) {
    if p.is_null() {
        return;
    }
    let _ = unsafe { Vec::from_raw_parts(p as *mut u8, len, len) };
}

/// Compress `src_len` bytes at `src`.
///
/// On success: `*out` is a malloc-style buffer (free with [`zexc_free`]),
/// `*out_len` is its length, returns [`ZEXC_OK`].
///
/// `level`: 1–22 (0 = default 3).  
/// `mode`: 0=turbo, 1=balanced, 2=max.
///
/// # Safety
/// Pointers must be valid for the given lengths; `out`/`out_len` non-null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zexc_compress(
    src: *const u8,
    src_len: usize,
    out: *mut *mut u8,
    out_len: *mut usize,
    level: c_int,
    mode: c_int,
) -> c_int {
    if out.is_null() || out_len.is_null() {
        return ZEXC_ERR_NULL;
    }
    if src.is_null() && src_len != 0 {
        return ZEXC_ERR_NULL;
    }
    let input = if src_len == 0 {
        &[][..]
    } else {
        unsafe { slice::from_raw_parts(src, src_len) }
    };

    let lvl = if level <= 0 {
        3
    } else {
        (level as u8).clamp(1, 22)
    };
    let m = match mode {
        0 => CompressionMode::Turbo,
        2 => CompressionMode::Max,
        _ => CompressionMode::Balanced,
    };
    let opts = CompressOptions::default().mode(m).level(lvl).threads(false);

    match compress(input, &opts) {
        Ok(mut buf) => {
            buf.shrink_to_fit();
            let len = buf.len();
            let ptr = buf.as_mut_ptr();
            core::mem::forget(buf);
            unsafe {
                *out = ptr;
                *out_len = len;
            }
            ZEXC_OK
        }
        Err(_) => ZEXC_ERROR,
    }
}

/// Decompress a full `.zex` frame.
///
/// # Safety
/// Same rules as [`zexc_compress`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zexc_decompress(
    src: *const u8,
    src_len: usize,
    out: *mut *mut u8,
    out_len: *mut usize,
) -> c_int {
    if out.is_null() || out_len.is_null() {
        return ZEXC_ERR_NULL;
    }
    if src.is_null() || src_len == 0 {
        return ZEXC_ERR_NULL;
    }
    let input = unsafe { slice::from_raw_parts(src, src_len) };
    match decompress(input) {
        Ok(mut buf) => {
            buf.shrink_to_fit();
            let len = buf.len();
            let ptr = buf.as_mut_ptr();
            core::mem::forget(buf);
            unsafe {
                *out = ptr;
                *out_len = len;
            }
            ZEXC_OK
        }
        Err(crate::Error::CorruptBlock(_))
        | Err(crate::Error::Decompression(_))
        | Err(crate::Error::InvalidHeader(_))
        | Err(crate::Error::ChecksumMismatch { .. }) => ZEXC_ERR_DATA,
        Err(_) => ZEXC_ERROR,
    }
}

/// Bound on compressed size for a given input length (conservative).
#[unsafe(no_mangle)]
pub extern "C" fn zexc_compress_bound(src_len: usize) -> usize {
    // Header + worst-case raw blocks + framing slack
    src_len
        .saturating_add(src_len / 128)
        .saturating_add(1024)
        .saturating_add(64)
}

/// Decompress into a caller-provided buffer.
///
/// Returns bytes written, or negative error code.
/// If `dst` is null, returns required size (positive) or error.
///
/// # Safety
/// `dst` must be valid for `dst_cap` if non-null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zexc_decompress_into(
    src: *const u8,
    src_len: usize,
    dst: *mut u8,
    dst_cap: usize,
) -> isize {
    if src.is_null() || src_len == 0 {
        return ZEXC_ERR_NULL as isize;
    }
    let input = unsafe { slice::from_raw_parts(src, src_len) };
    let plain = match decompress_with_options(input, &DecompressOptions::default()) {
        Ok(p) => p,
        Err(_) => return ZEXC_ERR_DATA as isize,
    };
    if dst.is_null() {
        return plain.len() as isize;
    }
    if plain.len() > dst_cap {
        return ZEXC_ERR_NOMEM as isize;
    }
    unsafe {
        ptr::copy_nonoverlapping(plain.as_ptr(), dst, plain.len());
    }
    plain.len() as isize
}

// Silence unused import warning for ZEX_VERSION if only used in docs
#[allow(dead_code)]
fn _ver() -> &'static str {
    ZEX_VERSION
}