Skip to main content

openreadout_codecs/
lib.rs

1//! Pure-Rust decoders used by the format readers. No C toolchain is needed, which keeps
2//! the musl static builds simple. Every function returns owned bytes in the caller's
3//! expected layout; nothing here knows about file formats.
4//!
5//! Every decoder is bounded: output never grows past the caller's expected size (plus one
6//! byte to detect overlong streams), and size hints are only trusted up to
7//! [`MAX_PREALLOC`] for up-front allocation.
8//!
9//! Decoding failures are reported as [`CodecError`] values, never by exiting the process.
10//!
11//! # Cargo features
12//!
13//! All enabled by default. A disabled codec's functions still exist and return
14//! [`CodecError::NotCompiled`].
15//!
16//! | feature | codecs |
17//! | --- | --- |
18//! | `zstd` | [`zstd_decode`], [`zstd1_decode`] (Zstandard, via `ruzstd`) |
19//! | `jpeg` | [`jpeg_decode`], [`jpeg_decode_tiff`] and their `_limited` forms (baseline, progressive, lossless) |
20//! | `jpegxr` | [`jpegxr_decode`] (JPEG XR, as in CZI files; `openreadout-jpegxr`, a safe port of jxrlib) |
21//! | `jpeg2000` | [`jpeg2000_decode`] and [`jpeg2000_decode_limited`] (`rust-j2k`, fallback `dicom-toolkit-jpeg2000`) |
22//! | `lzw` | [`lzw_decode`] (TIFF LZW) |
23//! | `deflate` | [`zlib_decode`] |
24//! | `lz4` | [`lz4_block_decode`], [`lz4_sized_decode`], [`hdf5_lz4_decode`] and LZ4 inside Blosc |
25//!
26//! [`chunked_decode`] (CZI chunked compression) uses the `zstd` and `lz4` features.
27//!
28//! [`unshuffle_hilo`], [`packbits_decode`], [`lzf_decode`], [`blosc_decode`], [`blosclz_decode`] and
29//! [`lzma2_decode`] (raw LZMA2 chunks) need no feature.
30//!
31//! # Example
32//!
33//! ```
34//! use openreadout_codecs::{packbits_decode, unshuffle_hilo};
35//!
36//! // PackBits: a literal run of 2 bytes, then the byte 0xAA repeated 3 times.
37//! let raw = packbits_decode(&[0x01, 0x10, 0x20, 0xFE, 0xAA], 5)?;
38//! assert_eq!(raw, [0x10, 0x20, 0xAA, 0xAA, 0xAA]);
39//!
40//! // "HiLo": all low bytes of 16-bit samples, then all high bytes.
41//! assert_eq!(unshuffle_hilo(&[0x01, 0x02, 0xA0, 0xB0]), [0x01, 0xA0, 0x02, 0xB0]);
42//! # Ok::<(), openreadout_codecs::CodecError>(())
43//! ```
44#![forbid(unsafe_code)]
45#![warn(missing_docs)]
46
47mod blosc;
48mod chunked;
49#[cfg(feature = "jpeg2000")]
50mod j2k;
51#[cfg(feature = "jpeg")]
52mod jpeg12;
53#[cfg(feature = "jpegxl")]
54mod jxl;
55#[cfg(feature = "lerc")]
56mod lerc;
57mod lzma;
58#[cfg(feature = "webp")]
59mod webp;
60
61pub use blosc::{
62    BloscCompressor, BloscHeader, blosc_decode, blosc_header, blosclz_decode, hdf5_lz4_decode,
63    lz4_block_decode, lz4_sized_decode, snappy_decode,
64};
65pub use chunked::chunked_decode;
66pub use lzma::lzma2_decode;
67
68/// Codec failure.
69#[derive(Debug, thiserror::Error)]
70#[non_exhaustive]
71pub enum CodecError {
72    /// The data is not a valid stream for this codec.
73    #[error("{codec}: {detail}")]
74    Decode {
75        /// Codec name.
76        codec: &'static str,
77        /// What is wrong with the stream.
78        detail: String,
79    },
80    /// The codec was left out at build time.
81    #[error("{codec} support was not compiled in (feature `{feature}`)")]
82    NotCompiled {
83        /// Codec name.
84        codec: &'static str,
85        /// Cargo feature that enables it.
86        feature: &'static str,
87    },
88    /// A valid stream that uses a feature this decoder does not implement.
89    #[error("{codec}: {detail} is not supported")]
90    Unsupported {
91        /// Codec name.
92        codec: &'static str,
93        /// The feature.
94        detail: String,
95    },
96    /// The stream decoded, but not to the expected number of bytes.
97    #[error("decoded {codec} data is {got} bytes, expected {expected}")]
98    SizeMismatch {
99        /// Codec name.
100        codec: &'static str,
101        /// Bytes decoded.
102        got: usize,
103        /// Bytes the caller expected.
104        expected: usize,
105    },
106}
107
108/// Result alias of this crate.
109pub type Result<T> = std::result::Result<T, CodecError>;
110
111/// Largest buffer a decoder pre-allocates from a caller-supplied size hint (64 MiB). Output
112/// beyond this grows on demand, so a lying size field cannot force a huge up-front allocation.
113pub const MAX_PREALLOC: usize = 64 << 20;
114
115/// Output cap for streams whose decoded size is unknown (`expected_len == 0`): 1 GiB.
116pub const MAX_UNSIZED_OUTPUT: usize = 1 << 30;
117
118/// How many bytes a decoder may produce: one more than expected (so "too long" is
119/// detectable without decoding a bomb to the end), or the unsized cap.
120fn output_limit(expected_len: usize) -> usize {
121    if expected_len == 0 {
122        MAX_UNSIZED_OUTPUT
123    } else {
124        expected_len.saturating_add(1)
125    }
126}
127
128/// Decompress a plain zstd frame. `expected_len` is a sanity bound (0 = unknown); decoding
129/// stops one byte past it, so a decompression bomb costs at most `expected_len + 1` bytes.
130pub fn zstd_decode(data: &[u8], expected_len: usize) -> Result<Vec<u8>> {
131    #[cfg(feature = "zstd")]
132    {
133        use std::io::Read;
134        // Fast path when the size is known: decode straight into a buffer of that size (no
135        // `Read` adapter). Any failure, including trailing bytes after the frame or a size
136        // other than expected, falls through to the streaming decoder below, which produces
137        // the same results and errors.
138        if expected_len != 0 && expected_len <= MAX_PREALLOC {
139            let mut out = vec![0u8; expected_len];
140            let mut fd = ruzstd::decoding::FrameDecoder::new();
141            if let Ok(n) = fd.decode_all(data, &mut out)
142                && n == expected_len
143            {
144                return Ok(out);
145            }
146        }
147        let dec =
148            ruzstd::decoding::StreamingDecoder::new(data).map_err(|e| CodecError::Decode {
149                codec: "zstd",
150                detail: e.to_string(),
151            })?;
152        let limit = output_limit(expected_len);
153        let mut out = Vec::with_capacity(expected_len.min(MAX_PREALLOC));
154        dec.take(limit as u64)
155            .read_to_end(&mut out)
156            .map_err(|e| CodecError::Decode {
157                codec: "zstd",
158                detail: e.to_string(),
159            })?;
160        if (expected_len != 0 && out.len() != expected_len) || out.len() >= MAX_UNSIZED_OUTPUT {
161            return Err(CodecError::SizeMismatch {
162                codec: "zstd",
163                got: out.len(),
164                expected: expected_len,
165            });
166        }
167        Ok(out)
168    }
169    #[cfg(not(feature = "zstd"))]
170    {
171        let _ = (data, expected_len);
172        Err(CodecError::NotCompiled {
173            codec: "zstd",
174            feature: "zstd",
175        })
176    }
177}
178
179/// Parsed "zstd1" prefix used by CZI compression id 6: `header_size`, `chunk_kind`, flags.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub struct Zstd1Header {
182    /// Size of the header in bytes (byte 0).
183    pub header_size: u8,
184    /// Kind of the first header chunk (byte 1).
185    pub chunk_kind: u8,
186    /// Bit 0 of the flags byte: samples were byte-shuffled into low-byte and high-byte halves.
187    pub hilo: bool,
188}
189
190/// Parse the zstd1 header; returns the header and the offset of the zstd frame.
191pub fn zstd1_header(data: &[u8]) -> Result<(Zstd1Header, usize)> {
192    if data.len() < 2 {
193        return Err(CodecError::Decode {
194            codec: "zstd1",
195            detail: "buffer shorter than the header".into(),
196        });
197    }
198    let header_size = data[0] as usize;
199    if header_size < 1 || header_size > data.len() {
200        return Err(CodecError::Decode {
201            codec: "zstd1",
202            detail: format!("implausible header_size {header_size}"),
203        });
204    }
205    let chunk_kind = data.get(1).copied().unwrap_or(0);
206    let flags = if header_size >= 3 { data[2] } else { 0 };
207    Ok((
208        Zstd1Header {
209            header_size: header_size as u8,
210            chunk_kind,
211            hilo: flags & 1 != 0,
212        },
213        header_size,
214    ))
215}
216
217/// Decode a zstd1 payload into interleaved samples of `bytes_per_sample` bytes.
218pub fn zstd1_decode(data: &[u8], expected_len: usize, bytes_per_sample: usize) -> Result<Vec<u8>> {
219    let (h, off) = zstd1_header(data)?;
220    let raw = zstd_decode(data.get(off..).unwrap_or_default(), expected_len)?;
221    if h.hilo && bytes_per_sample == 2 {
222        Ok(unshuffle_hilo(&raw))
223    } else {
224        Ok(raw)
225    }
226}
227
228/// Undo the `HiLo` byte shuffle: input is all low bytes followed by all high bytes of
229/// 16-bit little-endian samples; output is the interleaved samples.
230pub fn unshuffle_hilo(shuffled: &[u8]) -> Vec<u8> {
231    let n = shuffled.len() / 2;
232    let (lo, rest) = shuffled.split_at(n);
233    let hi = &rest[..n];
234    let mut out = vec![0u8; shuffled.len()];
235    // Zipped fixed-size chunks: no per-byte capacity or bounds checks in the loop.
236    for (pair, (&l, &h)) in out.as_chunks_mut::<2>().0.iter_mut().zip(lo.iter().zip(hi)) {
237        *pair = [l, h];
238    }
239    if shuffled.len() % 2 == 1 {
240        out[shuffled.len() - 1] = shuffled[shuffled.len() - 1];
241    }
242    out
243}
244
245/// A decoded raster: interleaved samples, no row padding.
246#[derive(Debug, Clone)]
247pub struct Raster {
248    /// Width in pixels.
249    pub width: u32,
250    /// Height in pixels.
251    pub height: u32,
252    /// Samples per pixel (1 for grayscale, 3 for colour).
253    pub channels: u32,
254    /// Bits per sample.
255    pub bits_per_sample: u32,
256    /// True for floating-point samples.
257    pub float: bool,
258    /// True when the codestream declares B,G,R sample order (the caller may want R,G,B).
259    pub bgr: bool,
260    /// The samples, interleaved, `width × channels × bits_per_sample / 8` bytes per row.
261    pub data: Vec<u8>,
262}
263
264/// Decode a JPEG XR codestream (as embedded in CZI subblocks).
265pub fn jpegxr_decode(data: &[u8]) -> Result<Raster> {
266    jpegxr_decode_expect(data, None)
267}
268
269/// Decode a JPEG XR codestream, refusing before any pixel allocation when the codestream's
270/// own dimensions differ from `expect` (width, height), e.g. the geometry a CZI directory
271/// entry declares. Without an expectation the decoded size is capped at
272/// [`MAX_UNSIZED_OUTPUT`].
273///
274/// Backed by `openreadout-jpegxr`, our `forbid(unsafe_code)` port of the decoder path of
275/// Microsoft's jxrlib (bit-exact with it). Features that decoder does not implement (alpha
276/// planes, CMYK, packed formats, ...) are [`CodecError::Unsupported`].
277pub fn jpegxr_decode_expect(data: &[u8], expect: Option<(u32, u32)>) -> Result<Raster> {
278    #[cfg(feature = "jpegxr")]
279    {
280        use openreadout_jpegxr as jxr;
281        let map = |e: jxr::Error| match e {
282            jxr::Error::Unsupported(m) => CodecError::Unsupported {
283                codec: "jpeg-xr",
284                detail: m,
285            },
286            other => CodecError::Decode {
287                codec: "jpeg-xr",
288                detail: other.to_string(),
289            },
290        };
291        let info = jxr::probe(data).map_err(map)?;
292        if let Some((ew, eh)) = expect
293            && (ew, eh) != (info.width, info.height)
294        {
295            return Err(CodecError::Decode {
296                codec: "jpeg-xr",
297                detail: format!(
298                    "codestream is {}x{} but {ew}x{eh} was declared",
299                    info.width, info.height
300                ),
301            });
302        }
303        let limit = match expect {
304            // The declared geometry at the widest sample layout (4 x 32-bit per pixel).
305            Some((w, h)) => {
306                (u64::from(w) * u64::from(h) * 16).min(MAX_UNSIZED_OUTPUT as u64) as usize
307            }
308            None => MAX_UNSIZED_OUTPUT,
309        };
310        let img = jxr::decode(data, limit).map_err(map)?;
311        let (bits, float) = match img.sample {
312            jxr::SampleType::U8 => (8, false),
313            jxr::SampleType::U16 => (16, false),
314            jxr::SampleType::F32 => (32, true),
315            other => {
316                return Err(CodecError::Unsupported {
317                    codec: "jpeg-xr",
318                    detail: format!("{other:?} samples (signed fixed point or half float)"),
319                });
320            }
321        };
322        Ok(Raster {
323            width: img.width,
324            height: img.height,
325            channels: img.channels,
326            bits_per_sample: bits,
327            float,
328            bgr: img.bgr,
329            data: img.data,
330        })
331    }
332    #[cfg(not(feature = "jpegxr"))]
333    {
334        let _ = (data, expect);
335        Err(CodecError::NotCompiled {
336            codec: "jpeg-xr",
337            feature: "jpegxr",
338        })
339    }
340}
341
342/// `io::Write` sink that refuses to grow past `limit` bytes (decompression-bomb guard).
343#[cfg(feature = "lzw")]
344struct LimitedWriter {
345    buf: Vec<u8>,
346    limit: usize,
347}
348
349#[cfg(feature = "lzw")]
350impl std::io::Write for LimitedWriter {
351    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
352        let room = self.limit - self.buf.len();
353        if room == 0 && !data.is_empty() {
354            return Err(std::io::Error::other(
355                "decoded data exceeds the declared size",
356            ));
357        }
358        let n = data.len().min(room);
359        self.buf.extend_from_slice(&data[..n]);
360        Ok(n)
361    }
362    fn flush(&mut self) -> std::io::Result<()> {
363        Ok(())
364    }
365}
366
367/// Decode a JPEG stream (ITU-T T.81): baseline and progressive 8-bit, sequential 12-bit
368/// (extended process, Huffman coding, no chroma subsampling), lossless (SOF3) up to 16 bit.
369/// Returns gray (`channels == 1`) or R,G,B (`channels == 3`) samples; samples above 8 bits
370/// come back as little-endian u16. Progressive or subsampled 12-bit streams and CMYK are
371/// rejected with an error.
372pub fn jpeg_decode(data: &[u8]) -> Result<Raster> {
373    jpeg_decode_with(data, None, MAX_UNSIZED_OUTPUT)
374}
375
376/// [`jpeg_decode`], refusing (before decoding anything) a frame whose decoded size would
377/// exceed `max_bytes`. Callers that know the tile or plane size pass a bound derived from it,
378/// so a few-byte stream declaring 60000 x 15000 pixels costs nothing.
379pub fn jpeg_decode_limited(data: &[u8], max_bytes: usize) -> Result<Raster> {
380    jpeg_decode_with(data, None, max_bytes.min(MAX_UNSIZED_OUTPUT))
381}
382
383/// `color`: `None` keeps the decoder's default (Adobe/JFIF markers, else YCbCr for three
384/// components); `Some` forces the transform. `max_bytes`: largest decoded frame accepted.
385fn jpeg_decode_with(data: &[u8], color: Option<JpegColor>, max_bytes: usize) -> Result<Raster> {
386    #[cfg(feature = "jpeg")]
387    {
388        // jpeg-decoder stops at 8-bit DCT samples; 12-bit sequential streams have their own
389        // decoder (`jpeg12`).
390        if jpeg12::frame_precision(data) == Some(12) {
391            return jpeg12::decode(data, color, max_bytes);
392        }
393        let mut dec = jpeg_decoder::Decoder::new(data);
394        // A frame header can declare 65535 x 65535 x 4 samples; cap what the decoder allocates.
395        dec.set_max_decoding_buffer_size(MAX_UNSIZED_OUTPUT);
396        dec.read_info().map_err(|e| CodecError::Decode {
397            codec: "jpeg",
398            detail: e.to_string(),
399        })?;
400        // That cap applies to the output only: the decoder sizes its per-component planes
401        // from the frame header before checking it (a 342-byte stream made it allocate 4 GB).
402        if let Some(i) = dec.info() {
403            let bytes =
404                u64::from(i.width) * u64::from(i.height) * i.pixel_format.pixel_bytes() as u64;
405            if bytes > max_bytes as u64 {
406                return Err(CodecError::Decode {
407                    codec: "jpeg",
408                    detail: format!(
409                        "frame header declares {} x {} pixels ({bytes} bytes decoded)",
410                        i.width, i.height
411                    ),
412                });
413            }
414        }
415        if let Some(color) = color {
416            // Only three-component streams have a colour transform to choose.
417            if dec
418                .info()
419                .is_some_and(|i| i.pixel_format == jpeg_decoder::PixelFormat::RGB24)
420            {
421                dec.set_color_transform(match color {
422                    // "RGB" in jpeg-decoder: the components already are R, G, B (no conversion).
423                    JpegColor::AsCoded => jpeg_decoder::ColorTransform::RGB,
424                    JpegColor::ToRgb => jpeg_decoder::ColorTransform::YCbCr,
425                });
426            }
427        }
428        let px = dec.decode().map_err(|e| CodecError::Decode {
429            codec: "jpeg",
430            detail: e.to_string(),
431        })?;
432        let info = dec.info().ok_or_else(|| CodecError::Decode {
433            codec: "jpeg",
434            detail: "stream has no frame header".into(),
435        })?;
436        let (channels, bits_per_sample, data) = match info.pixel_format {
437            jpeg_decoder::PixelFormat::L8 => (1, 8, px),
438            jpeg_decoder::PixelFormat::RGB24 => (3, 8, px),
439            // jpeg-decoder hands back native-endian u16; normalize to little-endian.
440            jpeg_decoder::PixelFormat::L16 => (
441                1,
442                16,
443                px.as_chunks::<2>()
444                    .0
445                    .iter()
446                    .flat_map(|c| u16::from_ne_bytes(*c).to_le_bytes())
447                    .collect(),
448            ),
449            jpeg_decoder::PixelFormat::CMYK32 => {
450                return Err(CodecError::Decode {
451                    codec: "jpeg",
452                    detail: "CMYK JPEG streams are not supported".into(),
453                });
454            }
455        };
456        let (width, height) = (u32::from(info.width), u32::from(info.height));
457        let need =
458            width as usize * height as usize * channels as usize * (bits_per_sample as usize / 8);
459        if data.len() < need {
460            return Err(CodecError::SizeMismatch {
461                codec: "jpeg",
462                got: data.len(),
463                expected: need,
464            });
465        }
466        Ok(Raster {
467            width,
468            height,
469            channels,
470            bits_per_sample,
471            float: false,
472            bgr: false,
473            data,
474        })
475    }
476    #[cfg(not(feature = "jpeg"))]
477    {
478        let _ = (data, color);
479        Err(CodecError::NotCompiled {
480            codec: "jpeg",
481            feature: "jpeg",
482        })
483    }
484}
485
486/// Decode a JPEG 2000 codestream (raw J2K `FF 4F FF 51…` or a JP2 file) at its native bit depth.
487/// Samples are interleaved; precisions above 8 bits come back as little-endian u16. Used for the
488/// frames of legacy (NIS-Elements 2.x) ND2 files, VSI/ETS tiles and Aperio SVS tiles. Backed by
489/// `rust-j2k` (pure Rust, no `unsafe`, OpenJPEG-style mid-point reconstruction), with
490/// `dicom-toolkit-jpeg2000` for codestreams it does not support (see `j2k.rs`). The caller
491/// converts colour: components come back as coded (after the codestream's own RCT/ICT).
492pub fn jpeg2000_decode(data: &[u8]) -> Result<Raster> {
493    jpeg2000_decode_limited(data, MAX_UNSIZED_OUTPUT)
494}
495
496/// [`jpeg2000_decode`], refusing (before decoding) an image that would decode to more than
497/// `max_bytes` (counted at 2 bytes per sample).
498pub fn jpeg2000_decode_limited(data: &[u8], max_bytes: usize) -> Result<Raster> {
499    #[cfg(feature = "jpeg2000")]
500    {
501        j2k::decode(data, max_bytes)
502    }
503    #[cfg(not(feature = "jpeg2000"))]
504    {
505        let _ = (data, max_bytes);
506        Err(CodecError::NotCompiled {
507            codec: "jpeg2000",
508            feature: "jpeg2000",
509        })
510    }
511}
512
513/// Decode a WebP file (lossy VP8 or lossless VP8L; TIFF compression 50001) to 8-bit R,G,B, or
514/// R,G,B,A when the file has alpha, refusing (before decoding) an image larger than
515/// `max_bytes`. Backed by `image-webp` (pure Rust, no `unsafe`).
516pub fn webp_decode_limited(data: &[u8], max_bytes: usize) -> Result<Raster> {
517    #[cfg(feature = "webp")]
518    {
519        webp::decode(data, max_bytes)
520    }
521    #[cfg(not(feature = "webp"))]
522    {
523        let _ = (data, max_bytes);
524        Err(CodecError::NotCompiled {
525            codec: "webp",
526            feature: "webp",
527        })
528    }
529}
530
531/// Decode a JPEG XL codestream or container (TIFF compression 50002/52546): the first frame,
532/// colour channels then extra channels (alpha, ...), interleaved; u8 up to 8 bits per sample,
533/// little-endian u16 up to 16, f32 for float images. Refuses (before rendering) an image larger
534/// than `max_bytes`. Backed by `jxl-oxide`.
535pub fn jpegxl_decode_limited(data: &[u8], max_bytes: usize) -> Result<Raster> {
536    #[cfg(feature = "jpegxl")]
537    {
538        jxl::decode(data, max_bytes)
539    }
540    #[cfg(not(feature = "jpegxl"))]
541    {
542        let _ = (data, max_bytes);
543        Err(CodecError::NotCompiled {
544            codec: "jpeg-xl",
545            feature: "jpegxl",
546        })
547    }
548}
549
550/// Decode a LERC2 blob (TIFF compression 34887, after any deflate/zstd wrapping is removed) to
551/// interleaved little-endian samples of the blob's type (`channels` = depth x bands); pixels
552/// its mask marks invalid are 0. Refuses (before decoding) an image larger than `max_bytes`.
553/// Backed by `lerc-rs`.
554pub fn lerc_decode_limited(data: &[u8], max_bytes: usize) -> Result<Raster> {
555    #[cfg(feature = "lerc")]
556    {
557        lerc::decode(data, max_bytes)
558    }
559    #[cfg(not(feature = "lerc"))]
560    {
561        let _ = (data, max_bytes);
562        Err(CodecError::NotCompiled {
563            codec: "lerc",
564            feature: "lerc",
565        })
566    }
567}
568
569/// TIFF-flavoured LZW (MSB-first, 8-bit symbols), as used by CZI compression id 2.
570pub fn lzw_decode(data: &[u8], expected_len: usize) -> Result<Vec<u8>> {
571    #[cfg(feature = "lzw")]
572    {
573        let mut dec = weezl::decode::Decoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8);
574        let mut out = LimitedWriter {
575            buf: Vec::with_capacity(expected_len.min(MAX_PREALLOC)),
576            limit: output_limit(expected_len),
577        };
578        // Reuse a small per-thread staging buffer across TIFF strips. The bounded writer
579        // still stops decompression bombs, without zeroing weezl's default 16 MiB per strip.
580        thread_local! {
581            static BUFFER: std::cell::RefCell<Vec<u8>> =
582                std::cell::RefCell::new(vec![0; 64 << 10]);
583        }
584        BUFFER
585            .with_borrow_mut(|buffer| {
586                let mut stream = dec.into_stream(&mut out);
587                stream.set_buffer(buffer);
588                stream.decode_all(data).status
589            })
590            .or_else(|e| {
591                // A strip that ends without the end-of-information code (libtiff: "Strip not
592                // terminated with EOI code") keeps what it decoded, as libtiff and tifffile do;
593                // a short result is caught by the caller's length check.
594                if e.kind() == std::io::ErrorKind::UnexpectedEof && !out.buf.is_empty() {
595                    Ok(())
596                } else {
597                    Err(e)
598                }
599            })
600            .map_err(|e| CodecError::Decode {
601                codec: "lzw",
602                detail: e.to_string(),
603            })?;
604        let out = out.buf;
605        if (expected_len != 0 && out.len() != expected_len) || out.len() >= MAX_UNSIZED_OUTPUT {
606            return Err(CodecError::SizeMismatch {
607                codec: "lzw",
608                got: out.len(),
609                expected: expected_len,
610            });
611        }
612        Ok(out)
613    }
614    #[cfg(not(feature = "lzw"))]
615    {
616        let _ = (data, expected_len);
617        Err(CodecError::NotCompiled {
618            codec: "lzw",
619            feature: "lzw",
620        })
621    }
622}
623
624/// zlib/deflate (used by some ND2 chunks and by OME-TIFF). With a nonzero `expected_len`
625/// at most that many bytes are inflated (callers only use that prefix).
626pub fn zlib_decode(data: &[u8], expected_len: usize) -> Result<Vec<u8>> {
627    #[cfg(feature = "deflate")]
628    {
629        use std::io::Read;
630        let limit = if expected_len == 0 {
631            MAX_UNSIZED_OUTPUT
632        } else {
633            expected_len
634        };
635        let mut out = Vec::with_capacity(expected_len.min(MAX_PREALLOC));
636        flate2::read::ZlibDecoder::new(data)
637            .take(limit as u64)
638            .read_to_end(&mut out)
639            .map_err(|e| CodecError::Decode {
640                codec: "zlib",
641                detail: e.to_string(),
642            })?;
643        if expected_len == 0 && out.len() >= MAX_UNSIZED_OUTPUT {
644            return Err(CodecError::SizeMismatch {
645                codec: "zlib",
646                got: out.len(),
647                expected: expected_len,
648            });
649        }
650        Ok(out)
651    }
652    #[cfg(not(feature = "deflate"))]
653    {
654        let _ = (data, expected_len);
655        Err(CodecError::NotCompiled {
656            codec: "zlib",
657            feature: "deflate",
658        })
659    }
660}
661
662/// How [`jpeg_decode_tiff`] treats the colour components of the codestream.
663#[derive(Debug, Clone, Copy, PartialEq, Eq)]
664#[non_exhaustive]
665pub enum JpegColor {
666    /// Return the components exactly as coded (no colour conversion). Used when the
667    /// container says the components already are R, G, B (e.g. TIFF photometric RGB).
668    AsCoded,
669    /// Convert three YCbCr-coded components to R, G, B (e.g. TIFF photometric YCbCr).
670    ToRgb,
671}
672
673/// What a JPEG stream's markers say about its colour coding, read up to the first scan
674/// (`SOS`) without decoding anything. See [`jpeg_markers`].
675#[derive(Debug, Clone, Default, PartialEq, Eq)]
676#[non_exhaustive]
677pub struct JpegMarkers {
678    /// An `APP0` segment starting `JFIF\0` is present (JFIF implies Y, Cb, Cr components).
679    pub jfif: bool,
680    /// The transform byte of an `APP14` `Adobe` segment: 0 = components as coded (RGB or
681    /// CMYK), 1 = YCbCr, 2 = YCCK.
682    pub adobe_transform: Option<u8>,
683    /// Component identifiers of the frame header (`SOF`), in coding order.
684    pub component_ids: Vec<u8>,
685    /// Horizontal and vertical sampling factors per component (1 = full resolution).
686    pub sampling: Vec<(u8, u8)>,
687    /// The coding process of the frame: the low nibble of its `SOF` marker (0 baseline,
688    /// 1 extended sequential, 2 progressive, 3 lossless, 9 and up arithmetic coding).
689    pub process: u8,
690    /// Sample precision of the frame in bits (8 or 12 for DCT, 2 to 16 for lossless).
691    pub precision: u8,
692}
693
694impl JpegMarkers {
695    /// The colour coding of a three-component stream by the rules libjpeg applies when the
696    /// container says nothing (JFIF, then Adobe, then component ids `R`,`G`,`B`, else
697    /// YCbCr). `None` for streams that are not three-component.
698    #[must_use]
699    pub fn coded_color(&self) -> Option<JpegColor> {
700        if self.component_ids.len() != 3 {
701            return None;
702        }
703        Some(if self.jfif {
704            JpegColor::ToRgb
705        } else if let Some(t) = self.adobe_transform {
706            if t == 0 {
707                JpegColor::AsCoded
708            } else {
709                JpegColor::ToRgb
710            }
711        } else if self.component_ids == *b"RGB" {
712            JpegColor::AsCoded
713        } else {
714            JpegColor::ToRgb
715        })
716    }
717}
718
719/// Scan the marker segments of a JPEG stream (`tables` first when given, as for a TIFF
720/// `JPEGTables` tag) up to the first `SOS`. Only segment lengths are followed; nothing is
721/// decoded. Fails when the stream does not start with `SOI` or a segment runs past the end
722/// before a frame header was seen.
723pub fn jpeg_markers(data: &[u8], tables: Option<&[u8]>) -> Result<JpegMarkers> {
724    let mut m = JpegMarkers::default();
725    let mut frame_seen = false;
726    for s in tables.into_iter().chain(std::iter::once(data)) {
727        if s.len() < 2 || s[..2] != [0xFF, 0xD8] {
728            return Err(CodecError::Decode {
729                codec: "jpeg",
730                detail: "stream lacks an SOI marker".into(),
731            });
732        }
733        let mut i = 2usize;
734        while let Some(&b) = s.get(i) {
735            if b != 0xFF {
736                break;
737            }
738            let Some(&mk) = s.get(i + 1) else { break };
739            if mk == 0xFF {
740                i += 1; // fill byte
741                continue;
742            }
743            if mk == 0xD8 || mk == 0x01 || (0xD0..=0xD7).contains(&mk) {
744                i += 2;
745                continue;
746            }
747            if mk == 0xD9 || mk == 0xDA {
748                break;
749            }
750            let Some(len) = s
751                .get(i + 2..i + 4)
752                .map(|l| usize::from(u16::from_be_bytes([l[0], l[1]])))
753            else {
754                break;
755            };
756            let Some(seg) = len.checked_sub(2).and_then(|n| s.get(i + 4..i + 4 + n)) else {
757                break;
758            };
759            match mk {
760                0xE0 if seg.starts_with(b"JFIF\0") => m.jfif = true,
761                0xEE if seg.starts_with(b"Adobe") && seg.len() >= 12 => {
762                    m.adobe_transform = Some(seg[11]);
763                }
764                0xC0..=0xCF if !matches!(mk, 0xC4 | 0xC8 | 0xCC) => {
765                    m.process = mk & 0x0F;
766                    m.precision = seg.first().copied().unwrap_or(0);
767                    if let Some(&n) = seg.get(5) {
768                        let comps = seg.get(6..6 + 3 * usize::from(n)).unwrap_or_default();
769                        m.component_ids = comps.as_chunks::<3>().0.iter().map(|c| c[0]).collect();
770                        m.sampling = comps
771                            .as_chunks::<3>()
772                            .0
773                            .iter()
774                            .map(|c| (c[1] >> 4, c[1] & 0x0F))
775                            .collect();
776                        frame_seen = true;
777                    }
778                }
779                _ => {}
780            }
781            i += 2 + len;
782        }
783    }
784    if !frame_seen {
785        return Err(CodecError::Decode {
786            codec: "jpeg",
787            detail: "no frame header (SOF) before the first scan".into(),
788        });
789    }
790    Ok(m)
791}
792
793/// Decode a JPEG chunk of a TIFF (compression 7). `tables` is the abbreviated
794/// table-specification stream of the `JPEGTables` tag (`SOI`, DQT/DHT segments, `EOI`), spliced
795/// in front of the chunk; `color` says whether the components are already R, G, B (TIFF
796/// photometric RGB, decoded as coded) or YCbCr (photometric YCbCr, converted to R, G, B).
797/// Same decoder and output conventions as [`jpeg_decode`].
798pub fn jpeg_decode_tiff(data: &[u8], tables: Option<&[u8]>, color: JpegColor) -> Result<Raster> {
799    jpeg_decode_tiff_limited(data, tables, color, MAX_UNSIZED_OUTPUT)
800}
801
802/// [`jpeg_decode_tiff`] with the frame-size bound of [`jpeg_decode_limited`].
803pub fn jpeg_decode_tiff_limited(
804    data: &[u8],
805    tables: Option<&[u8]>,
806    color: JpegColor,
807    max_bytes: usize,
808) -> Result<Raster> {
809    let stream: std::borrow::Cow<'_, [u8]> = match tables {
810        Some(t) if t.len() >= 4 && data.len() >= 2 => {
811            if t[..2] != [0xFF, 0xD8] || data[..2] != [0xFF, 0xD8] {
812                return Err(CodecError::Decode {
813                    codec: "jpeg",
814                    detail: "JPEG tables or image stream lack an SOI marker".into(),
815                });
816            }
817            let t_end = if t[t.len() - 2..] == [0xFF, 0xD9] {
818                t.len() - 2
819            } else {
820                t.len()
821            };
822            let mut v = Vec::with_capacity(t_end + data.len());
823            v.extend_from_slice(&t[..t_end]);
824            v.extend_from_slice(&data[2..]);
825            std::borrow::Cow::Owned(v)
826        }
827        _ => std::borrow::Cow::Borrowed(data),
828    };
829    jpeg_decode_with(&stream, Some(color), max_bytes.min(MAX_UNSIZED_OUTPUT))
830}
831
832/// Apple/TIFF PackBits run-length decoding (TIFF compression 32773). Stops when
833/// `expected_len` bytes have been produced (0 = decode the whole input).
834pub fn packbits_decode(data: &[u8], expected_len: usize) -> Result<Vec<u8>> {
835    let mut out = Vec::with_capacity(expected_len.min(MAX_PREALLOC));
836    let mut i = 0usize;
837    while i < data.len() && (expected_len == 0 || out.len() < expected_len) {
838        let n = data[i] as i8;
839        i += 1;
840        if n >= 0 {
841            let count = n as usize + 1;
842            let end = i
843                .checked_add(count)
844                .filter(|&e| e <= data.len())
845                .ok_or_else(|| CodecError::Decode {
846                    codec: "packbits",
847                    detail: format!("literal run of {count} bytes runs past the input"),
848                })?;
849            out.extend_from_slice(&data[i..end]);
850            i = end;
851        } else if n != -128 {
852            let count = (1 - i16::from(n)) as usize;
853            let b = *data.get(i).ok_or_else(|| CodecError::Decode {
854                codec: "packbits",
855                detail: "repeat run without a value byte".into(),
856            })?;
857            i += 1;
858            out.extend(std::iter::repeat_n(b, count));
859        }
860    }
861    if expected_len != 0 {
862        out.truncate(expected_len);
863    }
864    Ok(out)
865}
866
867/// LZF decompression (the public liblzf scheme, as in Agilent `MSProfile.bin` and early
868/// Bruker TDF frames): a control byte below 32 copies that many plus one literal bytes;
869/// otherwise its top three bits are a back-reference length (an extra length byte follows
870/// when all three are set) and its low five bits, with the next byte, the distance back.
871/// `max_len` caps the output (0 = [`MAX_UNSIZED_OUTPUT`]); a stream that would produce more
872/// is an error.
873pub fn lzf_decode(data: &[u8], max_len: usize) -> Result<Vec<u8>> {
874    let limit = if max_len == 0 {
875        MAX_UNSIZED_OUTPUT
876    } else {
877        max_len
878    };
879    let bad = |detail: &str| CodecError::Decode {
880        codec: "lzf",
881        detail: detail.into(),
882    };
883    let mut out: Vec<u8> = Vec::with_capacity(limit.min(MAX_PREALLOC).min(data.len() * 4));
884    let mut i = 0usize;
885    while i < data.len() {
886        let c = usize::from(data[i]);
887        i += 1;
888        if c < 32 {
889            let n = c + 1;
890            let lit = data
891                .get(i..i + n)
892                .ok_or_else(|| bad("literal run past the end of the input"))?;
893            if out.len() + n > limit {
894                return Err(bad("output exceeds the expected size"));
895            }
896            out.extend_from_slice(lit);
897            i += n;
898        } else {
899            let mut len = c >> 5;
900            if len == 7 {
901                len += usize::from(*data.get(i).ok_or_else(|| bad("length byte missing"))?);
902                i += 1;
903            }
904            let lo = usize::from(*data.get(i).ok_or_else(|| bad("distance byte missing"))?);
905            i += 1;
906            let back = ((c & 0x1f) << 8) + lo + 1;
907            let from = out
908                .len()
909                .checked_sub(back)
910                .ok_or_else(|| bad("back-reference before the start of the output"))?;
911            let n = len + 2;
912            if out.len() + n > limit {
913                return Err(bad("output exceeds the expected size"));
914            }
915            // Overlapping copies repeat bytes written by this very reference.
916            for k in 0..n {
917                let v = out[from + k];
918                out.push(v);
919            }
920        }
921    }
922    Ok(out)
923}
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    #[test]
930    fn lzf_literals_and_overlapping_references() {
931        // literal "ab", then a back-reference of length 4 at distance 2 ("abab"), then "c"
932        let s = [0x01, b'a', b'b', 0x40, 0x01, 0x00, b'c'];
933        assert_eq!(lzf_decode(&s, 0).unwrap(), b"abababc");
934        assert!(lzf_decode(&s, 3).is_err(), "output cap");
935        assert!(lzf_decode(&[0x05, b'a'], 0).is_err(), "short literal");
936        assert!(
937            lzf_decode(&[0x20, 0x05], 0).is_err(),
938            "reference before start"
939        );
940        assert!(lzf_decode(&[0xE0], 0).is_err(), "missing length byte");
941    }
942
943    /// SOI, optional APP0 JFIF / APP14 Adobe, SOF0 with the given component ids (sampling of
944    /// the first 2x2, others 1x1), SOS.
945    fn jpeg_head(jfif: bool, adobe: Option<u8>, ids: &[u8]) -> Vec<u8> {
946        let mut v = vec![0xFF, 0xD8];
947        if jfif {
948            v.extend_from_slice(&[0xFF, 0xE0, 0, 16]);
949            v.extend_from_slice(b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0");
950        }
951        if let Some(t) = adobe {
952            v.extend_from_slice(&[0xFF, 0xEE, 0, 14]);
953            v.extend_from_slice(b"Adobe\0\x64\0\0\0\0");
954            v.push(t);
955        }
956        let n = u8::try_from(ids.len()).unwrap();
957        let len = 8 + 3 * u16::from(n);
958        v.extend_from_slice(&[0xFF, 0xC0]);
959        v.extend_from_slice(&len.to_be_bytes());
960        v.extend_from_slice(&[8, 0, 16, 0, 16, n]);
961        for (k, id) in ids.iter().enumerate() {
962            v.extend_from_slice(&[*id, if k == 0 { 0x22 } else { 0x11 }, 0]);
963        }
964        v.extend_from_slice(&[0xFF, 0xDA, 0, 8, 1, 1, 0, 0, 63, 0]);
965        v
966    }
967
968    #[test]
969    fn jpeg_markers_and_libjpeg_colour_rules() {
970        let m = jpeg_markers(&jpeg_head(true, None, &[1, 2, 3]), None).unwrap();
971        assert!(m.jfif);
972        assert_eq!(m.component_ids, [1, 2, 3]);
973        assert_eq!(m.sampling, [(2, 2), (1, 1), (1, 1)]);
974        assert_eq!(m.coded_color(), Some(JpegColor::ToRgb));
975        // JFIF wins over R,G,B ids (libjpeg 6b)
976        let m = jpeg_markers(&jpeg_head(true, None, b"RGB"), None).unwrap();
977        assert_eq!(m.coded_color(), Some(JpegColor::ToRgb));
978        // Adobe transform 0 / 1 without JFIF
979        let m = jpeg_markers(&jpeg_head(false, Some(0), &[1, 2, 3]), None).unwrap();
980        assert_eq!(
981            (m.adobe_transform, m.coded_color()),
982            (Some(0), Some(JpegColor::AsCoded))
983        );
984        let m = jpeg_markers(&jpeg_head(false, Some(1), b"RGB"), None).unwrap();
985        assert_eq!(m.coded_color(), Some(JpegColor::ToRgb));
986        // ids only
987        let m = jpeg_markers(&jpeg_head(false, None, b"RGB"), None).unwrap();
988        assert_eq!(m.coded_color(), Some(JpegColor::AsCoded));
989        let m = jpeg_markers(&jpeg_head(false, None, &[0, 1, 2]), None).unwrap();
990        assert_eq!(m.coded_color(), Some(JpegColor::ToRgb));
991        let m = jpeg_markers(&jpeg_head(false, None, &[1]), None).unwrap();
992        assert_eq!(m.coded_color(), None);
993        // tables stream (JPEGTables) scanned first; the frame header is in the chunk
994        let tables = [0xFF, 0xD8, 0xFF, 0xD9];
995        let m = jpeg_markers(&jpeg_head(true, None, &[1, 2, 3]), Some(&tables)).unwrap();
996        assert!(m.jfif);
997        // malformed: no SOI, truncated segment, no frame header
998        assert!(jpeg_markers(&[0, 1, 2], None).is_err());
999        let mut t = jpeg_head(true, None, &[1, 2, 3]);
1000        t.truncate(12);
1001        assert!(jpeg_markers(&t, None).is_err());
1002        assert!(jpeg_markers(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2], None).is_err());
1003        assert!(jpeg_markers(&[0xFF, 0xD8, 0xFF, 0xC0, 0, 1], None).is_err());
1004    }
1005
1006    /// A lossless WebP whose Huffman code counts overflow image-webp's u16 arithmetic: an error,
1007    /// not a panic, in every build (the workspace turns off overflow checks for image-webp).
1008    #[cfg(feature = "webp")]
1009    #[test]
1010    fn webp_huffman_overflow_is_an_error() {
1011        let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1012            .join("../../fuzz/known-upstream/image-webp-0.2.4-huffman-overflow.webp");
1013        let Ok(d) = std::fs::read(p) else {
1014            return;
1015        };
1016        assert!(webp_decode_limited(&d, 1 << 20).is_err());
1017    }
1018
1019    /// OpenJPEG-encoded fixtures (imagecodecs 2026.8.16) and OpenJPEG's own decodes of them:
1020    /// lossless 14-bit grey (exact), a JP2-wrapped lossless RGB (exact) and an irreversible
1021    /// 9/7 + ICT RGB (within one grey level).
1022    #[cfg(feature = "jpeg2000")]
1023    #[test]
1024    fn jpeg2000_matches_openjpeg() {
1025        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/j2k");
1026        for (name, channels, bits, tol) in [
1027            ("gray16-lossless", 1, 16, 0),
1028            ("rgb8-lossless-jp2", 3, 8, 0),
1029            ("rgb8-lossy-ict", 3, 8, 1),
1030        ] {
1031            let cs = std::fs::read(dir.join(format!("{name}.j2k"))).unwrap();
1032            let want = std::fs::read(dir.join(format!("{name}.openjpeg.raw"))).unwrap();
1033            let r = jpeg2000_decode(&cs).unwrap();
1034            assert_eq!(
1035                (r.width, r.height, r.channels, r.bits_per_sample),
1036                (37, 21, channels, bits),
1037                "{name}"
1038            );
1039            assert_eq!(r.data.len(), want.len(), "{name}");
1040            if bits == 16 {
1041                assert_eq!(r.data, want, "{name}");
1042            } else {
1043                let worst = r.data.iter().zip(&want).map(|(a, b)| a.abs_diff(*b)).max();
1044                assert!(worst <= Some(tol), "{name}: off by {worst:?}");
1045            }
1046            assert!(
1047                jpeg2000_decode(&cs[..cs.len() / 3]).is_err(),
1048                "{name}: truncated"
1049            );
1050            assert!(jpeg2000_decode_limited(&cs, 100).is_err(), "{name}: limit");
1051        }
1052        assert!(jpeg2000_decode(b"not a codestream").is_err());
1053    }
1054
1055    #[test]
1056    fn hilo_roundtrip() {
1057        // samples 0x0201, 0x0403 -> lo bytes [01,03], hi bytes [02,04]
1058        assert_eq!(
1059            unshuffle_hilo(&[0x01, 0x03, 0x02, 0x04]),
1060            vec![0x01, 0x02, 0x03, 0x04]
1061        );
1062    }
1063
1064    /// 4x4 lossless (SOF3) 16-bit JPEG of `i * 1000`, written by libjpeg-turbo via imagecodecs.
1065    #[cfg(feature = "jpeg")]
1066    #[test]
1067    fn jpeg_lossless_16bit_is_exact() {
1068        let data = [
1069            0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00,
1070            0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xff, 0xc3, 0x00, 0x0b, 0x10, 0x00, 0x04, 0x00,
1071            0x04, 0x01, 0x01, 0x11, 0x00, 0xff, 0xc4, 0x00, 0x16, 0x00, 0x01, 0x01, 0x01, 0x00,
1072            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x0c,
1073            0x10, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0xcf, 0xa1, 0xf4,
1074            0x3e, 0x8b, 0xe8, 0x1f, 0x43, 0xe8, 0x7d, 0x17, 0xd0, 0x3e, 0x87, 0xd0, 0xfa, 0x2f,
1075            0xa0, 0x7d, 0x0f, 0xa1, 0xf4, 0x7f, 0xff, 0xd9,
1076        ];
1077        let r = jpeg_decode(&data).unwrap();
1078        assert_eq!(
1079            (r.width, r.height, r.channels, r.bits_per_sample),
1080            (4, 4, 1, 16)
1081        );
1082        let want: Vec<u8> = (0..16u16).flat_map(|i| (i * 1000).to_le_bytes()).collect();
1083        assert_eq!(r.data, want);
1084    }
1085
1086    #[cfg(feature = "jpeg")]
1087    #[test]
1088    fn jpeg_rejects_garbage_cleanly() {
1089        assert!(jpeg_decode(&[0xFF, 0xD8, 0xFF, 0x00, 0x01]).is_err());
1090        assert!(jpeg_decode(&[]).is_err());
1091    }
1092
1093    #[test]
1094    fn packbits_spec_example() {
1095        // The example from the TIFF 6.0 specification, section 9.
1096        let packed = [
1097            0xFE, 0xAA, 0x02, 0x80, 0x00, 0x2A, 0xFD, 0xAA, 0x03, 0x80, 0x00, 0x2A, 0x22, 0xF7,
1098            0xAA,
1099        ];
1100        let expected = [
1101            0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0xAA, 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0x22,
1102            0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
1103        ];
1104        assert_eq!(packbits_decode(&packed, 0).unwrap(), expected);
1105        assert_eq!(packbits_decode(&packed, 5).unwrap(), expected[..5]);
1106        assert!(packbits_decode(&[0x05, 0x01], 0).is_err());
1107    }
1108
1109    #[cfg(feature = "jpeg")]
1110    #[test]
1111    fn jpeg_tiff_rejects_garbage() {
1112        assert!(jpeg_decode_tiff(&[0xFF, 0xD8, 0x00, 0x01], None, JpegColor::AsCoded).is_err());
1113        assert!(
1114            jpeg_decode_tiff(
1115                &[0xFF, 0xD8, 0x00, 0x01],
1116                Some(&[0, 0, 0, 0]),
1117                JpegColor::ToRgb
1118            )
1119            .is_err()
1120        );
1121    }
1122
1123    #[test]
1124    fn zstd1_header_parses() {
1125        let (h, off) = zstd1_header(&[3, 1, 1, 0x28, 0xB5, 0x2F, 0xFD]).unwrap();
1126        assert_eq!(off, 3);
1127        assert!(h.hilo);
1128        assert_eq!(h.chunk_kind, 1);
1129    }
1130
1131    #[cfg(feature = "deflate")]
1132    #[test]
1133    fn zlib_output_is_capped_at_expected_len() {
1134        use std::io::Write;
1135        let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
1136        enc.write_all(&vec![0u8; 1 << 20]).unwrap();
1137        let bomb = enc.finish().unwrap();
1138        assert_eq!(zlib_decode(&bomb, 100).unwrap().len(), 100);
1139    }
1140
1141    #[cfg(feature = "lzw")]
1142    #[test]
1143    fn lzw_reused_buffer_preserves_output_and_enforces_limit() {
1144        let raw: Vec<u8> = (0..200_000).map(|i| (i % 251) as u8).collect();
1145        let packed = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8)
1146            .encode(&raw)
1147            .unwrap();
1148        // Multiple staging-buffer fills, an overlong stream, then reuse after that error.
1149        assert_eq!(lzw_decode(&packed, raw.len()).unwrap(), raw);
1150        assert!(lzw_decode(&packed, 100).is_err());
1151        assert!(lzw_decode(&packed, raw.len() - 1).is_err());
1152        assert!(lzw_decode(&packed, raw.len() + 1).is_err());
1153        assert_eq!(lzw_decode(&packed, 0).unwrap(), raw);
1154        assert!(lzw_decode(&packed[..packed.len() / 2], raw.len()).is_err());
1155        assert_eq!(lzw_decode(&packed, raw.len()).unwrap(), raw);
1156        // A stream without its end-of-information code keeps what it decoded (libtiff and
1157        // tifffile accept such strips; the Harmony corpus has one); the length check still
1158        // rejects it when a size is expected.
1159        let head = lzw_decode(&packed[..packed.len() / 2], 0).unwrap();
1160        assert!(!head.is_empty() && raw.starts_with(&head));
1161    }
1162
1163    #[cfg(feature = "zstd")]
1164    #[test]
1165    fn zstd_fast_path_and_fallback_enforce_size() {
1166        let raw = vec![42; 4096];
1167        let packed = ruzstd::encoding::compress_to_vec(
1168            &raw[..],
1169            ruzstd::encoding::CompressionLevel::Fastest,
1170        );
1171        assert_eq!(zstd_decode(&packed, raw.len()).unwrap(), raw);
1172        assert_eq!(zstd_decode(&packed, 0).unwrap(), raw);
1173        assert!(zstd_decode(&packed, 100).is_err());
1174        assert!(zstd_decode(&packed, raw.len() + 1).is_err());
1175        // A bogus hint must not cause a hint-sized allocation in the fast path.
1176        assert!(zstd_decode(&packed, usize::MAX).is_err());
1177    }
1178
1179    #[test]
1180    fn garbage_is_a_clean_error() {
1181        let junk = [0xFFu8; 64];
1182        assert!(zstd_decode(&junk, 16).is_err());
1183        assert!(zstd1_decode(&junk, 16, 2).is_err());
1184        assert!(zlib_decode(&junk, 16).is_err());
1185        assert!(zstd1_decode(&[], 16, 2).is_err());
1186    }
1187}