Skip to main content

omnizip_ffi/
lib.rs

1//! omnizip-ffi — the C ABI over the omnizip codecs: the Rust side of
2//! the Ruby gem's Rust-accelerated path.
3//!
4//! The surface is deliberately tiny and stable: three codecs
5//! (zstd, bzip2, lzma/xz), explicit lengths, one call each way, a
6//! thread-local last-error, and one deallocator. Ruby binds it with
7//! stdlib `Fiddle` — no compiled extension, no rake-compiler:
8//!
9//! ```ruby
10//! require 'fiddle'
11//! lib = Fiddle.dlopen('libomnizip_ffi.dylib')
12//! compress = Fiddle::Function.new(lib['ozip_compress'],
13//!   [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T,
14//!    Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP)
15//! ```
16//!
17//! ## Safety model
18//!
19//! Every entry point is `pub extern "C"` with a documented SAFETY
20//! contract; panics never cross the boundary (`catch_unwind` at
21//! every entry); errors surface as `NULL` returns plus
22//! [`ozip_last_error`]. Buffer ownership is explicit: returned
23//! buffers are Rust-allocated and MUST be freed by [`ozip_free`] —
24//! nothing else may touch them.
25//!
26//! ## Determinism
27//!
28//! The codecs' contracts carry through: same input + level ⇒ same
29//! bytes, on every machine — the tier swap in the gem cannot
30//! disturb downstream content addressing.
31
32// The workspace `forbid` cannot be scoped; this crate keeps the
33// strictest enforceable form and allows it ONLY in the `shim`
34// module, where each unsafe block carries its contract.
35#![deny(unsafe_code)]
36#![allow(clippy::missing_safety_doc)]
37
38use std::cell::RefCell;
39use std::ffi::c_char;
40use std::ffi::CString;
41
42use omnizip_codecs::level::CompressionLevel;
43use omnizip_codecs::{Codec, OmnizipError};
44
45thread_local! {
46    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::new("no error").expect("static"));
47}
48
49fn set_last_error(msg: String) {
50    let sanitized = msg.replace('\0', " ");
51    LAST_ERROR.with(|e| {
52        *e.borrow_mut() =
53            CString::new(sanitized).unwrap_or_else(|_| CString::new("error").expect("static"));
54    });
55}
56
57fn codec_by_name(name: &str) -> Result<Box<dyn Codec>, String> {
58    match name {
59        "zstd" => Ok(Box::new(omnizip_zstd::ZstdCodec)),
60        "bzip2" => Ok(Box::new(omnizip_bzip2::Bzip2Codec)),
61        "lzma" | "xz" => Ok(Box::new(omnizip_lzma::LzmaCodec)),
62        "deflate" => Ok(Box::new(RawDeflateAdapter)),
63        "deflate64" => Ok(Box::new(omnizip_deflate64::Deflate64Codec)),
64        "lzma-alone" => Ok(Box::new(LzmaAloneAdapter)),
65        "lzip" => Ok(Box::new(LzipAdapter)),
66        "zlib" => Ok(Box::new(omnizip_libdeflate::LibdeflateCodec)),
67        "gzip" => Ok(Box::new(GzipAdapter)),
68        name if name.starts_with("ppmd7:") || name.starts_with("ppmd8:") => {
69            let (variant, order, mem) = parse_ppmd_name(name)?;
70            match variant {
71                7 => Ok(Box::new(PpmdAdapter7 { order, mem })),
72                _ => Ok(Box::new(PpmdAdapter8 { order, mem })),
73            }
74        }
75        other => Err(format!(
76            "unknown codec '{other}' (available: zstd, bzip2, lzma, xz, deflate, deflate64, lzma-alone, lzip, zlib, gzip, ppmd7:*, ppmd8:*)"
77        )),
78    }
79}
80
81/// The error from the most recent FFI call on this thread, as a
82/// NUL-terminated C string valid until the next call. Never NULL.
83#[allow(unsafe_code)]
84#[no_mangle]
85pub extern "C" fn ozip_last_error() -> *const c_char {
86    LAST_ERROR.with(|e| e.borrow().as_ptr())
87}
88
89/// The library's semver (`env!("CARGO_PKG_VERSION")`) as a
90/// NUL-terminated C string. Static for the process lifetime — the
91/// gem's platform-gem smoke gate asserts the vendored dylib matches
92/// the gem's expected Rust release.
93#[allow(unsafe_code)]
94#[no_mangle]
95pub extern "C" fn ozip_version() -> *const c_char {
96    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr().cast()
97}
98
99/// Free a buffer returned by `ozip_compress`/`ozip_decompress`.
100///
101/// # Safety
102///
103/// `buf` must have been returned by this library on the same
104/// thread-era allocation (Rust global allocator), `len` must be the
105/// length reported at return time, and the buffer must not have
106/// been freed already. Passing NULL is a no-op.
107#[allow(unsafe_code)]
108#[no_mangle]
109pub unsafe extern "C" fn ozip_free(buf: *mut u8, len: usize) {
110    if buf.is_null() {
111        return;
112    }
113    // SAFETY: the caller satisfies the contract above — the pointer
114    // came from Vec::into_raw_parts (below) with this exact length,
115    // and ownership transfers back here exactly once.
116    drop(unsafe { Vec::from_raw_parts(buf, len, len) });
117}
118
119/// Compress `input` (`input_len` bytes) with `codec` at `level`.
120/// Returns a Rust-allocated buffer and writes its length through
121/// `out_len`, or NULL on error (see `ozip_last_error`).
122///
123/// # Safety
124///
125/// `codec` must be a readable NUL-terminated string; `input` must
126/// be readable for `input_len` bytes; `out_len` must be writable.
127/// The returned buffer must be freed with `ozip_free`.
128#[allow(unsafe_code)]
129#[no_mangle]
130pub unsafe extern "C" fn ozip_compress(
131    codec: *const c_char,
132    input: *const u8,
133    input_len: usize,
134    level: u8,
135    out_len: *mut usize,
136) -> *mut u8 {
137    // SAFETY: caller contract above.
138    #[allow(unsafe_code)]
139    match unsafe { try_compress(codec, input, input_len, level, out_len) } {
140        Ok(ptr) => ptr,
141        Err(()) => std::ptr::null_mut(),
142    }
143}
144
145#[allow(unsafe_code)]
146unsafe fn try_compress(
147    codec: *const c_char,
148    input: *const u8,
149    input_len: usize,
150    level: u8,
151    out_len: *mut usize,
152) -> Result<*mut u8, ()> {
153    let name = unsafe { std::ffi::CStr::from_ptr(codec) }
154        .to_string_lossy()
155        .into_owned();
156    let data = if input_len == 0 {
157        &[][..]
158    } else {
159        // SAFETY: caller guarantees readability for input_len.
160        unsafe { std::slice::from_raw_parts(input, input_len) }
161    };
162    let result = std::panic::catch_unwind(|| {
163        codec_by_name(&name).and_then(|c| {
164            c.compress(data, CompressionLevel::new(level))
165                .map_err(|e| e.to_string())
166        })
167    });
168    match result {
169        Ok(Ok(out)) => {
170            unsafe { *out_len = out.len() };
171            Ok(ozip_take(out))
172        }
173        Ok(Err(msg)) => {
174            set_last_error(msg);
175            Err(())
176        }
177        Err(_) => {
178            set_last_error("codec panicked".into());
179            Err(())
180        }
181    }
182}
183
184/// Decompress `input` (`input_len` bytes). `expected_len` is the
185/// exact plaintext size (the codecs verify it); use the value
186/// recorded at compress time. Returns a buffer + length via
187/// `out_len`, or NULL on error.
188///
189/// # Safety
190///
191/// Same contract as `ozip_compress`.
192#[allow(unsafe_code)]
193#[no_mangle]
194pub unsafe extern "C" fn ozip_decompress(
195    codec: *const c_char,
196    input: *const u8,
197    input_len: usize,
198    expected_len: usize,
199    out_len: *mut usize,
200) -> *mut u8 {
201    #[allow(unsafe_code)]
202    match unsafe { try_decompress(codec, input, input_len, expected_len, out_len) } {
203        Ok(ptr) => ptr,
204        Err(()) => std::ptr::null_mut(),
205    }
206}
207
208#[allow(unsafe_code)]
209unsafe fn try_decompress(
210    codec: *const c_char,
211    input: *const u8,
212    input_len: usize,
213    expected_len: usize,
214    out_len: *mut usize,
215) -> Result<*mut u8, ()> {
216    let name = unsafe { std::ffi::CStr::from_ptr(codec) }
217        .to_string_lossy()
218        .into_owned();
219    let data = if input_len == 0 {
220        &[][..]
221    } else {
222        // SAFETY: caller guarantees readability for input_len.
223        unsafe { std::slice::from_raw_parts(input, input_len) }
224    };
225    // expected_len == usize::MAX means "unknown": streaming
226    // callers (the Ruby tier) cannot know the plaintext size. The
227    // Codec trait enforces exact lengths, so this routes to each
228    // codec's length-agnostic free function instead.
229    let result = if expected_len == usize::MAX {
230        std::panic::catch_unwind(|| {
231            match name.as_str() {
232            "zstd" => omnizip_zstd::decompress(data, u32::MAX).map_err(|e| e.to_string()),
233            "bzip2" => omnizip_bzip2::decompress_framed(data).map_err(|e| e.to_string()),
234            "lzma" | "xz" => omnizip_lzma::xz_decompress(data).map_err(|e| e.to_string()),
235            "deflate" => omnizip_libdeflate::decompress_raw_unknown_len(data)
236                .map_err(|e| e.to_string()),
237            "deflate64" => omnizip_deflate64::Deflate64Codec
238                .decompress(data, u32::MAX)
239                .map_err(|e| e.to_string()),
240            "lzma-alone" => omnizip_lzma::lzma_alone_decompress(data).map_err(|e| e.to_string()),
241            "lzip" => omnizip_lzma::lzip_decompress(data).map_err(|e| e.to_string()),
242            "zlib" => omnizip_libdeflate::decompress_zlib_unknown_len(data)
243                .map_err(|e| e.to_string()),
244            "gzip" => omnizip_archive_core::formats::gzip::decompress(data).map_err(|e| e.to_string()),
245            name if name.starts_with("ppmd7:") || name.starts_with("ppmd8:") => {
246                let (variant, _order, mem) = parse_ppmd_name(name)
247                    .map_err(|e| e.to_string())?;
248                // The container carries its own size (magic + order +
249                // u32 LE at bytes 6..10); expected_len is a cross-check
250                // there, so feed the container's value, not a sentinel.
251                if data.len() < 10 {
252                    return Err("ppmd container too short".to_string());
253                }
254                let expected =
255                    u32::from_le_bytes([data[6], data[7], data[8], data[9]]) as usize;
256                match variant {
257                    7 => omnizip_ppmd::ppmd7::codec::decompress_with_budget(
258                        data, expected, mem,
259                    )
260                    .map_err(|e| e.to_string()),
261                    _ => omnizip_ppmd::ppmd8::codec::decompress_with_budget(
262                        data, expected, mem,
263                    )
264                    .map_err(|e| e.to_string()),
265                }
266            }
267            other => Err(format!(
268                "unknown codec '{other}' (available: zstd, bzip2, lzma, xz, deflate, deflate64, lzma-alone, lzip, zlib, gzip, ppmd7:*, ppmd8:*)"
269            )),
270        }
271        })
272    } else {
273        let Ok(expected) = u32::try_from(expected_len) else {
274            set_last_error(format!("expected_len {expected_len} exceeds u32"));
275            return Err(());
276        };
277        std::panic::catch_unwind(|| {
278            codec_by_name(&name).and_then(|c| {
279                c.decompress(data, expected)
280                    .map_err(|e: OmnizipError| e.to_string())
281            })
282        })
283    };
284    match result {
285        Ok(Ok(out)) => {
286            unsafe { *out_len = out.len() };
287            Ok(ozip_take(out))
288        }
289        Ok(Err(msg)) => {
290            set_last_error(msg);
291            Err(())
292        }
293        Err(_) => {
294            set_last_error("codec panicked".into());
295            Err(())
296        }
297    }
298}
299
300/// Hand a Vec's buffer to the caller: leaks capacity semantics are
301/// fine — `ozip_free` reconstructs the Vec with len == capacity.
302fn ozip_take(mut v: Vec<u8>) -> *mut u8 {
303    let ptr = v.as_mut_ptr();
304    let len = v.len();
305    let cap = v.capacity();
306    // Normalization: reallocating to cap == len guarantees
307    // `Vec::from_raw_parts(buf, len, len)` in `ozip_free` is always
308    // sound, whatever the growth history was.
309    if cap != len {
310        let exact = v.clone();
311        drop(v);
312        return ozip_take(exact);
313    }
314    std::mem::forget(v);
315    ptr
316}
317
318/// An opened archive: one `ArchiveReader` (any supported format,
319/// auto-detected) plus its materialized entry list. Opaque handle for
320/// the archive-level FFI surface — the gem's whole-archive
321/// operations (list entries, read entry) ride this instead of
322/// decoding entry-by-entry through codec names.
323pub struct ArchHandle {
324    reader: Box<dyn omnizip_archive_core::ArchiveReader>,
325    entries: Vec<omnizip_archive_core::ArchiveEntry>,
326    last_name: CString,
327}
328
329fn open_archive_reader(
330    data: &[u8],
331    password: Option<&str>,
332) -> Result<Box<dyn omnizip_archive_core::ArchiveReader>, String> {
333    use omnizip_archive_core::detect::{detect_format, FormatKind};
334    let pw = password;
335    match detect_format(data) {
336        FormatKind::Zip => Ok(Box::new(
337            omnizip_zip::ZipReader::from_bytes(data).map_err(|e| e.to_string())?,
338        )),
339        FormatKind::Tar => Ok(Box::new(
340            omnizip_tar::TarReader::from_bytes(data).map_err(|e| e.to_string())?,
341        )),
342        FormatKind::Cpio => Ok(Box::new(
343            omnizip_cpio::CpioReader::from_bytes(data).map_err(|e| e.to_string())?,
344        )),
345        FormatKind::SevenZip => Ok(Box::new(
346            omnizip_sevenzip::reader::SevenZipReader::from_bytes_with_password(data, pw)
347                .map_err(|e| e.to_string())?,
348        )),
349        FormatKind::Rar5 => match pw {
350            Some(p) => omnizip_rar::rar5::Rar5Reader::from_bytes_with_password(data, p)
351                .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>)
352                .map_err(|e| e.to_string()),
353            None => omnizip_rar::rar5::Rar5Reader::from_bytes(data)
354                .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>)
355                .map_err(|e| e.to_string()),
356        },
357        FormatKind::Rar4 => match pw {
358            Some(p) => omnizip_rar::rar3::Rar4Reader::from_bytes_with_password(data, p)
359                .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>)
360                .map_err(|e| e.to_string()),
361            None => omnizip_rar::rar3::Rar4Reader::from_bytes(data)
362                .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>)
363                .map_err(|e| e.to_string()),
364        },
365        // ISO/RPM/XAR/OLE have magic sniffing in their own crates'
366        // readers; detect_format's enum predates them. Try them in a
367        // fixed order for kinds the enum cannot express.
368        _ => {
369            for probe in [
370                omnizip_iso::reader::IsoReader::from_bytes(data)
371                    .ok()
372                    .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>),
373                omnizip_rpm::reader::RpmReader::from_bytes(data)
374                    .ok()
375                    .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>),
376                omnizip_xar::reader::XarReader::from_bytes(data)
377                    .ok()
378                    .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>),
379                omnizip_ole::reader::OleReader::from_bytes(data)
380                    .ok()
381                    .map(|r| Box::new(r) as Box<dyn omnizip_archive_core::ArchiveReader>),
382            ] {
383                if let Some(reader) = probe {
384                    return Ok(reader);
385                }
386            }
387            Err("unsupported archive format kind".into())
388        }
389    }
390}
391
392/// Open an archive from raw bytes (format auto-detected; optional
393/// NUL-terminated password). Returns NULL on error
394/// ([`ozip_last_error`]). Free with [`ozip_arch_close`].
395#[allow(unsafe_code)]
396#[no_mangle]
397pub unsafe extern "C" fn ozip_arch_open(
398    data: *const u8,
399    len: usize,
400    password: *const c_char,
401) -> *mut ArchHandle {
402    #[allow(unsafe_code)]
403    match unsafe { try_arch_open(data, len, password) } {
404        Ok(h) => Box::into_raw(h),
405        Err(()) => std::ptr::null_mut(),
406    }
407}
408
409#[allow(unsafe_code)]
410unsafe fn try_arch_open(
411    data: *const u8,
412    len: usize,
413    password: *const c_char,
414) -> Result<Box<ArchHandle>, ()> {
415    if data.is_null() {
416        set_last_error("arch data pointer is null".into());
417        return Err(());
418    }
419    // SAFETY: caller guarantees readability for `len` bytes.
420    let bytes = unsafe { std::slice::from_raw_parts(data, len) };
421    let pw = if password.is_null() {
422        None
423    } else {
424        // SAFETY: caller guarantees NUL termination.
425        Some(
426            unsafe { std::ffi::CStr::from_ptr(password) }
427                .to_string_lossy()
428                .into_owned(),
429        )
430    };
431    let result = std::panic::catch_unwind(|| {
432        let mut reader = open_archive_reader(bytes, pw.as_deref())?;
433        let entries = reader.entries().map_err(|e| format!("entries: {e}"))?;
434        Ok::<_, String>(ArchHandle {
435            reader,
436            entries,
437            last_name: CString::new("no entry").expect("static"),
438        })
439    });
440    match result {
441        Ok(Ok(mut h)) => {
442            h.last_name = CString::new("ok").expect("static");
443            Ok(Box::new(h))
444        }
445        Ok(Err(msg)) => {
446            set_last_error(msg);
447            Err(())
448        }
449        Err(_) => {
450            set_last_error("archive open panicked".into());
451            Err(())
452        }
453    }
454}
455
456/// Number of entries in the opened archive. 0 on NULL handle.
457#[allow(unsafe_code)]
458#[no_mangle]
459pub unsafe extern "C" fn ozip_arch_count(handle: *const ArchHandle) -> usize {
460    if handle.is_null() {
461        return 0;
462    }
463    // SAFETY: handle came from ozip_arch_open and was not closed.
464    (unsafe { &*handle }).entries.len()
465}
466
467/// Entry name (NUL-terminated, valid until the next call on this
468/// handle). NULL on out-of-range index.
469#[allow(unsafe_code)]
470#[no_mangle]
471pub unsafe extern "C" fn ozip_arch_entry_name(
472    handle: *mut ArchHandle,
473    index: usize,
474) -> *const c_char {
475    if handle.is_null() {
476        return std::ptr::null();
477    }
478    // SAFETY: handle came from ozip_arch_open and was not closed.
479    let h = unsafe { &mut *handle };
480    match h.entries.get(index) {
481        Some(e) => {
482            h.last_name = CString::new(e.name.clone())
483                .unwrap_or_else(|_| CString::new("bad name").expect("static"));
484            h.last_name.as_ptr()
485        }
486        None => std::ptr::null(),
487    }
488}
489
490/// Entry uncompressed size (u64). 0 on out-of-range.
491#[allow(unsafe_code)]
492#[no_mangle]
493pub unsafe extern "C" fn ozip_arch_entry_size(handle: *const ArchHandle, index: usize) -> u64 {
494    if handle.is_null() {
495        return 0;
496    }
497    // SAFETY: handle from ozip_arch_open.
498    (unsafe { &*handle })
499        .entries
500        .get(index)
501        .and_then(|e| e.size)
502        .unwrap_or(0)
503}
504
505/// Read one entry's uncompressed bytes; free the buffer with
506/// [`ozip_free`]. NULL on error.
507#[allow(unsafe_code)]
508#[no_mangle]
509pub unsafe extern "C" fn ozip_arch_read_entry(
510    handle: *mut ArchHandle,
511    index: usize,
512    out_len: *mut usize,
513) -> *mut u8 {
514    #[allow(unsafe_code)]
515    match unsafe { try_arch_read_entry(handle, index, out_len) } {
516        Ok(ptr) => ptr,
517        Err(()) => std::ptr::null_mut(),
518    }
519}
520
521#[allow(unsafe_code)]
522unsafe fn try_arch_read_entry(
523    handle: *mut ArchHandle,
524    index: usize,
525    out_len: *mut usize,
526) -> Result<*mut u8, ()> {
527    if handle.is_null() || out_len.is_null() {
528        set_last_error("arch read: null handle or out_len".into());
529        return Err(());
530    }
531    // SAFETY: handle from ozip_arch_open.
532    let h = unsafe { &mut *handle };
533    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
534        h.reader.read_entry(index).map_err(|e| e.to_string())
535    }));
536    match result {
537        Ok(Ok(out)) => {
538            // SAFETY: caller-provided writable slot.
539            unsafe { *out_len = out.len() };
540            Ok(ozip_take(out))
541        }
542        Ok(Err(msg)) => {
543            set_last_error(msg);
544            Err(())
545        }
546        Err(_) => {
547            set_last_error("entry read panicked".into());
548            Err(())
549        }
550    }
551}
552
553/// Close an archive handle (freeing it). NULL is a no-op.
554#[allow(unsafe_code)]
555#[no_mangle]
556pub unsafe extern "C" fn ozip_arch_close(handle: *mut ArchHandle) {
557    if !handle.is_null() {
558        // SAFETY: ownership transfers back exactly once.
559        drop(unsafe { Box::from_raw(handle) });
560    }
561}
562
563/// `ppmd7:o{order}:m{mem}` / `ppmd8:o{order}:m{mem}` — the gem's
564/// PPMd algorithms carry their parameters in the codec name (the FFI
565/// ABI has no params argument); `mem` is bytes.
566fn parse_ppmd_name(name: &str) -> Result<(u8, u8, usize), String> {
567    let bad = || format!("invalid ppmd codec name '{name}'");
568    let mut parts = name.split(':');
569    let variant = match parts.next() {
570        Some("ppmd7") => 7,
571        Some("ppmd8") => 8,
572        _ => return Err(bad()),
573    };
574    let order = parts
575        .next()
576        .and_then(|p| p.strip_prefix('o'))
577        .ok_or_else(bad)?;
578    let mem = parts
579        .next()
580        .and_then(|p| p.strip_prefix('m'))
581        .ok_or_else(bad)?;
582    if parts.next().is_some() {
583        return Err(bad());
584    }
585    let order: u8 = order.parse().map_err(|_| bad())?;
586    let mem: usize = mem.parse().map_err(|_| bad())?;
587    Ok((variant, order, mem))
588}
589
590struct PpmdAdapter7 {
591    order: u8,
592    mem: usize,
593}
594
595impl Codec for PpmdAdapter7 {
596    fn id(&self) -> omnizip_codecs::CodecId {
597        omnizip_codecs::CodecId::PPMD7
598    }
599    fn name(&self) -> &'static str {
600        "ppmd7"
601    }
602    fn compress(
603        &self,
604        plaintext: &[u8],
605        _level: CompressionLevel,
606    ) -> Result<Vec<u8>, OmnizipError> {
607        omnizip_ppmd::ppmd7::codec::compress_with_budget(plaintext, self.order, self.mem)
608            .map_err(map_ppmd_err)
609    }
610    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
611        omnizip_ppmd::ppmd7::codec::decompress_with_budget(
612            compressed,
613            expected_len as usize,
614            self.mem,
615        )
616        .map_err(map_ppmd_err)
617    }
618}
619
620struct PpmdAdapter8 {
621    order: u8,
622    mem: usize,
623}
624
625impl Codec for PpmdAdapter8 {
626    fn id(&self) -> omnizip_codecs::CodecId {
627        omnizip_codecs::CodecId::PPMD8
628    }
629    fn name(&self) -> &'static str {
630        "ppmd8"
631    }
632    fn compress(
633        &self,
634        plaintext: &[u8],
635        _level: CompressionLevel,
636    ) -> Result<Vec<u8>, OmnizipError> {
637        omnizip_ppmd::ppmd8::codec::compress_with_budget(plaintext, self.order, self.mem)
638            .map_err(map_ppmd_err)
639    }
640    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
641        omnizip_ppmd::ppmd8::codec::decompress_with_budget(
642            compressed,
643            expected_len as usize,
644            self.mem,
645        )
646        .map_err(map_ppmd_err)
647    }
648}
649
650fn map_ppmd_err(e: impl std::fmt::Display) -> OmnizipError {
651    OmnizipError::DecodeFailed {
652        codec: omnizip_codecs::CodecId::PPMD8,
653        reason: e.to_string(),
654    }
655}
656
657/// The gzip container (RFC 1952): header + raw deflate + CRC/ISIZE
658/// trailer — the Ruby gzip format wraps Zlib streams, and this name
659/// accelerates that whole-container path.
660struct GzipAdapter;
661
662impl Codec for GzipAdapter {
663    fn id(&self) -> omnizip_codecs::CodecId {
664        omnizip_codecs::CodecId::DEFLATE
665    }
666    fn name(&self) -> &'static str {
667        "gzip"
668    }
669    fn compress(&self, plaintext: &[u8], level: CompressionLevel) -> Result<Vec<u8>, OmnizipError> {
670        let opts = omnizip_archive_core::formats::gzip::GzipOptions {
671            level: level.as_u8().min(9),
672            ..Default::default()
673        };
674        omnizip_archive_core::formats::gzip::compress(plaintext, &opts).map_err(map_gzip_err)
675    }
676    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
677        let out =
678            omnizip_archive_core::formats::gzip::decompress(compressed).map_err(map_gzip_err)?;
679        let want = usize::try_from(expected_len).unwrap_or(usize::MAX);
680        if out.len() != want {
681            return Err(OmnizipError::LengthMismatch {
682                codec: omnizip_codecs::CodecId::DEFLATE,
683                expected: expected_len,
684                actual: out.len(),
685            });
686        }
687        Ok(out)
688    }
689}
690
691fn map_gzip_err(e: omnizip_archive_core::ArchiveError) -> OmnizipError {
692    OmnizipError::DecodeFailed {
693        codec: omnizip_codecs::CodecId::DEFLATE,
694        reason: e.to_string(),
695    }
696}
697
698/// The Ruby gem's Deflate algorithm speaks RAW RFC 1951 (its gzip
699/// format wraps the same raw stream in Ruby) — distinct from
700/// `DeflateCodec`, which wraps in zlib.
701struct RawDeflateAdapter;
702
703impl Codec for RawDeflateAdapter {
704    fn id(&self) -> omnizip_codecs::CodecId {
705        omnizip_codecs::CodecId::DEFLATE
706    }
707    fn name(&self) -> &'static str {
708        "deflate"
709    }
710    fn compress(&self, plaintext: &[u8], level: CompressionLevel) -> Result<Vec<u8>, OmnizipError> {
711        omnizip_libdeflate::compress_raw(plaintext, level.as_u8())
712    }
713    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
714        let out = omnizip_libdeflate::decompress_raw_unknown_len(compressed)?;
715        let want = usize::try_from(expected_len).unwrap_or(usize::MAX);
716        if out.len() != want {
717            return Err(OmnizipError::LengthMismatch {
718                codec: omnizip_codecs::CodecId::DEFLATE,
719                expected: expected_len,
720                actual: out.len(),
721            });
722        }
723        Ok(out)
724    }
725}
726
727/// The Ruby gem's LZMA algorithm emits LZMA1-alone streams (the
728/// 13-byte header carries lc/lp/pb/dict) — distinct from the XZ
729/// container that `LzmaCodec` speaks, hence a dedicated FFI name.
730struct LzmaAloneAdapter;
731
732impl Codec for LzmaAloneAdapter {
733    fn id(&self) -> omnizip_codecs::CodecId {
734        omnizip_codecs::CodecId::LZMA
735    }
736    fn name(&self) -> &'static str {
737        "lzma-alone"
738    }
739    fn compress(&self, plaintext: &[u8], level: CompressionLevel) -> Result<Vec<u8>, OmnizipError> {
740        let lv = level.as_u8().min(9);
741        let dict_size: u32 = [
742            1 << 16,
743            1 << 20,
744            1 << 21,
745            1 << 22,
746            1 << 22,
747            1 << 23,
748            1 << 23,
749            1 << 24,
750            1 << 25,
751            1 << 26,
752        ][usize::from(lv)];
753        let opts = omnizip_lzma::LzmaOptions {
754            dict_size,
755            ..Default::default()
756        };
757        omnizip_lzma::lzma_alone_compress_with_options(plaintext, &opts).map_err(map_lzma_err)
758    }
759    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
760        let out = omnizip_lzma::lzma_alone_decompress(compressed).map_err(map_lzma_err)?;
761        check_expected(out.len(), expected_len, "lzma-alone")?;
762        Ok(out)
763    }
764}
765
766/// lzip member decode (the trailer carries the plaintext size);
767/// compression is not offered through the FFI.
768struct LzipAdapter;
769
770impl Codec for LzipAdapter {
771    fn id(&self) -> omnizip_codecs::CodecId {
772        omnizip_codecs::CodecId::LZMA
773    }
774    fn name(&self) -> &'static str {
775        "lzip"
776    }
777    fn compress(
778        &self,
779        _plaintext: &[u8],
780        _level: CompressionLevel,
781    ) -> Result<Vec<u8>, OmnizipError> {
782        Err(OmnizipError::Unsupported {
783            codec: omnizip_codecs::CodecId::LZMA,
784            reason: "lzip compression is not available through the FFI".into(),
785        })
786    }
787    fn decompress(&self, compressed: &[u8], expected_len: u32) -> Result<Vec<u8>, OmnizipError> {
788        let out = omnizip_lzma::lzip_decompress(compressed).map_err(map_lzma_err)?;
789        check_expected(out.len(), expected_len, "lzip")?;
790        Ok(out)
791    }
792}
793
794fn map_lzma_err(e: omnizip_lzma::LzmaError) -> OmnizipError {
795    OmnizipError::DecodeFailed {
796        codec: omnizip_codecs::CodecId::LZMA,
797        reason: e.to_string(),
798    }
799}
800
801fn check_expected(got: usize, expected: u32, codec: &str) -> Result<(), OmnizipError> {
802    let want = usize::try_from(expected).unwrap_or(usize::MAX);
803    if got != want {
804        return Err(OmnizipError::Corrupt {
805            codec: omnizip_codecs::CodecId::LZMA,
806            reason: format!("{codec}: expected {want} bytes, decoded {got}"),
807        });
808    }
809    Ok(())
810}
811
812#[cfg(test)]
813#[allow(unsafe_code)]
814mod tests {
815    use super::*;
816    use std::ffi::CString;
817
818    #[test]
819    fn version_is_nul_terminated_semver() {
820        let p = ozip_version();
821        assert!(!p.is_null());
822        let s = unsafe { std::ffi::CStr::from_ptr(p) }
823            .to_string_lossy()
824            .into_owned();
825        assert_eq!(s, env!("CARGO_PKG_VERSION"));
826        assert!(
827            s.split('.').count() >= 3,
828            "semver, not a pointer-to-garbage"
829        );
830    }
831
832    fn roundtrip(codec_name: &str, level: u8, data: &[u8]) {
833        let name = CString::new(codec_name).unwrap();
834        let mut out_len = 0_usize;
835        let ptr = unsafe {
836            ozip_compress(
837                name.as_ptr(),
838                data.as_ptr(),
839                data.len(),
840                level,
841                &mut out_len,
842            )
843        };
844        assert!(
845            !ptr.is_null(),
846            "{} compress failed: {}",
847            codec_name,
848            unsafe { std::ffi::CStr::from_ptr(ozip_last_error()).to_string_lossy() }
849        );
850        let mut dec_len = 0_usize;
851        let dec = unsafe { ozip_decompress(name.as_ptr(), ptr, out_len, data.len(), &mut dec_len) };
852        assert!(
853            !dec.is_null(),
854            "{} decompress failed: {}",
855            codec_name,
856            unsafe { std::ffi::CStr::from_ptr(ozip_last_error()).to_string_lossy() }
857        );
858        let restored = unsafe { std::slice::from_raw_parts(dec, dec_len) };
859        assert_eq!(restored, data, "{codec_name} roundtrip");
860        unsafe { ozip_free(ptr, out_len) };
861        unsafe { ozip_free(dec, dec_len) };
862    }
863
864    fn sample(len: usize) -> Vec<u8> {
865        (0..len)
866            .map(|i| u8::try_from(i % 251).expect("<251"))
867            .collect()
868    }
869
870    #[test]
871    fn roundtrips_all_codecs() {
872        roundtrip("zstd", 6, &sample(50_000));
873        roundtrip("bzip2", 9, &sample(50_000));
874        roundtrip("lzma", 6, &sample(50_000));
875        roundtrip("xz", 6, &sample(1000)); // alias
876        roundtrip("deflate", 6, &sample(50_000));
877        roundtrip("deflate64", 6, &sample(50_000));
878        roundtrip("lzma-alone", 6, &sample(50_000));
879        roundtrip("zlib", 6, &sample(50_000));
880        roundtrip("gzip", 6, &sample(50_000));
881        // Param-carrying PPMd names (order + mem bytes in the name).
882        roundtrip("ppmd7:o6:m16777216", 0, &sample(20_000));
883        roundtrip("ppmd8:o6:m16777216", 0, &sample(20_000));
884    }
885
886    #[test]
887    fn lzip_decodes_unknown_length() {
888        use std::ffi::CStr;
889        // The good-1-v1 fixture from the lzip conformance set (the
890        // same corpus omnizip-lzma's own lzip tests decode).
891        let lzip_stream = std::fs::read(concat!(
892            env!("CARGO_MANIFEST_DIR"),
893            "/../tests/fixtures/lzma/good-1-v1.lz"
894        ))
895        .unwrap();
896        let expected = omnizip_lzma::lzip_decompress(&lzip_stream).unwrap();
897        assert!(!expected.is_empty());
898        let name = CString::new("lzip").unwrap();
899        let mut dec_len = 0_usize;
900        let dec = unsafe {
901            ozip_decompress(
902                name.as_ptr(),
903                lzip_stream.as_ptr(),
904                lzip_stream.len(),
905                usize::MAX,
906                &mut dec_len,
907            )
908        };
909        assert!(!dec.is_null(), "lzip decode failed: {}", unsafe {
910            CStr::from_ptr(ozip_last_error()).to_string_lossy()
911        });
912        let restored = unsafe { std::slice::from_raw_parts(dec, dec_len) };
913        assert_eq!(restored, &expected[..]);
914        unsafe { ozip_free(dec, dec_len) };
915    }
916
917    #[test]
918    fn unknown_length_paths_cover_new_codecs() {
919        use std::ffi::CStr;
920        for (name, encoded) in [
921            (
922                "deflate",
923                omnizip_libdeflate::compress_raw(&sample(20_000), 6).unwrap(),
924            ),
925            (
926                "deflate64",
927                omnizip_deflate64::Deflate64Codec
928                    .compress(&sample(20_000), CompressionLevel::new(6))
929                    .unwrap(),
930            ),
931            (
932                "lzma-alone",
933                omnizip_lzma::lzma_alone_compress_with_options(
934                    &sample(20_000),
935                    &omnizip_lzma::LzmaOptions::default(),
936                )
937                .unwrap(),
938            ),
939            (
940                "zlib",
941                omnizip_libdeflate::LibdeflateCodec
942                    .compress(&sample(20_000), CompressionLevel::new(6))
943                    .unwrap(),
944            ),
945            ("gzip", {
946                let opts = omnizip_archive_core::formats::gzip::GzipOptions::default();
947                omnizip_archive_core::formats::gzip::compress(&sample(20_000), &opts).unwrap()
948            }),
949        ] {
950            let cname = CString::new(name).unwrap();
951            let mut dec_len = 0_usize;
952            let dec = unsafe {
953                ozip_decompress(
954                    cname.as_ptr(),
955                    encoded.as_ptr(),
956                    encoded.len(),
957                    usize::MAX,
958                    &mut dec_len,
959                )
960            };
961            assert!(
962                !dec.is_null(),
963                "{name} unknown-length decode failed: {}",
964                unsafe { CStr::from_ptr(ozip_last_error()).to_string_lossy() }
965            );
966            let restored = unsafe { std::slice::from_raw_parts(dec, dec_len) };
967            assert_eq!(restored.len(), 20_000, "{name} length");
968            unsafe { ozip_free(dec, dec_len) };
969        }
970    }
971
972    #[test]
973    fn empty_and_tiny_inputs() {
974        roundtrip("zstd", 3, &[]);
975        roundtrip("bzip2", 1, b"x");
976    }
977
978    fn zip_archive() -> Vec<u8> {
979        use omnizip_archive_core::{NewEntry, WriteOptions};
980        use omnizip_zip::{ZipMethod, ZipWriter};
981        let mut w = ZipWriter::new();
982        let opts = WriteOptions::default();
983        let body: Vec<u8> = (0..30_000u32).map(|i| (i % 251) as u8).collect();
984        let p = ZipWriter::prepare(ZipMethod::Deflate, &body).unwrap();
985        w.add_file_prepared(&NewEntry::file("a.bin", &opts), &p, &opts)
986            .unwrap();
987        let p2 = ZipWriter::prepare(ZipMethod::Deflate, b"hello archive tier").unwrap();
988        w.add_file_prepared(&NewEntry::file("b.txt", &opts), &p2, &opts)
989            .unwrap();
990        w.finish_bytes().unwrap()
991    }
992
993    #[test]
994    fn archive_handle_round_trips() {
995        use std::ffi::CStr;
996        let bytes = zip_archive();
997        let h = unsafe { ozip_arch_open(bytes.as_ptr(), bytes.len(), std::ptr::null()) };
998        assert!(!h.is_null(), "arch open failed: {}", unsafe {
999            CStr::from_ptr(ozip_last_error()).to_string_lossy()
1000        });
1001        assert_eq!(unsafe { ozip_arch_count(h) }, 2);
1002        let n = unsafe { ozip_arch_entry_name(h, 0) };
1003        assert_eq!(unsafe { CStr::from_ptr(n) }.to_bytes(), b"a.bin");
1004        assert_eq!(unsafe { ozip_arch_entry_size(h, 0) }, 30_000);
1005        let mut out_len = 0usize;
1006        let buf = unsafe { ozip_arch_read_entry(h, 0, &mut out_len) };
1007        assert!(!buf.is_null());
1008        assert_eq!(out_len, 30_000);
1009        let restored = unsafe { std::slice::from_raw_parts(buf, out_len) };
1010        assert_eq!(restored.len(), 30_000);
1011        unsafe { ozip_free(buf, out_len) };
1012        let mut l2 = 0usize;
1013        let b2 = unsafe { ozip_arch_read_entry(h, 1, &mut l2) };
1014        assert_eq!(
1015            unsafe { std::slice::from_raw_parts(b2, l2) },
1016            b"hello archive tier"
1017        );
1018        unsafe { ozip_free(b2, l2) };
1019        unsafe { ozip_arch_close(h) };
1020    }
1021
1022    #[test]
1023    fn archive_handle_fuzz_no_panics() {
1024        let bytes = zip_archive();
1025        let mut rng = 0xC0DE_AAAAu64;
1026        let mut next = move || {
1027            rng ^= rng << 13;
1028            rng ^= rng >> 7;
1029            rng ^= rng << 17;
1030            rng
1031        };
1032        for case in 0..600 {
1033            let mut input = bytes.clone();
1034            let flips = 1 + (next() % 8) as usize;
1035            for _ in 0..flips {
1036                let pos = (next() as usize) % input.len();
1037                input[pos] ^= (next() % 255 + 1) as u8;
1038            }
1039            let r = std::panic::catch_unwind(|| {
1040                let h = unsafe { ozip_arch_open(input.as_ptr(), input.len(), std::ptr::null()) };
1041                if !h.is_null() {
1042                    unsafe {
1043                        let count = ozip_arch_count(h);
1044                        for i in 0..count.min(4) {
1045                            let mut l = 0usize;
1046                            let b = ozip_arch_read_entry(h, i, &mut l);
1047                            if !b.is_null() {
1048                                ozip_free(b, l);
1049                            }
1050                        }
1051                        ozip_arch_close(h);
1052                    }
1053                }
1054            });
1055            assert!(r.is_ok(), "case {case} panicked");
1056        }
1057    }
1058
1059    #[test]
1060    fn unknown_codec_sets_last_error() {
1061        let name = CString::new("nope").unwrap();
1062        let mut out_len = 0_usize;
1063        let ptr = unsafe { ozip_compress(name.as_ptr(), b"".as_ptr(), 0, 1, &mut out_len) };
1064        assert!(ptr.is_null());
1065        let err = unsafe { std::ffi::CStr::from_ptr(ozip_last_error()) }
1066            .to_string_lossy()
1067            .into_owned();
1068        assert!(err.contains("unknown codec 'nope'"), "{err}");
1069        assert!(err.contains("zstd"), "{err}");
1070    }
1071
1072    #[test]
1073    fn unknown_length_decodes_all_codecs() {
1074        for codec in ["zstd", "bzip2", "lzma"] {
1075            let name = CString::new(codec).unwrap();
1076            let data = sample(5000);
1077            let mut out_len = 0_usize;
1078            let ptr =
1079                unsafe { ozip_compress(name.as_ptr(), data.as_ptr(), data.len(), 6, &mut out_len) };
1080            assert!(!ptr.is_null());
1081            let mut dec_len = 0_usize;
1082            let dec =
1083                unsafe { ozip_decompress(name.as_ptr(), ptr, out_len, usize::MAX, &mut dec_len) };
1084            assert!(!dec.is_null(), "{codec}: {}", unsafe {
1085                std::ffi::CStr::from_ptr(ozip_last_error()).to_string_lossy()
1086            });
1087            assert_eq!(
1088                unsafe { std::slice::from_raw_parts(dec, dec_len) },
1089                data.as_slice(),
1090                "{codec} unknown-length decode"
1091            );
1092            unsafe { ozip_free(ptr, out_len) };
1093            unsafe { ozip_free(dec, dec_len) };
1094        }
1095    }
1096
1097    #[test]
1098    fn wrong_expected_len_errors() {
1099        let name = CString::new("zstd").unwrap();
1100        let data = sample(1000);
1101        let mut out_len = 0_usize;
1102        let ptr =
1103            unsafe { ozip_compress(name.as_ptr(), data.as_ptr(), data.len(), 3, &mut out_len) };
1104        assert!(!ptr.is_null());
1105        let mut dec_len = 0_usize;
1106        let dec = unsafe { ozip_decompress(name.as_ptr(), ptr, out_len, 999, &mut dec_len) };
1107        assert!(dec.is_null());
1108        let err = unsafe { std::ffi::CStr::from_ptr(ozip_last_error()) }
1109            .to_string_lossy()
1110            .into_owned();
1111        assert!(
1112            err.to_lowercase().contains("length") || err.to_lowercase().contains("size"),
1113            "{err}"
1114        );
1115        unsafe { ozip_free(ptr, out_len) };
1116    }
1117}