Skip to main content

laminapdf_syntax/
filters.rs

1//! Stream filters (ISO 32000-1 §7.4): `FlateDecode` (via `miniz_oxide`), `LZWDecode`,
2//! `ASCIIHexDecode`, `ASCII85Decode` and `RunLengthDecode`, with the PNG and TIFF predictors.
3//! The image codecs (DCT, JPX, CCITT, JBIG2) are left to their readers: [`decode`] reports them
4//! as unsupported.
5//!
6//! Decoding is bounded by [`Limits`]: every filter stage's output is capped by
7//! [`Limits::max_stream_decoded`] and charged to the call's [`DecodeBudget`]
8//! ([`Limits::max_decoded_total`]), and a `/Filter` chain may hold at most
9//! [`Limits::max_filter_chain`] filters.
10//!
11//! ```
12//! use laminapdf_syntax::filters::{decode, flate_encode};
13//! use laminapdf_syntax::{DecodeBudget, Dict, Limits, Object};
14//!
15//! let dict: Dict = [("Filter", Object::name("FlateDecode"))].into_iter().collect();
16//! let limits = Limits::default();
17//! let mut budget = DecodeBudget::new(&limits);
18//! let decoded = decode(&dict, &flate_encode(b"hello"), &limits, &mut budget)?;
19//! assert_eq!(decoded.data, b"hello");
20//! assert!(!decoded.flate_truncated);
21//! assert_eq!(budget.remaining(), limits.max_decoded_total() - 5);
22//! # Ok::<(), laminapdf_syntax::Error>(())
23//! ```
24
25use miniz_oxide::inflate::TINFLStatus;
26
27use crate::error::{Error, Result};
28use crate::limits::{DecodeBudget, Limit, Limits};
29use crate::object::{Dict, Object};
30
31mod lzw;
32mod text;
33
34/// A filter's data that can't be decoded, with what is wrong.
35const fn bad(message: &'static str) -> Error {
36    Error::InvalidStructure {
37        kind: "stream filter",
38        message,
39    }
40}
41
42/// A filter stage's output, refused past its cap with the limit it would break.
43struct Output {
44    data: Vec<u8>,
45    cap: usize,
46    over: Limit,
47    /// The filter skipped characters outside its alphabet ([`Decoded::characters_skipped`]).
48    skipped: bool,
49}
50
51impl Output {
52    const fn new(cap: usize, over: Limit) -> Self {
53        Self {
54            data: Vec::new(),
55            cap,
56            over,
57            skipped: false,
58        }
59    }
60
61    /// The cap for a stage of a call within `limits`, with `budget` left.
62    fn within(limits: &Limits, budget: DecodeBudget) -> Self {
63        let stream_cap = limits.max_stream_decoded();
64        if budget.remaining() < stream_cap {
65            Self::new(budget.remaining(), Limit::DecodedTotal)
66        } else {
67            Self::new(stream_cap, Limit::StreamDecoded)
68        }
69    }
70
71    fn room(&self, more: usize) -> Result<()> {
72        if self.data.len().saturating_add(more) > self.cap {
73            return Err(Error::limit(self.over, None));
74        }
75        Ok(())
76    }
77
78    fn push(&mut self, byte: u8) -> Result<()> {
79        self.room(1)?;
80        self.data.push(byte);
81        Ok(())
82    }
83
84    fn extend(&mut self, bytes: &[u8]) -> Result<()> {
85        self.room(bytes.len())?;
86        self.data.extend_from_slice(bytes);
87        Ok(())
88    }
89
90    fn fill(&mut self, byte: u8, count: usize) -> Result<()> {
91        self.room(count)?;
92        self.data.resize(self.data.len() + count, byte);
93        Ok(())
94    }
95
96    fn set(&mut self, at: usize, byte: u8) {
97        if let Some(slot) = self.data.get_mut(at) {
98            *slot = byte;
99        }
100    }
101
102    const fn len(&self) -> usize {
103        self.data.len()
104    }
105
106    /// Notes that the filter skipped a character outside its alphabet.
107    const fn skip(&mut self) {
108        self.skipped = true;
109    }
110
111    fn into_inner(self) -> Vec<u8> {
112        self.data
113    }
114}
115
116/// Runs `filter` on `input` within `limits`, charging its output to `budget`; sets `skipped`
117/// when the filter skipped characters outside its alphabet.
118fn stage(
119    input: &[u8],
120    limits: &Limits,
121    budget: &mut DecodeBudget,
122    flags: &mut Flags,
123    filter: impl FnOnce(&[u8], &mut Output) -> Result<()>,
124) -> Result<Vec<u8>> {
125    let mut out = Output::within(limits, *budget);
126    match filter(input, &mut out) {
127        // A prefix read stops at its cap and keeps what it has (`decode_prefix`).
128        Err(Error::LimitExceeded {
129            limit: Limit::StreamDecoded,
130            ..
131        }) if flags.prefix => flags.cut = true,
132        other => other?,
133    }
134    flags.skipped |= out.skipped;
135    let data = out.into_inner();
136    budget.spend(data.len());
137    Ok(data)
138}
139
140/// Decoded stream data.
141///
142/// Added in 0.2.0.
143#[derive(Debug, Clone, PartialEq, Eq, Default)]
144#[non_exhaustive]
145pub struct Decoded {
146    /// The decoded bytes.
147    pub data: Vec<u8>,
148    /// True when Flate data was truncated or had a bad checksum and the partial output was
149    /// kept (the reader reports it as the `flate-truncated` warning).
150    pub flate_truncated: bool,
151    /// True when `ASCIIHexDecode` or `ASCII85Decode` data held characters outside the filter's
152    /// alphabet, which were skipped as other readers skip them (the reader reports it as the
153    /// `filter-characters-skipped` warning).
154    ///
155    /// Added in 0.4.0.
156    pub characters_skipped: bool,
157}
158
159/// Zlib-compresses `data` at the default level (6).
160///
161/// Added in 0.2.0.
162#[must_use]
163pub fn flate_encode(data: &[u8]) -> Vec<u8> {
164    miniz_oxide::deflate::compress_to_vec_zlib(data, 6)
165}
166
167/// Inflates zlib `data`, refusing output larger than [`Limits::max_stream_decoded`] or than
168/// what is left of `budget`, and charges the output to `budget`.
169///
170/// Truncated streams and bad checksums are tolerated when some output was produced, as
171/// real-world readers do ([`Decoded::flate_truncated`] reports it).
172///
173/// # Errors
174/// [`Error::LimitExceeded`] ([`Limit::StreamDecoded`] or [`Limit::DecodedTotal`]) when the
175/// output would exceed either cap, [`Error::Decompress`] when the data is not inflatable at all.
176///
177/// Added in 0.2.0.
178pub fn flate_decode(data: &[u8], limits: &Limits, budget: &mut DecodeBudget) -> Result<Decoded> {
179    flate_stage(data, limits, budget, &mut Flags::default())
180}
181
182/// [`flate_decode`], keeping the output so far when a prefix read reaches its cap.
183fn flate_stage(data: &[u8], limits: &Limits, budget: &mut DecodeBudget, flags: &mut Flags) -> Result<Decoded> {
184    let stream_cap = limits.max_stream_decoded();
185    let (cap, over) = if budget.remaining() < stream_cap {
186        (budget.remaining(), Limit::DecodedTotal)
187    } else {
188        (stream_cap, Limit::StreamDecoded)
189    };
190    let (data, flate_truncated) = match miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, cap) {
191        Ok(out) => (out, false),
192        Err(e) => match e.status {
193            TINFLStatus::HasMoreOutput if flags.prefix && over == Limit::StreamDecoded => {
194                flags.cut = true;
195                (e.output, false)
196            }
197            TINFLStatus::HasMoreOutput => return Err(Error::limit(over, None)),
198            TINFLStatus::Adler32Mismatch | TINFLStatus::FailedCannotMakeProgress if !e.output.is_empty() => {
199                (e.output, true)
200            }
201            _ => return Err(Error::Decompress("invalid zlib data")),
202        },
203    };
204    budget.spend(data.len());
205    Ok(Decoded {
206        data,
207        flate_truncated,
208        characters_skipped: false,
209    })
210}
211
212/// A filter's full name for its inline-image abbreviation (ISO 32000-2 §8.9.7, Table 92):
213/// `AHx` is `ASCIIHexDecode`, `CCF` is `CCITTFaxDecode`…; a full name comes back as it is.
214///
215/// Added in 0.4.0.
216#[must_use]
217pub fn full_name(name: &[u8]) -> &[u8] {
218    match name {
219        b"AHx" => b"ASCIIHexDecode",
220        b"A85" => b"ASCII85Decode",
221        b"LZW" => b"LZWDecode",
222        b"Fl" => b"FlateDecode",
223        b"RL" => b"RunLengthDecode",
224        b"CCF" => b"CCITTFaxDecode",
225        b"DCT" => b"DCTDecode",
226        other => other,
227    }
228}
229
230/// Decodes stream `data` according to `/Filter` and `/DecodeParms` in `dict`, within
231/// `limits` and `budget` (see the [module docs](self)).
232///
233/// `dict` values are expected to be direct (the reader resolves references first). Data
234/// without a filter is returned as is and costs no budget.
235///
236/// # Errors
237/// [`Error::UnsupportedFilter`] for the image codecs (DCT, JPX, CCITT, JBIG2) and `/Crypt` (decryption needs
238/// the file key, so the reader decrypts the stream when it loads it and removes `/Crypt` from
239/// the chain before calling this), [`Error::LimitExceeded`] for a chain longer than
240/// [`Limits::max_filter_chain`] or output over a decode limit, plus any decode error.
241///
242/// Added in 0.2.0.
243pub fn decode(dict: &Dict, data: &[u8], limits: &Limits, budget: &mut DecodeBudget) -> Result<Decoded> {
244    decode_with(dict, data, limits, budget, &mut Flags::default())
245}
246
247/// The first bytes of a stream ([`decode_prefix`]) and whether they are all of it.
248///
249/// Added in 0.6.0.
250#[derive(Debug, Clone, PartialEq, Eq)]
251#[non_exhaustive]
252pub struct Prefix {
253    /// At most the bytes asked for, decoded.
254    pub decoded: Decoded,
255    /// Whether the stream decodes to no more than these bytes.
256    pub complete: bool,
257}
258
259/// The first `max` bytes `data` decodes to, as [`decode`] decodes them, decoding at most one byte
260/// more to know whether there is more: a viewer that shows the start of a stream never decodes
261/// the rest. `limits` still apply, so when `max` is at or past
262/// [`Limits::max_stream_decoded`] a longer stream is refused as [`decode`] refuses it.
263///
264/// # Errors
265/// As [`decode`].
266///
267/// Added in 0.6.0.
268pub fn decode_prefix(
269    dict: &Dict,
270    data: &[u8],
271    limits: &Limits,
272    budget: &mut DecodeBudget,
273    max: usize,
274) -> Result<Prefix> {
275    let mut flags = Flags {
276        want: Some(max.saturating_add(1)),
277        ..Flags::default()
278    };
279    let mut decoded = decode_with(dict, data, limits, budget, &mut flags)?;
280    let complete = !flags.cut && decoded.data.len() <= max;
281    decoded.data.truncate(max);
282    Ok(Prefix { decoded, complete })
283}
284
285/// What a decode notes as it goes, and whether it reads a prefix.
286#[derive(Debug, Default)]
287struct Flags {
288    /// A prefix read: the bytes the chain's output needs (`max` + 1). Only the last stage stops
289    /// early; the ones before it decode under the document's limits, since a later filter needs
290    /// its whole input to decode the first bytes right.
291    want: Option<usize>,
292    /// The current stage reads a prefix: it stops at the stream cap and keeps its output.
293    prefix: bool,
294    /// A stage stopped at the cap.
295    cut: bool,
296    /// Characters outside a filter's alphabet were skipped.
297    skipped: bool,
298}
299
300fn decode_with(
301    dict: &Dict,
302    data: &[u8],
303    limits: &Limits,
304    budget: &mut DecodeBudget,
305    flags: &mut Flags,
306) -> Result<Decoded> {
307    let filters: Vec<&[u8]> = match dict.get("Filter") {
308        None | Some(Object::Null) => Vec::new(),
309        Some(Object::Name(n)) => vec![n.as_bytes()],
310        Some(Object::Array(items)) => items
311            .iter()
312            .map(|o| match o {
313                Object::Name(n) => Ok(n.as_bytes()),
314                _ => Err(Error::Type {
315                    expected: "name",
316                    context: "/Filter",
317                }),
318            })
319            .collect::<Result<_>>()?,
320        Some(_) => {
321            return Err(Error::Type {
322                expected: "name or array",
323                context: "/Filter",
324            });
325        }
326    };
327    if filters.len() > limits.max_filter_chain() {
328        return Err(Error::limit(Limit::FilterChain, None));
329    }
330    let all_parms = dict.get("DecodeParms");
331    let mut current: Option<Vec<u8>> = None;
332    let mut flate_truncated = false;
333    let document_limits = *limits;
334    for (i, filter) in filters.iter().enumerate() {
335        let input = current.as_deref().unwrap_or(data);
336        let parms = match all_parms {
337            Some(Object::Array(a)) => a.get(i).and_then(Object::as_dict),
338            Some(o) if i == 0 => o.as_dict(),
339            _ => None,
340        };
341        // A prefix read caps its last stage at the rows its first bytes need.
342        let stage_cap = flags
343            .want
344            .filter(|_| i + 1 == filters.len())
345            .map(|want| predicted_len(want, parms))
346            .filter(|&cap| cap < document_limits.max_stream_decoded());
347        flags.prefix = stage_cap.is_some();
348        let stage_limits = stage_cap.map_or(document_limits, |cap| document_limits.with_max_stream_decoded(cap));
349        let limits = &stage_limits;
350        let decoded = match full_name(filter) {
351            b"FlateDecode" => {
352                let raw = flate_stage(input, limits, budget, flags)?;
353                flate_truncated |= raw.flate_truncated;
354                apply_predictor(raw.data, parms)?
355            }
356            b"LZWDecode" => {
357                let early = int_param(parms, "EarlyChange", 1) != 0;
358                let raw = stage(input, limits, budget, flags, |data, out| lzw::decode(data, early, out))?;
359                apply_predictor(raw, parms)?
360            }
361            b"ASCIIHexDecode" => stage(input, limits, budget, flags, text::ascii_hex)?,
362            b"ASCII85Decode" => stage(input, limits, budget, flags, text::ascii85)?,
363            b"RunLengthDecode" => stage(input, limits, budget, flags, text::run_length)?,
364            other => return Err(Error::UnsupportedFilter(String::from_utf8_lossy(other).into_owned())),
365        };
366        current = Some(decoded);
367    }
368    Ok(Decoded {
369        data: current.unwrap_or_else(|| data.to_vec()),
370        flate_truncated,
371        characters_skipped: flags.skipped,
372    })
373}
374
375/// The bytes a filter must put out for its predictor (§7.4.4.4) to give `want` bytes: whole rows,
376/// each with its filter byte for a PNG predictor; `want` itself without a predictor, or with
377/// parameters the predictor refuses anyway.
378fn predicted_len(want: usize, parms: Option<&Dict>) -> usize {
379    let predictor = int_param(parms, "Predictor", 1);
380    if predictor <= 1 {
381        return want;
382    }
383    let colors = int_param(parms, "Colors", 1);
384    let bpc = int_param(parms, "BitsPerComponent", 8);
385    let columns = int_param(parms, "Columns", 1);
386    let row_bits = colors.checked_mul(bpc).and_then(|b| b.checked_mul(columns));
387    let Some(row) = row_bits.and_then(|b| usize::try_from(b).ok()).map(|b| b.div_ceil(8)) else {
388        return want;
389    };
390    if row == 0 {
391        return want;
392    }
393    let raw_row = if predictor >= 10 { row + 1 } else { row };
394    want.div_ceil(row).saturating_mul(raw_row)
395}
396
397fn int_param(parms: Option<&Dict>, key: &str, default: i64) -> i64 {
398    parms.and_then(|p| p.get_int(key)).unwrap_or(default)
399}
400
401fn apply_predictor(data: Vec<u8>, parms: Option<&Dict>) -> Result<Vec<u8>> {
402    let predictor = int_param(parms, "Predictor", 1);
403    if predictor <= 1 {
404        return Ok(data);
405    }
406    if predictor == 2 {
407        return tiff_unpredict(data, parms);
408    }
409    if !(10..=15).contains(&predictor) {
410        return Err(Error::UnsupportedFilter(format!("/Predictor {predictor}")));
411    }
412    let colors = int_param(parms, "Colors", 1);
413    let bpc = int_param(parms, "BitsPerComponent", 8);
414    let columns = int_param(parms, "Columns", 1);
415    let bad = |message| Error::InvalidStructure {
416        kind: "PNG predictor",
417        message,
418    };
419    if !(1..=32).contains(&colors) || ![1, 2, 4, 8, 16].contains(&bpc) || !(1..=1 << 24).contains(&columns) {
420        return Err(bad("parameters out of range"));
421    }
422    // Do the row-length math in u64 so it is exact on 32-bit targets (wasm32) as well:
423    // 32 colours × 16 bits × 2^24 columns is 2^33 bits, which would overflow a 32-bit usize.
424    let bits_per_pixel = u64::try_from(colors * bpc).map_err(|_| bad("overflow"))?;
425    let columns = u64::try_from(columns).map_err(|_| bad("overflow"))?;
426    let row_bits = bits_per_pixel.checked_mul(columns).ok_or(bad("overflow"))?;
427    let row_len = row_bits.div_ceil(8);
428    // A row is a filter byte plus `row_len` bytes, so a row wider than the whole input can
429    // never be complete. Rejecting it caps the `prev` row buffer at the input size instead
430    // of letting crafted parameters force a large allocation.
431    let input_len = u64::try_from(data.len()).map_err(|_| bad("overflow"))?;
432    if row_len > input_len.saturating_add(1) {
433        return Err(bad("row length exceeds stream data"));
434    }
435    let row_len = usize::try_from(row_len).map_err(|_| bad("overflow"))?;
436    let bpp = usize::try_from(bits_per_pixel.div_ceil(8).max(1)).map_err(|_| bad("overflow"))?;
437    png_unpredict(&data, row_len, bpp)
438}
439
440/// Reverses TIFF predictor 2 (horizontal differencing): each sample is the difference from the
441/// same component of the pixel to its left, for 8- and 16-bit samples.
442fn tiff_unpredict(mut data: Vec<u8>, parms: Option<&Dict>) -> Result<Vec<u8>> {
443    let colors = int_param(parms, "Colors", 1);
444    let bpc = int_param(parms, "BitsPerComponent", 8);
445    let columns = int_param(parms, "Columns", 1);
446    let bad = |message| Error::InvalidStructure {
447        kind: "TIFF predictor",
448        message,
449    };
450    if !(1..=32).contains(&colors) || !(1..=1 << 24).contains(&columns) {
451        return Err(bad("parameters out of range"));
452    }
453    let bytes = match bpc {
454        8 => 1,
455        16 => 2,
456        _ => {
457            return Err(Error::UnsupportedFilter(format!(
458                "/Predictor 2 with {bpc} bits per component"
459            )));
460        }
461    };
462    let colors = usize::try_from(colors).map_err(|_| bad("overflow"))?;
463    let columns = usize::try_from(columns).map_err(|_| bad("overflow"))?;
464    let pixel = colors * bytes;
465    let row = pixel.checked_mul(columns).ok_or(bad("overflow"))?;
466    for line in data.chunks_mut(row) {
467        for at in (pixel..line.len()).step_by(bytes) {
468            let left = at - pixel;
469            if bytes == 1 {
470                let value = line
471                    .get(at)
472                    .copied()
473                    .unwrap_or(0)
474                    .wrapping_add(line.get(left).copied().unwrap_or(0));
475                if let Some(slot) = line.get_mut(at) {
476                    *slot = value;
477                }
478            } else {
479                let read = |line: &[u8], i: usize| {
480                    u16::from_be_bytes([line.get(i).copied().unwrap_or(0), line.get(i + 1).copied().unwrap_or(0)])
481                };
482                let value = read(line, at).wrapping_add(read(line, left)).to_be_bytes();
483                if let Some(slot) = line.get_mut(at..at + 2) {
484                    slot.copy_from_slice(&value);
485                }
486            }
487        }
488    }
489    Ok(data)
490}
491
492/// Reverses PNG row filters. Each input row is a filter-type byte followed by `row_len`
493/// bytes; a short final row is decoded as far as it goes.
494fn png_unpredict(data: &[u8], row_len: usize, bpp: usize) -> Result<Vec<u8>> {
495    let mut out = Vec::with_capacity(data.len());
496    let mut prev = vec![0u8; row_len];
497    let mut cur = vec![0u8; row_len];
498    for chunk in data.chunks(row_len + 1) {
499        let Some((&kind, row)) = chunk.split_first() else {
500            continue;
501        };
502        let cur = cur.get_mut(..row.len()).unwrap_or_default();
503        unfilter_row(kind, row, &prev, cur, bpp)?;
504        out.extend_from_slice(cur);
505        prev.iter_mut().zip(&*cur).for_each(|(p, c)| *p = *c);
506    }
507    Ok(out)
508}
509
510/// Reverses one row's PNG filter (PNG §9.2): `raw` (the row after its filter-type byte) into
511/// `out`, given the previous row's unfiltered bytes (zeros for the first row) and the bytes
512/// per complete pixel (at least 1). Flate's PNG predictors (§7.4.4.4) and PNG images share it.
513///
514/// # Errors
515/// [`Error::InvalidStructure`] for a filter type other than 0–4.
516///
517/// Added in 0.2.0.
518pub fn unfilter_row(filter: u8, raw: &[u8], prev: &[u8], out: &mut [u8], bpp: usize) -> Result<()> {
519    for i in 0..raw.len() {
520        let x = raw.get(i).copied().unwrap_or(0);
521        let a = i.checked_sub(bpp).and_then(|j| out.get(j)).copied().unwrap_or(0);
522        let b = prev.get(i).copied().unwrap_or(0);
523        let c = i.checked_sub(bpp).and_then(|j| prev.get(j)).copied().unwrap_or(0);
524        let value = match filter {
525            0 => x,
526            1 => x.wrapping_add(a),
527            2 => x.wrapping_add(b),
528            3 => x.wrapping_add(a.midpoint(b)),
529            4 => x.wrapping_add(paeth(a, b, c)),
530            _ => {
531                return Err(Error::InvalidStructure {
532                    kind: "PNG predictor",
533                    message: "unknown row filter",
534                });
535            }
536        };
537        if let Some(o) = out.get_mut(i) {
538            *o = value;
539        }
540    }
541    Ok(())
542}
543
544/// The Paeth predictor (PNG §9.4): of `a` (left), `b` (up) and `c` (up-left), the one closest
545/// to `a + b - c`.
546///
547/// Added in 0.2.0.
548#[must_use]
549pub fn paeth(a: u8, b: u8, c: u8) -> u8 {
550    let (ia, ib, ic) = (i16::from(a), i16::from(b), i16::from(c));
551    let p = ia + ib - ic;
552    let (pa, pb, pc) = ((p - ia).abs(), (p - ib).abs(), (p - ic).abs());
553    if pa <= pb && pa <= pc {
554        a
555    } else if pb <= pc {
556        b
557    } else {
558        c
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565
566    fn limits(max_stream: usize) -> Limits {
567        Limits::default().with_max_stream_decoded(max_stream)
568    }
569
570    fn inflate(data: &[u8], max_stream: usize) -> Result<Vec<u8>> {
571        let limits = limits(max_stream);
572        flate_decode(data, &limits, &mut DecodeBudget::new(&limits)).map(|d| d.data)
573    }
574
575    fn decode_with(dict: &Dict, data: &[u8], max_stream: usize) -> Result<Vec<u8>> {
576        let limits = limits(max_stream);
577        decode(dict, data, &limits, &mut DecodeBudget::new(&limits)).map(|d| d.data)
578    }
579
580    fn flate_chain(n: usize) -> Dict {
581        [("Filter", Object::Array(vec![Object::name("FlateDecode"); n]))]
582            .into_iter()
583            .collect()
584    }
585
586    fn encode_times(data: &[u8], n: usize) -> Vec<u8> {
587        (0..n).fold(data.to_vec(), |acc, _| flate_encode(&acc))
588    }
589
590    fn predictor_parms(columns: i64) -> Dict {
591        [("Predictor", 12), ("Columns", columns)].into_iter().collect()
592    }
593
594    #[test]
595    fn flate_round_trips() {
596        let data = b"hello hello hello".to_vec();
597        assert_eq!(inflate(&flate_encode(&data), 1024), Ok(data));
598    }
599
600    #[test]
601    fn flate_decode_accepts_output_at_the_stream_limit() {
602        assert_eq!(inflate(&flate_encode(&[0u8; 1000]), 1000).map(|d| d.len()), Ok(1000));
603    }
604
605    #[test]
606    fn flate_decode_refuses_output_past_the_stream_limit() {
607        assert_eq!(
608            inflate(&flate_encode(&[0u8; 1001]), 1000),
609            Err(Error::LimitExceeded {
610                limit: Limit::StreamDecoded,
611                at: None
612            })
613        );
614    }
615
616    #[test]
617    fn flate_decode_charges_its_output_to_the_budget() {
618        let limits = Limits::default();
619        let mut budget = DecodeBudget::new(&limits);
620        flate_decode(&flate_encode(&[0u8; 100]), &limits, &mut budget).unwrap();
621        assert_eq!(budget.remaining(), limits.max_decoded_total() - 100);
622    }
623
624    #[test]
625    fn flate_decode_accepts_output_that_spends_the_whole_budget() {
626        let limits = Limits::default().with_max_decoded_total(100);
627        let mut budget = DecodeBudget::new(&limits);
628        assert!(flate_decode(&flate_encode(&[0u8; 100]), &limits, &mut budget).is_ok());
629    }
630
631    #[test]
632    fn flate_decode_refuses_output_past_the_remaining_budget() {
633        let limits = Limits::default().with_max_decoded_total(150);
634        let mut budget = DecodeBudget::new(&limits);
635        let data = flate_encode(&[0u8; 100]);
636        flate_decode(&data, &limits, &mut budget).unwrap();
637        assert_eq!(
638            flate_decode(&data, &limits, &mut budget),
639            Err(Error::LimitExceeded {
640                limit: Limit::DecodedTotal,
641                at: None
642            })
643        );
644    }
645
646    #[test]
647    fn flate_decode_keeps_truncated_output_and_flags_it() {
648        let full = flate_encode(&[7u8; 4000]);
649        let cut = full.get(..full.len() - 6).unwrap();
650        let limits = Limits::default();
651        let decoded = flate_decode(cut, &limits, &mut DecodeBudget::new(&limits)).unwrap();
652        assert!(decoded.flate_truncated && !decoded.data.is_empty());
653    }
654
655    #[test]
656    fn flate_decode_rejects_garbage() {
657        assert!(inflate(b"not zlib", 1000).is_err());
658    }
659
660    #[test]
661    fn decode_accepts_a_filter_chain_at_the_limit() {
662        let limits = Limits::default().with_max_filter_chain(3);
663        let decoded = decode(
664            &flate_chain(3),
665            &encode_times(b"x", 3),
666            &limits,
667            &mut DecodeBudget::new(&limits),
668        );
669        assert_eq!(decoded.map(|d| d.data), Ok(b"x".to_vec()));
670    }
671
672    #[test]
673    fn decode_rejects_a_filter_chain_past_the_limit() {
674        let limits = Limits::default().with_max_filter_chain(3);
675        assert_eq!(
676            decode(
677                &flate_chain(4),
678                &encode_times(b"x", 4),
679                &limits,
680                &mut DecodeBudget::new(&limits)
681            ),
682            Err(Error::LimitExceeded {
683                limit: Limit::FilterChain,
684                at: None
685            })
686        );
687    }
688
689    #[test]
690    fn decode_charges_every_stage_of_a_chain_to_the_budget() {
691        let limits = Limits::default();
692        let mut budget = DecodeBudget::new(&limits);
693        let encoded = encode_times(&[0u8; 1000], 2);
694        let once = flate_encode(&[0u8; 1000]).len();
695        decode(&flate_chain(2), &encoded, &limits, &mut budget).unwrap();
696        assert_eq!(budget.remaining(), limits.max_decoded_total() - 1000 - once);
697    }
698
699    #[test]
700    fn png_up_predictor_adds_previous_row() {
701        // Two rows of 2 columns, filter type 2 (Up).
702        let encoded = [2, 1, 2, 2, 1, 1];
703        assert_eq!(png_unpredict(&encoded, 2, 1), Ok(vec![1, 2, 2, 3]));
704    }
705
706    #[test]
707    fn png_paeth_and_sub_predictors_decode() {
708        let encoded = [1, 5, 1, 4, 0, 0];
709        assert_eq!(png_unpredict(&encoded, 2, 1), Ok(vec![5, 6, 5, 6]));
710    }
711
712    #[test]
713    fn decode_applies_predictor_after_flate() {
714        let dict: Dict = [
715            ("Filter", Object::name("FlateDecode")),
716            ("DecodeParms", Object::Dict(predictor_parms(2))),
717        ]
718        .into_iter()
719        .collect();
720        let encoded = flate_encode(&[2, 1, 2, 2, 1, 1]);
721        assert_eq!(decode_with(&dict, &encoded, 1024), Ok(vec![1, 2, 2, 3]));
722    }
723
724    #[test]
725    fn decode_should_reject_predictor_row_longer_than_stream_data() {
726        // 32 colours × 16 bits × 16,777,215 columns ≈ 1 GiB per row; the stream holds 6 bytes.
727        let parms: Dict = [
728            ("Predictor", 12),
729            ("Colors", 32),
730            ("BitsPerComponent", 16),
731            ("Columns", 16_777_215),
732        ]
733        .into_iter()
734        .collect();
735        let dict: Dict = [
736            ("Filter", Object::name("FlateDecode")),
737            ("DecodeParms", Object::Dict(parms)),
738        ]
739        .into_iter()
740        .collect();
741        let encoded = flate_encode(&[2, 1, 2, 2, 1, 1]);
742        assert_eq!(
743            decode_with(&dict, &encoded, 1024),
744            Err(Error::InvalidStructure {
745                kind: "PNG predictor",
746                message: "row length exceeds stream data",
747            })
748        );
749    }
750
751    #[test]
752    fn decode_should_reject_out_of_range_predictor_colors() {
753        let parms: Dict = [("Predictor", 12), ("Colors", 33)].into_iter().collect();
754        let dict: Dict = [
755            ("Filter", Object::name("FlateDecode")),
756            ("DecodeParms", Object::Dict(parms)),
757        ]
758        .into_iter()
759        .collect();
760        assert!(decode_with(&dict, &flate_encode(&[0, 1]), 1024).is_err());
761    }
762
763    #[test]
764    fn decode_runs_a_chain_of_text_and_lzw_filters() {
765        // "Hello" as hex, then that text as ASCII85: decoded in the chain's order.
766        let dict: Dict = [("Filter", Object::Array(vec![Object::name("A85"), Object::name("AHx")]))]
767            .into_iter()
768            .collect();
769        assert_eq!(decode_with(&dict, b"1cRBN2IeXT2J,,~>", 100), Ok(b"Hello".to_vec()));
770    }
771
772    #[test]
773    fn decode_charges_a_text_filter_to_the_limits() {
774        let dict: Dict = [("Filter", Object::name("RunLengthDecode"))].into_iter().collect();
775        assert!(matches!(
776            decode_with(&dict, &[200, b'x'], 10),
777            Err(Error::LimitExceeded { .. })
778        ));
779    }
780
781    #[test]
782    fn tiff_predictor_adds_the_pixel_to_the_left() {
783        let parms: Dict = [("Predictor", 2), ("Colors", 2), ("Columns", 3)].into_iter().collect();
784        assert_eq!(
785            apply_predictor(vec![1, 10, 1, 1, 1, 1, 5, 5, 0, 0, 1, 2], Some(&parms)),
786            Ok(vec![1, 10, 2, 11, 3, 12, 5, 5, 5, 5, 6, 7])
787        );
788    }
789
790    #[test]
791    fn decode_reports_unsupported_filter() {
792        let dict: Dict = [("Filter", Object::name("DCTDecode"))].into_iter().collect();
793        assert_eq!(
794            decode_with(&dict, b"", 10),
795            Err(Error::UnsupportedFilter("DCTDecode".into()))
796        );
797    }
798
799    #[test]
800    fn decode_does_not_pass_crypt_through() {
801        // Undecrypted data must never be treated as plaintext: the reader strips `/Crypt`
802        // only after decrypting.
803        let dict: Dict = [("Filter", Object::name("Crypt"))].into_iter().collect();
804        assert_eq!(
805            decode_with(&dict, b"x", 10),
806            Err(Error::UnsupportedFilter("Crypt".into()))
807        );
808    }
809
810    fn prefix(dict: &Dict, data: &[u8], max: usize) -> Result<Prefix> {
811        let limits = Limits::default();
812        decode_prefix(dict, data, &limits, &mut DecodeBudget::new(&limits), max)
813    }
814
815    #[test]
816    fn a_prefix_of_a_bomb_decodes_only_what_is_asked_and_one_byte_more() {
817        let bomb = flate_encode(&vec![7u8; Limits::default().max_stream_decoded() + 1]);
818        let limits = Limits::default();
819        let mut budget = DecodeBudget::new(&limits);
820        let read = decode_prefix(&flate_chain(1), &bomb, &limits, &mut budget, 16).unwrap();
821        assert_eq!((read.decoded.data, read.complete), (vec![7u8; 16], false));
822        // At most 17 bytes were decoded, so the call's budget is nearly whole.
823        assert!(budget.remaining() >= limits.max_decoded_total() - 17);
824    }
825
826    #[test]
827    fn a_prefix_as_long_as_the_stream_is_complete() {
828        let read = prefix(&flate_chain(1), &flate_encode(b"BT ET"), 5).unwrap();
829        assert_eq!((read.decoded.data.as_slice(), read.complete), (&b"BT ET"[..], true));
830    }
831
832    #[test]
833    fn a_prefix_through_a_text_filter_stops_at_the_cap() {
834        let dict: Dict = [("Filter", Object::name("ASCIIHexDecode"))].into_iter().collect();
835        let read = prefix(&dict, b"414243444546>", 3).unwrap();
836        assert_eq!((read.decoded.data.as_slice(), read.complete), (&b"ABC"[..], false));
837    }
838
839    #[test]
840    fn a_prefix_past_the_stream_limit_is_refused_as_decode_refuses_it() {
841        let bomb = flate_encode(&vec![0u8; 2000]);
842        let limits = limits(1000);
843        let read = decode_prefix(&flate_chain(1), &bomb, &limits, &mut DecodeBudget::new(&limits), 5000);
844        assert!(matches!(
845            read,
846            Err(Error::LimitExceeded {
847                limit: Limit::StreamDecoded,
848                ..
849            })
850        ));
851    }
852
853    /// `data` decoded whole, and its first `max` bytes as a prefix read decodes them.
854    fn whole_and_prefix(dict: &Dict, data: &[u8], max: usize) -> (Vec<u8>, Prefix) {
855        let limits = Limits::default();
856        let whole = decode(dict, data, &limits, &mut DecodeBudget::new(&limits))
857            .unwrap()
858            .data;
859        (whole, prefix(dict, data, max).unwrap())
860    }
861
862    fn chain(names: &[&str]) -> Dict {
863        [("Filter", Object::Array(names.iter().map(|n| Object::name(n)).collect()))]
864            .into_iter()
865            .collect()
866    }
867
868    fn text_of(n: usize) -> Vec<u8> {
869        (0..n).map(|i| b'a' + u8::try_from(i % 26).unwrap()).collect()
870    }
871
872    #[test]
873    fn a_prefix_through_hex_then_flate_is_the_start_of_the_whole() {
874        let hex: Vec<u8> = flate_encode(&text_of(5000))
875            .iter()
876            .flat_map(|b| format!("{b:02x}").into_bytes())
877            .collect();
878        let (whole, read) = whole_and_prefix(&chain(&["AHx", "Fl"]), &hex, 100);
879        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..100], false));
880        assert!(!read.decoded.flate_truncated);
881    }
882
883    #[test]
884    fn a_prefix_through_two_flates_is_the_start_of_the_whole() {
885        let twice = flate_encode(&flate_encode(&text_of(5000)));
886        let (whole, read) = whole_and_prefix(&chain(&["FlateDecode", "FlateDecode"]), &twice, 100);
887        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..100], false));
888    }
889
890    #[test]
891    fn a_prefix_through_a_png_predictor_wider_than_it_is_the_start_of_the_whole() {
892        // Rows of 5000 bytes, each with the Up filter byte (2).
893        let rows: Vec<u8> = (0..4)
894            .flat_map(|r| [vec![2u8], vec![u8::try_from(r).unwrap(); 5000]].concat())
895            .collect();
896        let parms: Dict = [("Predictor", Object::from(12)), ("Columns", Object::from(5000))]
897            .into_iter()
898            .collect();
899        let dict: Dict = [
900            ("Filter", Object::name("FlateDecode")),
901            ("DecodeParms", Object::Dict(parms)),
902        ]
903        .into_iter()
904        .collect();
905        let (whole, read) = whole_and_prefix(&dict, &flate_encode(&rows), 10);
906        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..10], false));
907    }
908}