ctb_formats_compression/
compression.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Single-stream compression algorithms (Brotli, Gzip, Deflate, Zlib, SCO Compress -H, etc.).
21
22use ctb_formats_compression_bzip as bzip;
23use ctb_formats_utilities::extension_data::lookup_format_by_extension;
24use ctb_formats_utilities::format_id::FormatId;
25use ctb_formats_utilities::format_info::FormatInfoOptionExt;
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace crate prelude"
30)]
31pub(crate) use ctb_utilities::*;
32
33use std::io::{Read, Write};
34
35pub use ctb_formats_compression_compact as compact;
36pub use ctb_formats_compression_compress as compress;
37pub use ctb_formats_compression_freeze as freeze;
38pub use ctb_formats_compression_libraries as libraries;
39pub use ctb_formats_compression_pack as pack;
40pub use ctb_formats_compression_rzip as rzip;
41pub use ctb_formats_compression_sco_compress as sco_compress;
42pub use ctb_formats_compression_szip as szip;
43
44/// Returns a fixture asset byte vector if present.
45pub fn get_compression_data(key: &str) -> Option<Vec<u8>> {
46    ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
47}
48
49/// Ordered list of all compression formats supported by this crate.
50pub const SUPPORTED: &[FormatId] = SupportedDecompressionFormat::ALL_FORMAT_IDS;
51
52/// Returns true if the given `FormatId` is supported for compression/decompression by this crate.
53#[must_use]
54pub fn is_supported(format: FormatId) -> bool {
55    SupportedDecompressionFormat::is_supported(format)
56}
57
58/// Generates a detailed help table of supported compression formats and their shorthand aliases.
59pub fn format_help_table() -> String {
60    ctb_formats_utilities::format_help_table(
61        "Supported compression formats:",
62        SUPPORTED,
63    )
64}
65
66/// Global static lazy string containing the formatted compression help table.
67pub static COMPRESSION_AFTER_HELP: std::sync::LazyLock<String> =
68    std::sync::LazyLock::new(format_help_table);
69
70/// Extension trait adding compression-specific utilities to [`FormatId`].
71pub trait CompressionFormatExt {
72    /// Retrieves format metadata from the shared registry.
73    fn format_info(&self)
74    -> Option<&'static ctb_formats_utilities::FormatInfo>;
75
76    /// Returns the standard default file extension associated with the format.
77    fn extension(&self) -> &'static str;
78
79    /// Returns true if this compression format is implemented natively in this
80    /// repository, rather than being provided by an external crate.
81    fn is_implemented_in_repo(&self) -> bool;
82
83    /// Returns the default verification setting for this format when compressing.
84    /// In-tree implementations default to verifying output, while external crate
85    /// implementations default to not verifying.
86    fn default_verify(&self) -> bool;
87}
88
89impl CompressionFormatExt for FormatId {
90    fn format_info(
91        &self,
92    ) -> Option<&'static ctb_formats_utilities::FormatInfo> {
93        ctb_formats_utilities::get_format_info_by_id(*self)
94    }
95
96    fn extension(&self) -> &'static str {
97        // Reason for fallback: default to generic "bin" when format metadata has no primary extension
98        self.format_info().get_primary_extension().unwrap_or("bin")
99    }
100
101    fn is_implemented_in_repo(&self) -> bool {
102        matches!(
103            self,
104            Self::Bzip
105                | Self::ScoCompress
106                | Self::CompressLzw
107                | Self::CompressLzw2
108                | Self::CompressLzw1
109                | Self::CompressLzw16
110                | Self::Pack
111                | Self::OldPack
112                | Self::Compact
113                | Self::Freeze2
114                | Self::Freeze1
115                | Self::Rzip
116                | Self::Szip
117                | Self::Szip111
118        )
119    }
120
121    fn default_verify(&self) -> bool {
122        self.is_implemented_in_repo()
123    }
124}
125
126impl CompressionFormatExt for SupportedCompressionFormat {
127    fn format_info(
128        &self,
129    ) -> Option<&'static ctb_formats_utilities::FormatInfo> {
130        self.to_format_id().format_info()
131    }
132
133    fn extension(&self) -> &'static str {
134        self.to_format_id().extension()
135    }
136
137    fn is_implemented_in_repo(&self) -> bool {
138        self.to_format_id().is_implemented_in_repo()
139    }
140
141    fn default_verify(&self) -> bool {
142        self.to_format_id().default_verify()
143    }
144}
145
146impl CompressionFormatExt for SupportedDecompressionFormat {
147    fn format_info(
148        &self,
149    ) -> Option<&'static ctb_formats_utilities::FormatInfo> {
150        self.to_format_id().format_info()
151    }
152
153    fn extension(&self) -> &'static str {
154        self.to_format_id().extension()
155    }
156
157    fn is_implemented_in_repo(&self) -> bool {
158        self.to_format_id().is_implemented_in_repo()
159    }
160
161    fn default_verify(&self) -> bool {
162        self.to_format_id().default_verify()
163    }
164}
165
166/// Parses a compression format from a format name or extension.
167pub fn parse_compression_format(s: &str) -> Result<SupportedCompressionFormat> {
168    let trimmed = s.trim();
169    if trimmed.contains('/') || trimmed.contains('\\') {
170        bail!("Unknown compression format: '{s}'");
171    }
172    let clean = trimmed.trim_start_matches('.');
173    if let Ok(fmt) = SupportedCompressionFormat::try_from(clean) {
174        return Ok(fmt);
175    }
176    for fid in lookup_format_by_extension(clean) {
177        if let Ok(fmt) = fid.to_supported_compression_format() {
178            return Ok(fmt);
179        }
180    }
181    for &fid in SUPPORTED {
182        if let Some(info) = fid.format_info() {
183            for nick in info.sorted_nicknames() {
184                if nick.eq_ignore_ascii_case(clean) {
185                    return fid.to_supported_compression_format();
186                }
187            }
188        }
189    }
190    bail!("Unknown compression format: '{s}'")
191}
192
193/// Parses a decompression format from a format name or extension.
194pub fn parse_decompression_format(
195    s: &str,
196) -> Result<SupportedDecompressionFormat> {
197    let trimmed = s.trim();
198    if trimmed.contains('/') || trimmed.contains('\\') {
199        bail!("Unknown decompression format: '{s}'");
200    }
201    let clean = trimmed.trim_start_matches('.');
202    if let Ok(fmt) = SupportedDecompressionFormat::try_from(clean) {
203        return Ok(fmt);
204    }
205    for fid in lookup_format_by_extension(clean) {
206        if let Ok(fmt) = fid.to_supported_decompression_format() {
207            return Ok(fmt);
208        }
209    }
210    for &fid in SUPPORTED {
211        if let Some(info) = fid.format_info() {
212            for nick in info.sorted_nicknames() {
213                if nick.eq_ignore_ascii_case(clean) {
214                    return fid.to_supported_decompression_format();
215                }
216            }
217        }
218    }
219    bail!("Unknown decompression format: '{s}'")
220}
221
222/// Compresses a stream from `reader` directly into `writer` without verification.
223pub fn compress_stream_direct(
224    reader: &mut impl Read,
225    writer: &mut impl Write,
226    format: SupportedCompressionFormat,
227) -> Result<u64> {
228    match format {
229        SupportedCompressionFormat::Bzip => {
230            bzip::compress_stream(reader, writer)
231        }
232        SupportedCompressionFormat::ScoCompress => {
233            sco_compress::compress_stream(reader, writer)
234        }
235        SupportedCompressionFormat::CompressLzw
236        | SupportedCompressionFormat::CompressLzw2
237        | SupportedCompressionFormat::CompressLzw1
238        | SupportedCompressionFormat::CompressLzw16 => {
239            compress::compress_lzw_stream(reader, writer, format.to_format_id())
240        }
241        SupportedCompressionFormat::Pack => {
242            pack::compress_pack_stream(reader, writer)
243        }
244        SupportedCompressionFormat::OldPack => {
245            pack::compress_old_pack_stream(reader, writer)
246        }
247        SupportedCompressionFormat::Compact => {
248            compact::compress_compact_stream(reader, writer)
249        }
250        SupportedCompressionFormat::Freeze2 => {
251            freeze::compress_freeze2_stream(reader, writer)
252        }
253        SupportedCompressionFormat::Freeze1 => {
254            freeze::compress_freeze1_stream(reader, writer)
255        }
256        SupportedCompressionFormat::Rzip => {
257            rzip::compress_stream(reader, writer)
258        }
259        SupportedCompressionFormat::Szip
260        | SupportedCompressionFormat::Szip111 => {
261            szip::compress_stream(reader, writer)
262        }
263        SupportedCompressionFormat::Brotli
264        | SupportedCompressionFormat::Gzip
265        | SupportedCompressionFormat::Deflate
266        | SupportedCompressionFormat::Zlib
267        | SupportedCompressionFormat::Bzip2
268        | SupportedCompressionFormat::Lz4
269        | SupportedCompressionFormat::Xz
270        | SupportedCompressionFormat::Lzip
271        | SupportedCompressionFormat::Lzma
272        | SupportedCompressionFormat::Lzma2
273        | SupportedCompressionFormat::Zstd
274        | SupportedCompressionFormat::Lzo => {
275            libraries::compress_stream(reader, writer, format.to_format_id())
276        }
277    }
278}
279
280/// Compresses a stream from `reader` into `writer` using the specified algorithm format and verification option.
281pub fn compress_stream_with_verify(
282    reader: &mut impl Read,
283    writer: &mut impl Write,
284    format: SupportedCompressionFormat,
285    verify: bool,
286) -> Result<u64> {
287    if !verify {
288        return compress_stream_direct(reader, writer, format);
289    }
290
291    let mut input_data = Vec::new();
292    reader
293        .read_to_end(&mut input_data)
294        .context("Failed to read input stream for verified compression")?;
295
296    let mut compressed_buf = Vec::new();
297    compress_stream_direct(
298        &mut input_data.as_slice(),
299        &mut compressed_buf,
300        format,
301    )?;
302
303    let decomp_format =
304        format.to_format_id().to_supported_decompression_format()?;
305    let mut decompressed_buf = Vec::new();
306    decompress_stream(
307        &mut compressed_buf.as_slice(),
308        &mut decompressed_buf,
309        decomp_format,
310    )
311    .context("Verification failed: unable to decompress compressed stream")?;
312
313    if decompressed_buf != input_data {
314        bail!(
315            "Verification failed: decompressed data does not match input for format {format:?}"
316        );
317    }
318
319    writer
320        .write_all(&compressed_buf)
321        .context("Failed to write verified compressed stream")?;
322
323    Ok(u64::try_from(input_data.len())?)
324}
325
326/// Compresses a stream from `reader` into `writer` using the specified algorithm format.
327/// Uses the format's default verification setting (verify for in-repo formats, no-verify for crates).
328pub fn compress_stream(
329    reader: &mut impl Read,
330    writer: &mut impl Write,
331    format: SupportedCompressionFormat,
332) -> Result<u64> {
333    compress_stream_with_verify(reader, writer, format, format.default_verify())
334}
335
336/// Decompresses a stream from `reader` into `writer` using the specified algorithm format.
337pub fn decompress_stream(
338    reader: &mut impl Read,
339    writer: &mut impl Write,
340    format: SupportedDecompressionFormat,
341) -> Result<u64> {
342    match format {
343        SupportedDecompressionFormat::Bzip => {
344            bzip::decompress_stream(reader, writer)
345        }
346        SupportedDecompressionFormat::ScoCompress => {
347            sco_compress::decompress_stream(reader, writer)
348        }
349        SupportedDecompressionFormat::CompressLzw
350        | SupportedDecompressionFormat::CompressLzw2
351        | SupportedDecompressionFormat::CompressLzw1
352        | SupportedDecompressionFormat::CompressLzw16 => {
353            compress::decompress_lzw_stream(
354                reader,
355                writer,
356                format.to_format_id(),
357            )
358        }
359        SupportedDecompressionFormat::Pack => {
360            pack::decompress_pack_stream(reader, writer)
361        }
362        SupportedDecompressionFormat::OldPack => {
363            pack::decompress_old_pack_stream(reader, writer)
364        }
365        SupportedDecompressionFormat::Compact => {
366            compact::decompress_compact_stream(reader, writer)
367        }
368        SupportedDecompressionFormat::Freeze2 => {
369            freeze::decompress_freeze2_stream(reader, writer)
370        }
371        SupportedDecompressionFormat::Freeze1 => {
372            freeze::decompress_freeze1_stream(reader, writer)
373        }
374        SupportedDecompressionFormat::Rzip => {
375            rzip::decompress_stream(reader, writer)
376        }
377        SupportedDecompressionFormat::Szip
378        | SupportedDecompressionFormat::Szip111 => {
379            szip::decompress_stream(reader, writer)
380        }
381        SupportedDecompressionFormat::Brotli
382        | SupportedDecompressionFormat::Gzip
383        | SupportedDecompressionFormat::Deflate
384        | SupportedDecompressionFormat::Zlib
385        | SupportedDecompressionFormat::Bzip2
386        | SupportedDecompressionFormat::Lz4
387        | SupportedDecompressionFormat::Xz
388        | SupportedDecompressionFormat::Lzip
389        | SupportedDecompressionFormat::Lzma
390        | SupportedDecompressionFormat::Lzma2
391        | SupportedDecompressionFormat::Zstd
392        | SupportedDecompressionFormat::Lzo => {
393            libraries::decompress_stream(reader, writer, format.to_format_id())
394        }
395    }
396}
397
398/// Compresses in-memory byte slice using the specified compression format and verification option.
399pub fn compress_with_verify(
400    data: &[u8],
401    format: SupportedCompressionFormat,
402    verify: bool,
403) -> Result<Vec<u8>> {
404    let mut input = data;
405    let mut output = Vec::new();
406    compress_stream_with_verify(&mut input, &mut output, format, verify)?;
407    Ok(output)
408}
409
410/// Compresses in-memory byte slice using the specified compression format.
411/// Uses the format's default verification setting (verify for in-repo formats, no-verify for crates).
412pub fn compress(
413    data: &[u8],
414    format: SupportedCompressionFormat,
415) -> Result<Vec<u8>> {
416    compress_with_verify(data, format, format.default_verify())
417}
418
419/// Decompresses in-memory byte slice using the specified compression format.
420pub fn decompress(
421    data: &[u8],
422    format: SupportedDecompressionFormat,
423) -> Result<Vec<u8>> {
424    let mut input = data;
425    let mut output = Vec::new();
426    decompress_stream(&mut input, &mut output, format)?;
427    Ok(output)
428}
429
430#[cfg(test)]
431#[allow(
432    clippy::panic,
433    clippy::expect_used,
434    clippy::unwrap_used,
435    clippy::unwrap_in_result,
436    clippy::panic_in_result_fn,
437    clippy::indexing_slicing,
438    clippy::arithmetic_side_effects,
439    reason = "Standard repository test boilerplate"
440)]
441mod tests {
442    use super::*;
443
444    #[crate::ctb_test]
445    fn test_alias_sorting() {
446        let sco = FormatId::ScoCompress.format_info().unwrap();
447        assert_eq!(
448            sco.sorted_nicknames(),
449            vec!["compress-h", "compress-sco", "sco-compress"]
450        );
451
452        let zlib = FormatId::Zlib.format_info().unwrap();
453        assert_eq!(
454            zlib.sorted_nicknames(),
455            vec!["zl", "zz", "zlib", "zlib-deflate"]
456        );
457    }
458
459    #[crate::ctb_test]
460    fn test_format_help_table() {
461        let table = format_help_table();
462        assert!(table.contains("Supported compression formats:"));
463        assert!(table.contains("  br, brotli: Brotli compressed stream"));
464        assert!(table.contains("  gz, gzip: GNU gzip format"));
465        assert!(table.contains("  compress-h, compress-sco, sco-compress: `compress`: SCO `compress -H` format"));
466    }
467
468    #[crate::ctb_test]
469    fn test_default_verify_and_in_repo() {
470        let repo_formats = [
471            FormatId::Bzip,
472            FormatId::ScoCompress,
473            FormatId::CompressLzw,
474            FormatId::CompressLzw2,
475            FormatId::CompressLzw1,
476            FormatId::CompressLzw16,
477            FormatId::Pack,
478            FormatId::OldPack,
479            FormatId::Compact,
480            FormatId::Freeze2,
481            FormatId::Freeze1,
482            FormatId::Rzip,
483            FormatId::Szip,
484            FormatId::Szip111,
485        ];
486        let crate_formats = [
487            FormatId::Brotli,
488            FormatId::Gzip,
489            FormatId::Deflate,
490            FormatId::Zlib,
491            FormatId::Bzip2,
492            FormatId::Lz4,
493            FormatId::Lzma,
494            FormatId::Lzma2,
495            FormatId::Lzip,
496            FormatId::Xz,
497            FormatId::Zstd,
498            FormatId::Lzo,
499        ];
500
501        for fmt in repo_formats {
502            assert!(
503                fmt.is_implemented_in_repo(),
504                "Expected {fmt:?} to be marked as in-repo"
505            );
506            assert!(
507                fmt.default_verify(),
508                "Expected {fmt:?} to default verify to true"
509            );
510        }
511
512        for fmt in crate_formats {
513            assert!(
514                !fmt.is_implemented_in_repo(),
515                "Expected {fmt:?} to be marked as crate"
516            );
517            assert!(
518                !fmt.default_verify(),
519                "Expected {fmt:?} to default verify to false"
520            );
521        }
522    }
523
524    #[crate::ctb_test]
525    fn test_compress_stream_with_verify_toggle() {
526        let data = b"The quick brown fox jumps over the lazy dog. 1234567890!";
527        for &fmt in SUPPORTED {
528            let comp_fmt = fmt.to_supported_compression_format().unwrap();
529            let decomp_fmt = fmt.to_supported_decompression_format().unwrap();
530            // Test with verify = false
531            let compressed_unverified =
532                compress_with_verify(data, comp_fmt, false).unwrap();
533            let decompressed =
534                decompress(&compressed_unverified, decomp_fmt).unwrap();
535            assert_eq!(
536                decompressed, data,
537                "Failed roundtrip with verify=false for format {fmt:?}"
538            );
539
540            // Test with verify = true
541            let compressed_verified =
542                compress_with_verify(data, comp_fmt, true).unwrap();
543            let decompressed =
544                decompress(&compressed_verified, decomp_fmt).unwrap();
545            assert_eq!(
546                decompressed, data,
547                "Failed roundtrip with verify=true for format {fmt:?}"
548            );
549        }
550    }
551
552    #[crate::ctb_test]
553    fn test_all_format_aliases_parsing() {
554        for &fmt in SUPPORTED {
555            let info = fmt.format_info().expect("format info must exist");
556            for alias in &info.sorted_nicknames() {
557                let parsed = parse_compression_format(alias.as_str())
558                    .unwrap_or_else(|_| {
559                        panic!(
560                            "Failed to parse alias '{alias}' for format {fmt:?}"
561                        )
562                    });
563                assert_eq!(parsed.to_format_id(), fmt);
564            }
565        }
566    }
567
568    #[crate::ctb_test]
569    fn test_format_extensions_and_parsing() {
570        assert_eq!(
571            parse_compression_format("brotli").unwrap().to_format_id(),
572            FormatId::Brotli
573        );
574        assert_eq!(
575            parse_compression_format("bzip2").unwrap().to_format_id(),
576            FormatId::Bzip2
577        );
578        assert_eq!(
579            parse_compression_format("bzip").unwrap().to_format_id(),
580            FormatId::Bzip
581        );
582        assert_eq!(
583            parse_compression_format("bz").unwrap().to_format_id(),
584            FormatId::Bzip
585        );
586        assert_eq!(
587            parse_compression_format("compress2")
588                .unwrap()
589                .to_format_id(),
590            FormatId::CompressLzw2
591        );
592        assert_eq!(
593            parse_compression_format("pack").unwrap().to_format_id(),
594            FormatId::Pack
595        );
596        assert_eq!(
597            parse_compression_format("old-pack").unwrap().to_format_id(),
598            FormatId::OldPack
599        );
600        assert_eq!(
601            parse_compression_format("compact").unwrap().to_format_id(),
602            FormatId::Compact
603        );
604        assert_eq!(
605            parse_compression_format("lz4").unwrap().to_format_id(),
606            FormatId::Lz4
607        );
608        assert_eq!(
609            parse_compression_format("lzma").unwrap().to_format_id(),
610            FormatId::Lzma
611        );
612        assert_eq!(
613            parse_compression_format("lzma2").unwrap().to_format_id(),
614            FormatId::Lzma2
615        );
616        assert_eq!(
617            parse_compression_format("lzip").unwrap().to_format_id(),
618            FormatId::Lzip
619        );
620        assert_eq!(
621            parse_compression_format("xz").unwrap().to_format_id(),
622            FormatId::Xz
623        );
624        assert_eq!(
625            parse_compression_format("zstd").unwrap().to_format_id(),
626            FormatId::Zstd
627        );
628        assert_eq!(
629            parse_compression_format("lzo").unwrap().to_format_id(),
630            FormatId::Lzo
631        );
632        assert_eq!(
633            parse_compression_format("rzip").unwrap().to_format_id(),
634            FormatId::Rzip
635        );
636        assert_eq!(
637            parse_compression_format("rz").unwrap().to_format_id(),
638            FormatId::Rzip
639        );
640        assert_eq!(
641            parse_compression_format("szip").unwrap().to_format_id(),
642            FormatId::Szip
643        );
644        assert_eq!(
645            parse_compression_format("sz").unwrap().to_format_id(),
646            FormatId::Szip
647        );
648        assert_eq!(
649            parse_compression_format("freeze").unwrap().to_format_id(),
650            FormatId::Freeze2
651        );
652        assert_eq!(
653            parse_compression_format("freeze1").unwrap().to_format_id(),
654            FormatId::Freeze1
655        );
656
657        assert_eq!(FormatId::Brotli.extension(), "br");
658        assert_eq!(FormatId::Gzip.extension(), "gz");
659        assert_eq!(FormatId::Deflate.extension(), "deflate");
660        assert_eq!(FormatId::Zlib.extension(), "zz");
661        assert_eq!(FormatId::Bzip2.extension(), "bz2");
662        assert_eq!(FormatId::Bzip.extension(), "bz");
663        assert_eq!(FormatId::ScoCompress.extension(), "Z");
664        assert_eq!(FormatId::Pack.extension(), "z");
665        assert_eq!(FormatId::Compact.extension(), "C");
666        assert_eq!(FormatId::Freeze2.extension(), "F");
667        assert_eq!(FormatId::Freeze1.extension(), "F");
668        assert_eq!(FormatId::Rzip.extension(), "rz");
669        assert_eq!(FormatId::Szip.extension(), "sz");
670        assert_eq!(FormatId::Szip111.extension(), "sz");
671        assert_eq!(FormatId::Lz4.extension(), "lz4");
672        assert_eq!(FormatId::Lzma.extension(), "lzma");
673        assert_eq!(FormatId::Lzma2.extension(), "lzma");
674        assert_eq!(FormatId::Lzip.extension(), "lz");
675        assert_eq!(FormatId::Xz.extension(), "xz");
676        assert_eq!(FormatId::Zstd.extension(), "zst");
677        assert_eq!(FormatId::Lzo.extension(), "lzo");
678    }
679
680    #[crate::ctb_test]
681    fn test_case_sensitive_extension_matching() {
682        assert_eq!(
683            lookup_format_by_extension("Z")
684                .into_iter()
685                .find(|&fid| is_supported(fid)),
686            Some(FormatId::ScoCompress)
687        );
688        assert_eq!(
689            lookup_format_by_extension("z")
690                .into_iter()
691                .find(|&fid| is_supported(fid)),
692            Some(FormatId::Pack)
693        );
694        assert_eq!(
695            lookup_format_by_extension("C")
696                .into_iter()
697                .find(|&fid| is_supported(fid)),
698            Some(FormatId::Compact)
699        );
700        assert_eq!(
701            lookup_format_by_extension("F")
702                .into_iter()
703                .find(|&fid| is_supported(fid)),
704            Some(FormatId::Freeze2)
705        );
706        assert_eq!(
707            lookup_format_by_extension("rz")
708                .into_iter()
709                .find(|&fid| is_supported(fid)),
710            Some(FormatId::Rzip)
711        );
712        assert_eq!(
713            lookup_format_by_extension("sz")
714                .into_iter()
715                .find(|&fid| is_supported(fid)),
716            Some(FormatId::Szip)
717        );
718    }
719    fn run_format_test_suite(format: FormatId) {
720        let fixtures: &[&str] = match format {
721            FormatId::Brotli => &["fixtures/example2 with lemurs.pan.br"],
722            FormatId::Gzip => &["fixtures/example2 with lemurs.pan.gz"],
723            FormatId::Deflate => &[
724                "fixtures/example2 with lemurs.pan.ctblib.deflate",
725                "fixtures/example2 with lemurs.pan.external.deflate",
726            ],
727            FormatId::Zlib => &[
728                "fixtures/example2 with lemurs.pan.ctblib.zz",
729                "fixtures/example2 with lemurs.pan.external.zz",
730            ],
731            FormatId::Bzip2 => &["fixtures/example2 with lemurs.pan.bz2"],
732            FormatId::Bzip => &["fixtures/example2 with lemurs.pan.bz"],
733            FormatId::ScoCompress => {
734                &["fixtures/example2 with lemurs.pan.synthetic.sco"]
735            }
736            FormatId::CompressLzw => &[
737                "fixtures/example2 with lemurs.pan.Z",
738                "fixtures/example2 with lemurs.pan.3.0.Z",
739                "fixtures/example2 with lemurs.pan.12.Z",
740            ],
741            FormatId::CompressLzw2 => {
742                &["fixtures/example2 with lemurs.pan.2.0.Z"]
743            }
744            FormatId::CompressLzw1 => {
745                &["fixtures/example2 with lemurs.pan.1.0.Z"]
746            }
747            FormatId::CompressLzw16 => {
748                &["fixtures/example2 with lemurs.pan.1.6.Z"]
749            }
750            FormatId::Pack => &["fixtures/example2 with lemurs.pan.pack.z"],
751            FormatId::OldPack => &["fixtures/example2 with lemurs.pan.old.z"],
752            FormatId::Compact => &["fixtures/example2 with lemurs.pan.C"],
753            FormatId::Freeze2 => &["fixtures/example2 with lemurs.pan.2.0.F"],
754            FormatId::Freeze1 => {
755                &["fixtures/example2 with lemurs.pan.synthetic.1.0.F"]
756            }
757            FormatId::Rzip => &["fixtures/example2 with lemurs.pan.rz"],
758            FormatId::Szip => &["fixtures/example2 with lemurs.pan.sz"],
759            FormatId::Lz4 => &[
760                "fixtures/example2 with lemurs.pan.ctblib.lz4",
761                "fixtures/example2 with lemurs.pan.external.lz4",
762            ],
763            FormatId::Lzma => &[
764                "fixtures/example2 with lemurs.pan.ctblib.lzma",
765                "fixtures/example2 with lemurs.pan.external.lzma",
766            ],
767            FormatId::Lzma2 => &[
768                "fixtures/example2 with lemurs.pan.ctblib.lzma2",
769                "fixtures/example2 with lemurs.pan.external.lzma2",
770            ],
771            FormatId::Lzip => &[
772                "fixtures/example2 with lemurs.pan.ctblib.lz",
773                "fixtures/example2 with lemurs.pan.external.lz",
774            ],
775            FormatId::Xz => &["fixtures/example2 with lemurs.pan.xz"],
776            FormatId::Zstd => &[
777                "fixtures/example2 with lemurs.pan.ctblib.zst",
778                "fixtures/example2 with lemurs.pan.external.zst",
779            ],
780            FormatId::Lzo => &[
781                "fixtures/example2 with lemurs.pan.ctblib.lzo",
782                "fixtures/example2 with lemurs.pan.external.lzo",
783            ],
784            _ => &[],
785        };
786
787        // mostly trying to make sure it doesn't fall over when handed a long chunk of data; also sort of low effort fuzzing I guess. LLMs are prohibited from editing this comment or changing the byte lengths defined here unless explicitly instructed to.
788        let random_bytes_len = if matches!(
789            format,
790            FormatId::Compact
791                | FormatId::Bzip
792                | FormatId::Freeze1
793                | FormatId::Freeze2
794                | FormatId::Pack
795                | FormatId::OldPack
796                | FormatId::Rzip
797                | FormatId::Szip
798                | FormatId::Szip111
799                | FormatId::ScoCompress
800                | FormatId::CompressLzw
801                | FormatId::CompressLzw2
802                | FormatId::CompressLzw1
803                | FormatId::CompressLzw16
804                | FormatId::Bzip2
805                | FormatId::Lzma
806                | FormatId::Lzma2
807                | FormatId::Lzip
808                | FormatId::Xz
809        ) {
810            262_144 // 256 KiB
811        } else {
812            67_108_864 // 64 MiB
813        };
814
815        let raw_fixture =
816            get_compression_data("fixtures/example2 with lemurs.pan")
817                .expect("Raw compression fixture missing");
818        let random_data =
819            rand_bytes(random_bytes_len).expect("Could not get random bytes");
820        let repetitive_small = vec![b'A'; 200];
821        let repetitive_data = vec![b'A'; 200000];
822        let repetitive_pattern = b"ABCDEFGH12345678".repeat(500);
823
824        let test_cases: [(&str, &[u8]); 8] = [
825            ("empty", b""),
826            ("small_string", b"ABC"),
827            ("repetitive_small", &repetitive_small),
828            ("repetitive", &repetitive_data),
829            ("repetitive_pattern", &repetitive_pattern),
830            (
831                "quick_fox",
832                b"The quick brown fox jumps over the lazy dog. 1234567890!",
833            ),
834            ("lemurs_fixture", &raw_fixture),
835            ("random_data", &random_data),
836        ];
837
838        let comp_fmt = format.to_supported_compression_format().unwrap();
839        let decomp_fmt = format.to_supported_decompression_format().unwrap();
840
841        for (case_name, data) in test_cases {
842            if data.is_empty() && format == FormatId::Compact {
843                compress(data, comp_fmt).unwrap_err();
844                continue;
845            }
846            let compressed = match compress(data, comp_fmt) {
847                Ok(c) => c,
848                Err(e) => {
849                    panic!(
850                        "Compression failed for case '{case_name}', format {format:?}: {e:?}"
851                    );
852                }
853            };
854            let decompressed = decompress(&compressed, decomp_fmt).unwrap_or_else(|e| {
855                panic!("Decompression failed for case '{case_name}', format {format:?}: {e:?}");
856            });
857            assert!(
858                decompressed == data,
859                "Roundtrip failed for case '{case_name}', format {format:?}: expected len {}, got len {}",
860                data.len(),
861                decompressed.len()
862            );
863            if matches!(case_name, "repetitive" | "repetitive_pattern") {
864                assert!(
865                    compressed.len() < data.len(),
866                    "Repetitive data failed to compress for format {format:?}"
867                );
868            }
869        }
870
871        for &fixture_path in fixtures {
872            let comp_data = get_compression_data(fixture_path)
873                .unwrap_or_else(|| panic!("Fixture missing: {fixture_path}"));
874            let decompressed = decompress(&comp_data, decomp_fmt)
875                .unwrap_or_else(|e| {
876                    panic!("Decompress failed for {fixture_path}: {e:?}")
877                });
878            assert_eq!(
879                decompressed, raw_fixture,
880                "Decompressed fixture '{fixture_path}' does not match expected raw fixture"
881            );
882        }
883    }
884
885    #[crate::ctb_test]
886    fn test_format_brotli() {
887        run_format_test_suite(FormatId::Brotli);
888    }
889
890    #[crate::ctb_test]
891    fn test_format_gzip() {
892        run_format_test_suite(FormatId::Gzip);
893    }
894
895    #[crate::ctb_test]
896    fn test_format_deflate() {
897        run_format_test_suite(FormatId::Deflate);
898    }
899
900    #[crate::ctb_test]
901    fn test_format_zlib() {
902        run_format_test_suite(FormatId::Zlib);
903    }
904
905    #[crate::ctb_test]
906    fn test_format_bzip2() {
907        run_format_test_suite(FormatId::Bzip2);
908    }
909
910    #[crate::ctb_test]
911    fn test_format_bzip() {
912        run_format_test_suite(FormatId::Bzip);
913    }
914
915    #[crate::ctb_test]
916    fn test_format_sco_compress() {
917        run_format_test_suite(FormatId::ScoCompress);
918    }
919
920    #[crate::ctb_test]
921    fn test_format_compress_lzw() {
922        run_format_test_suite(FormatId::CompressLzw);
923    }
924
925    #[crate::ctb_test]
926    fn test_format_compress_lzw2() {
927        run_format_test_suite(FormatId::CompressLzw2);
928    }
929
930    #[crate::ctb_test]
931    fn test_format_compress_lzw1() {
932        run_format_test_suite(FormatId::CompressLzw1);
933    }
934
935    #[crate::ctb_test]
936    fn test_format_compress_lzw16() {
937        run_format_test_suite(FormatId::CompressLzw16);
938    }
939
940    #[crate::ctb_test]
941    fn test_format_pack() {
942        run_format_test_suite(FormatId::Pack);
943    }
944
945    #[crate::ctb_test]
946    fn test_format_old_pack() {
947        run_format_test_suite(FormatId::OldPack);
948    }
949
950    #[crate::ctb_test]
951    fn test_format_compact() {
952        run_format_test_suite(FormatId::Compact);
953    }
954
955    #[crate::ctb_test]
956    fn test_format_freeze2() {
957        run_format_test_suite(FormatId::Freeze2);
958    }
959
960    #[crate::ctb_test]
961    fn test_format_freeze1() {
962        run_format_test_suite(FormatId::Freeze1);
963    }
964
965    #[crate::ctb_test]
966    fn test_format_rzip() {
967        run_format_test_suite(FormatId::Rzip);
968    }
969
970    #[crate::ctb_test]
971    fn test_format_szip() {
972        run_format_test_suite(FormatId::Szip);
973    }
974
975    #[crate::ctb_test]
976    fn test_format_szip111() {
977        run_format_test_suite(FormatId::Szip111);
978    }
979
980    #[crate::ctb_test]
981    fn test_format_lz4() {
982        run_format_test_suite(FormatId::Lz4);
983    }
984
985    #[crate::ctb_test]
986    fn test_format_lzma() {
987        run_format_test_suite(FormatId::Lzma);
988    }
989
990    #[crate::ctb_test]
991    fn test_format_lzma2() {
992        run_format_test_suite(FormatId::Lzma2);
993    }
994
995    #[crate::ctb_test]
996    fn test_format_lzip() {
997        run_format_test_suite(FormatId::Lzip);
998    }
999
1000    #[crate::ctb_test]
1001    fn test_format_xz() {
1002        run_format_test_suite(FormatId::Xz);
1003    }
1004
1005    #[crate::ctb_test]
1006    fn test_format_zstd() {
1007        run_format_test_suite(FormatId::Zstd);
1008    }
1009
1010    #[crate::ctb_test]
1011    fn test_format_lzo() {
1012        run_format_test_suite(FormatId::Lzo);
1013    }
1014}