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