Skip to main content

pdfcer_model/filters/
mod.rs

1//! # Stream filters (ISO 32000-1 §7.4) — the decode pipeline
2//!
3//! Decodes stream data through its `/Filter` chain. Spec sources:
4//! `filter__pipeline.md` (cascade rules), `filter__flate.md`,
5//! `filter__predictors.md` in the PDF-spec RAG; Table 5 of
6//! `iso32000__s__7.3.8.md` for the `/Filter`//`/DecodeParms` shapes.
7//! Clause numbers are ISO 32000-1:2008.
8//!
9//! ## Fail-clean is a TYPE-LEVEL contract here
10//!
11//! Every decoder returns `Result<Vec<u8>, FilterError>`, and **no code
12//! path returns undecoded or partial bytes as if they had decoded**
13//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 4).
14//! This is a deliberate divergence from observed prior art: the audited
15//! oxidize-pdf filter layer falls back to returning raw bytes when
16//! zlib/predictor decoding fails, which silently corrupts downstream
17//! consumers. pdfcer's corrupted-stream regression tests (one per
18//! filter) pin the opposite behavior: corrupt in → `Err` out, never
19//! plausible-looking garbage. Truncated-but-partially-decodable
20//! streams also `Err` in Pass 1; a *labeled* best-effort mode for
21//! damaged-file recovery is a later, explicit, corpus-driven feature —
22//! never a silent default.
23//!
24//! ## Resource ceiling (ARCHITECTURE.md §10.1 — pdfcer policy, not spec)
25//!
26//! Deflate's worst case is ~1032:1 expansion — a 1 MB stream can claim
27//! a gigabyte. Every decode enforces [`MAX_DECODED_LEN`] *incrementally*
28//! (abort mid-decode when crossed, never inflate-then-check). `/DL` is
29//! a hint (Table 5) and is deliberately NOT the bound.
30//!
31//! ## This module handles BYTE-STREAM filters only (decision 005 R23)
32//!
33//! A byte-stream filter consumes bytes, produces bytes, and composes
34//! with the next stage of the cascade. An **image codec** —
35//! `DCTDecode`, `CCITTFaxDecode`, `JBIG2Decode`, `JPXDecode` — does
36//! not: its output is *samples* whose geometry and colour model are
37//! declared by the codestream itself, and §8.9.5 Table 89 goes as far
38//! as making the codestream's declarations **outrank the image
39//! dictionary** for JPXDecode. A `Vec<u8>` return type has nowhere to
40//! put that information, and re-deriving it would mean parsing hostile
41//! input twice.
42//!
43//! So [`decode_stream`] never decodes an image codec. Reaching one
44//! returns [`FilterError::ImageCodec`], which says "this is a codec,
45//! decode it through `pdfcer_core::image_codec`" — deliberately distinct
46//! from [`FilterError::UnsupportedFilter`], which says "pdfcer does not
47//! implement this filter at all." The full rationale is in
48//! `docs/decisions/005-image-codecs.md` §1.2, §4.6 and §5.2.
49//!
50//! ## Coverage
51//!
52//! - **FlateDecode** (with PNG/TIFF predictors) — object streams, xref
53//!   streams, content streams, and most images.
54//! - **ASCIIHexDecode / ASCII85Decode** ([`ascii`]) — the ASCII
55//!   armouring filters. They compress nothing, but they are the only
56//!   two filters that make an inline image's data length unambiguous
57//!   (§8.9.7), which is why they land with the image-rendering slice
58//!   rather than later.
59//! - **LZWDecode** ([`lzw`], Pass 2.1) — legacy but still present in
60//!   pre-PDF-1.2 files and legacy tooling output. Shares the predictor
61//!   stage with Flate; `/EarlyChange` is its one extra parameter.
62//! - **RunLengthDecode** ([`runlength`], Pass 2.1) — trivial, no
63//!   parameters, self-limiting.
64//!
65//! Any other name — a codec handled elsewhere, a crypt filter, or
66//! something non-standard — is *recognized* and refused with a precise
67//! diagnostic rather than guessed at, the same detect-don't-misparse
68//! posture as the xref layer.
69//!
70//! ## Notes vs errors
71//!
72//! Some streams decode correctly while still being *non-conformant* in
73//! a way an operator should be able to see (an LZW stream with no
74//! `ClearCode`, for instance). Those are counted in [`FilterNotes`] and
75//! surfaced by [`decode_stream_with_notes`] — "fuzzy, never sneaky"
76//! applied at the filter layer. [`decode_stream`] is the same decode
77//! with the notes dropped, for the many callers (xref streams, object
78//! streams, content streams) that have nowhere to put them.
79
80pub mod ascii;
81/// `/BrotliDecode` — a PDF Association EXTENSION, not ISO 32000-2. See the
82/// module docs before believing any citation you find for it.
83pub mod brotli;
84#[cfg(test)]
85#[allow(clippy::unwrap_used, clippy::indexing_slicing)] // test assertions
86mod cancel_tests;
87pub mod flate;
88pub mod lzw;
89pub mod predictor;
90pub mod runlength;
91mod stream;
92
93pub use stream::{MAX_DECODE_RATIO, ReadStatus, StreamDecoder};
94
95use crate::object::{Dict, Object};
96
97/// Hard ceiling on a single stream's decoded size.
98///
99/// pdfcer policy (ARCHITECTURE.md §10.1): no Annex C limit exists for
100/// this; 256 MiB decoded is beyond any legitimate single stream
101/// (content streams are KBs; even a 300-DPI A4 uncompressed RGB image
102/// is ~35 MB) while bounding a decompression bomb's blast radius.
103pub const MAX_DECODED_LEN: usize = 256 * 1024 * 1024;
104
105/// Scratch-chunk size every incremental decoder works in: large enough
106/// to amortize the per-call overhead, small enough that a ceiling
107/// overshoots by a negligible amount.
108pub(crate) const CHUNK: usize = 64 * 1024;
109
110/// A decoder that produces its output a chunk at a time.
111///
112/// Both the whole-stream decode ([`drain`]) and the windowed
113/// [`StreamDecoder`] drive the same `pull`, so the two cannot disagree
114/// about a stream's bytes.
115pub(crate) trait Pull {
116    /// Append the next chunk to `out`; `Ok(true)` once the stream has
117    /// ended (anything appended by that call is still output).
118    fn pull(&mut self, out: &mut Vec<u8>) -> Result<bool, FilterError>;
119}
120
121/// Run `p` to its end under [`MAX_DECODED_LEN`], asking `cancelled`
122/// before every [`CHUNK`]-sized pull.
123pub(crate) fn drain(
124    p: &mut impl Pull,
125    cancelled: &dyn Fn() -> bool,
126) -> Result<Vec<u8>, FilterError> {
127    let mut out = Vec::new();
128    loop {
129        if cancelled() {
130            return Err(FilterError::Cancelled);
131        }
132        let done = p.pull(&mut out)?;
133        if out.len() > MAX_DECODED_LEN {
134            return Err(FilterError::OutputTooLarge);
135        }
136        if done {
137            return Ok(out);
138        }
139    }
140}
141
142/// The poll the uncancellable entry points pass: never cancelled.
143pub(crate) fn never_cancelled() -> bool {
144    false
145}
146
147/// A filter-decode error.
148#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
149#[non_exhaustive]
150pub enum FilterError {
151    /// The compressed data is invalid (bad zlib header, corrupt
152    /// deflate stream, checksum structurally unreadable, …).
153    #[error("corrupt {filter} data: {detail}")]
154    Corrupt {
155        /// Which filter failed.
156        filter: &'static str,
157        /// Human-readable failure detail from the underlying decoder.
158        detail: String,
159    },
160    /// The stream ended before the filter's own end-of-data — a
161    /// truncated stream (§7.3.8.2 extent inconsistency).
162    #[error("{filter} stream truncated")]
163    Truncated {
164        /// Which filter detected the truncation.
165        filter: &'static str,
166    },
167    /// Decoded output crossed [`MAX_DECODED_LEN`] (pdfcer guard) — the
168    /// decode was aborted mid-stream.
169    #[error("decoded output exceeds MAX_DECODED_LEN ({MAX_DECODED_LEN} bytes)")]
170    OutputTooLarge,
171    /// `/DecodeParms` carried an invalid parameter combination
172    /// (unknown `Predictor` value, zero `Columns`, bad
173    /// `BitsPerComponent`, …).
174    #[error("invalid decode parameters: {0}")]
175    BadParams(&'static str),
176    /// Predicted data length is not a whole number of rows — wrong
177    /// parameters or truncation (`filter__predictors.md` row
178    /// arithmetic).
179    #[error("predicted data is not a whole number of rows")]
180    RaggedRows,
181    /// A PNG row carried an algorithm tag outside 0–4 (RFC 2083 §6:
182    /// an error).
183    #[error("unknown PNG predictor tag {0}")]
184    UnknownPngTag(u8),
185    /// A standard filter pdfcer doesn't implement yet (Pass 1 scope).
186    /// The payload is the filter name as written.
187    #[error("filter {0:?} is not yet supported")]
188    UnsupportedFilter(String),
189    /// The chain reaches an image codec, which [`decode_stream`] does
190    /// not handle **by design** (decision 005 R23). Decode it through
191    /// `pdfcer_core::image_codec::decode_image`, which has the `&Document`
192    /// and the image dictionary that these codecs require, and which
193    /// returns the codec-declared geometry and colour model that a
194    /// `Vec<u8>` cannot carry.
195    ///
196    /// Deliberately distinct from [`FilterError::UnsupportedFilter`]:
197    /// that one means "pdfcer cannot decode this at all", this one means
198    /// "you called the wrong entry point." A caller that only wants
199    /// bytes (an xref stream, an object stream) genuinely cannot
200    /// proceed, so it is still an error there — but the operator-facing
201    /// message stays honest about which of the two situations it is.
202    #[error("filter {0:?} is an image codec; decode it via image_codec::decode_image")]
203    ImageCodec(String),
204    /// `/Filter` held something other than a name or array of names.
205    #[error("malformed /Filter entry")]
206    BadFilterEntry,
207    /// The caller's cancel poll answered `true` mid-decode
208    /// ([`decode_stream_cancellable`]); no partial output is returned.
209    #[error("decode cancelled by the caller")]
210    Cancelled,
211}
212
213/// Divergences that did **not** stop a stream from decoding.
214///
215/// Separate from [`FilterError`] because the operator's question is
216/// different: an error means "these bytes are unusable", a note means
217/// "these bytes are fine but the file that produced them is not
218/// conformant." Accumulated across the whole `/Filter` chain.
219#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
220#[non_exhaustive]
221pub struct FilterNotes {
222    /// LZW streams that did not begin with a `ClearCode`, or that ended
223    /// without an `EndOfInformation`. Both are non-conformant (TIFF 6.0
224    /// §13; ISO 32000-1 §7.4.4.2), both are recovered, both are
225    /// reported. See [`lzw`] for the sourced recovery rules.
226    pub lzw_framing_anomalies: usize,
227}
228
229/// Decode a stream's raw bytes through its full `/Filter` chain.
230///
231/// `dict` is the stream dictionary; `raw` its encoded bytes (the
232/// `data_span` slice). Handles the Table 5 shapes: `/Filter` absent
233/// (identity), a single name, or an array of zero or more names
234/// applied **in array order** (decode order = written order, Table 5);
235/// `/DecodeParms` correspondingly a dict, an array (with `null` for
236/// parameterless positions), or absent.
237///
238/// # Errors
239///
240/// [`FilterError`] — see the variants; fail-clean per the module docs.
241pub fn decode_stream(dict: &Dict, raw: &[u8]) -> Result<Vec<u8>, FilterError> {
242    decode_stream_with_notes(dict, raw).map(|(data, _)| data)
243}
244
245/// [`decode_stream`], keeping the non-fatal [`FilterNotes`].
246///
247/// Use this wherever the notes have somewhere to go — the image path
248/// surfaces them in the renderer's diagnostics. Every other caller
249/// (xref streams, object streams, content streams) has no diagnostics
250/// channel and uses [`decode_stream`].
251///
252/// # Errors
253///
254/// Identical to [`decode_stream`].
255pub fn decode_stream_with_notes(
256    dict: &Dict,
257    raw: &[u8],
258) -> Result<(Vec<u8>, FilterNotes), FilterError> {
259    let filters = filter_names(dict)?;
260    let mut notes = FilterNotes::default();
261    let data = decode_prefix(dict, raw, filters.len(), &mut notes)?;
262    Ok((data, notes))
263}
264
265/// [`decode_stream_with_notes`], abandoning the decode once `cancelled`
266/// returns `true`.
267///
268/// `cancelled` is polled before each filter stage, before every
269/// 64 KiB chunk the Flate, LZW, Brotli and RunLength decoders produce,
270/// and once per row of a `/Predictor` stage, so a caller that stops
271/// wanting a large stream waits for one chunk or row rather than the
272/// whole decode. `ASCIIHexDecode` and `ASCII85Decode` run each stage
273/// whole. The [`MAX_DECODED_LEN`] ceiling applies unchanged.
274///
275/// The poll is a plain closure so the caller chooses the flag (an
276/// `AtomicBool`, a render token, a deadline); it should be cheap, since
277/// it runs once per chunk and row.
278///
279/// # Errors
280///
281/// As [`decode_stream`], plus [`FilterError::Cancelled`] once
282/// `cancelled` returns `true`. No partial output is returned.
283///
284/// # Examples
285///
286/// ```
287/// use pdfcer_model::filters::{FilterError, decode_stream_cancellable};
288/// use pdfcer_model::object::{Dict, Name, Object};
289///
290/// let mut dict = Dict::new();
291/// dict.insert(Name::from(b"Filter"), Object::Name(Name::from(b"ASCIIHexDecode")));
292///
293/// let (bytes, _notes) = decode_stream_cancellable(&dict, b"4869>", &|| false)?;
294/// assert_eq!(bytes, b"Hi");
295///
296/// let refused = decode_stream_cancellable(&dict, b"4869>", &|| true);
297/// assert_eq!(refused, Err(FilterError::Cancelled));
298/// # Ok::<(), FilterError>(())
299/// ```
300pub fn decode_stream_cancellable(
301    dict: &Dict,
302    raw: &[u8],
303    cancelled: &dyn Fn() -> bool,
304) -> Result<(Vec<u8>, FilterNotes), FilterError> {
305    let filters = filter_names(dict)?;
306    let mut notes = FilterNotes::default();
307    let data = decode_prefix_polled(dict, raw, filters.len(), &mut notes, cancelled)?;
308    Ok((data, notes))
309}
310
311/// Apply the first `take` filters of `dict`'s chain to `raw`.
312///
313/// Exists so `pdfcer_core::image_codec` can run the **byte-stream prefix**
314/// of a chain that ends in an image codec (e.g.
315/// `/Filter [/ASCII85Decode /DCTDecode]`, which is a real and legal
316/// shape) and then dispatch the terminal codec itself. `take` equal to
317/// the full chain length is the ordinary [`decode_stream`] case.
318///
319/// # Errors
320///
321/// [`FilterError`] from any stage; in particular
322/// [`FilterError::ImageCodec`] if a codec name falls inside the prefix,
323/// which means the caller mis-computed where the chain's byte-stream
324/// part ends.
325#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
326pub fn decode_prefix(
327    dict: &Dict,
328    raw: &[u8],
329    take: usize,
330    notes: &mut FilterNotes,
331) -> Result<Vec<u8>, FilterError> {
332    decode_prefix_polled(dict, raw, take, notes, &never_cancelled)
333}
334
335/// [`decode_prefix`] under a cancel poll, as [`decode_stream_cancellable`]
336/// describes.
337///
338/// # Errors
339///
340/// As [`decode_prefix`], plus [`FilterError::Cancelled`].
341#[doc(hidden)] // workspace-internal: called by pdfcer-image-codec, not API
342pub fn decode_prefix_polled(
343    dict: &Dict,
344    raw: &[u8],
345    take: usize,
346    notes: &mut FilterNotes,
347    cancelled: &dyn Fn() -> bool,
348) -> Result<Vec<u8>, FilterError> {
349    let filters = filter_names(dict)?;
350    let mut data: Vec<u8> = raw.to_vec();
351    for (i, name) in filters.iter().enumerate().take(take) {
352        if cancelled() {
353            return Err(FilterError::Cancelled);
354        }
355        let parms = decode_parms_for(dict, i, filters.len());
356        data = apply_one(name, parms, &data, notes, cancelled)?;
357    }
358    Ok(data)
359}
360
361/// Apply a single named filter.
362///
363/// Abbreviated spellings (Table 94) are accepted alongside the full
364/// names because inline images legally use them; `pdfcer_model::content`
365/// normalizes the ones it sees, but a stream dictionary that spells a
366/// filter the short way is not worth refusing.
367fn apply_one(
368    name: &[u8],
369    parms: Option<&Dict>,
370    data: &[u8],
371    notes: &mut FilterNotes,
372    cancelled: &dyn Fn() -> bool,
373) -> Result<Vec<u8>, FilterError> {
374    match name {
375        b"FlateDecode" | b"Fl" => flate::decode_polled(data, parms, cancelled),
376        // EXTN-BROTLI-1 §5.2. NO ABBREVIATION: the extension defines none,
377        // and Table 92's abbreviations exist for inline images, which this
378        // filter `SHALL NOT` be used for. MuPDF accepts a `/Br` alias that
379        // does not exist in the extension -- that is MuPDF's behaviour, not
380        // the specification, and pdfcer does not follow it. Accepting `/Br`
381        // would make pdfcer read files no conformant writer produces and no
382        // other reader agrees on.
383        b"BrotliDecode" => brotli::decode_polled(data, parms, cancelled),
384        // §7.4.2/§7.4.3 — parameterless (Table 6), so `parms` is
385        // deliberately not forwarded.
386        b"ASCIIHexDecode" | b"AHx" => ascii::decode_hex(data),
387        b"ASCII85Decode" | b"A85" => ascii::decode_85(data),
388        b"LZWDecode" | b"LZW" => lzw::decode_polled(data, parms, notes, cancelled),
389        // §7.4.5 — parameterless (Table 6).
390        b"RunLengthDecode" | b"RL" => runlength::decode_polled(data, cancelled),
391        // Image codecs are a TERMINAL stage, not a byte-stream filter
392        // (R23). Named separately so the operator-facing message says
393        // "wrong entry point", not "unsupported".
394        b"DCTDecode" | b"DCT" | b"CCITTFaxDecode" | b"CCF" | b"JBIG2Decode" | b"JPXDecode"
395        | b"JXLDecode" => Err(FilterError::ImageCodec(
396            String::from_utf8_lossy(name).into_owned(),
397        )),
398        // Anything else: a crypt filter, or a non-standard name.
399        // Refused with a precise diagnostic rather than guessed at.
400        other => Err(FilterError::UnsupportedFilter(
401            String::from_utf8_lossy(other).into_owned(),
402        )),
403    }
404}
405
406/// Extract the ordered filter-name list from `/Filter` (name, array of
407/// names, or absent → empty).
408#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
409pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
410    match dict.get(b"Filter") {
411        None => Ok(Vec::new()),
412        Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
413        Some(Object::Array(items)) => items
414            .iter()
415            .map(|o| match o {
416                Object::Name(n) => Ok(n.as_bytes().to_vec()),
417                _ => Err(FilterError::BadFilterEntry),
418            })
419            .collect(),
420        Some(_) => Err(FilterError::BadFilterEntry),
421    }
422}
423
424/// The `/DecodeParms` entry for filter position `i` of `total`
425/// (Table 5 shape rules). `None` = defaults. A malformed entry is
426/// treated as absent — the individual filter then validates whatever
427/// it actually needs; parameters it never looks at can't hurt it.
428fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
429    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
430    match parms {
431        Object::Dict(d) if total == 1 => Some(d),
432        Object::Array(items) => match items.get(i) {
433            Some(Object::Dict(d)) => Some(d),
434            _ => None, // null / absent position = defaults (Table 5)
435        },
436        _ => None,
437    }
438}
439
440#[cfg(test)]
441#[allow(
442    clippy::unwrap_used,
443    clippy::expect_used,
444    clippy::panic,
445    clippy::indexing_slicing
446)]
447mod tests {
448    use super::*;
449    use crate::object::Name;
450
451    fn dict_with_filter(filter: Object) -> Dict {
452        let mut d = Dict::new();
453        d.insert(Name::from(b"Filter"), filter);
454        d
455    }
456
457    #[test]
458    fn no_filter_is_identity() {
459        let d = Dict::new();
460        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
461    }
462
463    #[test]
464    fn empty_filter_array_is_identity() {
465        // Table 5: an array of ZERO names is legal.
466        let d = dict_with_filter(Object::Array(vec![]));
467        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
468    }
469
470    #[test]
471    fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
472        // R23: `decode_stream` never decodes a codec, and says so in a
473        // way distinguishable from "pdfcer cannot do this at all".
474        for name in [
475            &b"DCTDecode"[..],
476            b"CCITTFaxDecode",
477            b"JBIG2Decode",
478            b"JPXDecode",
479            b"JXLDecode",
480        ] {
481            let d = dict_with_filter(Object::Name(Name::from(name)));
482            let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
483            assert_eq!(
484                e,
485                FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
486            );
487        }
488    }
489
490    #[test]
491    fn unsupported_filter_is_named_in_error() {
492        let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
493        let e = decode_stream(&d, b"anything").unwrap_err();
494        assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
495    }
496
497    /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
498    ///
499    /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
500    /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
501    /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
502    /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
503    /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
504    ///
505    /// This is a behaviour-versus-specification split, and following the
506    /// behaviour would be the worse choice in both directions — pdfcer would
507    /// read files no conformant writer emits, and would disagree with every
508    /// reader that is not MuPDF. Pinned as a test so a future reader who
509    /// meets a `/Br` in the wild adds it deliberately, with a decision
510    /// record, rather than as an obvious-looking omission.
511    #[test]
512    fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
513        let mut notes = FilterNotes::default();
514        let e = apply_one(b"Br", None, b"anything", &mut notes, &never_cancelled).unwrap_err();
515        assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
516    }
517
518    /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
519    ///
520    /// Asserted through the DISPATCH rather than by calling `brotli::decode`
521    /// directly: the filter module's own tests prove the decoder works, and
522    /// this proves the name is wired to it. Those are different claims, and
523    /// `Pass 2.x`'s history has an instance of each passing while the other
524    /// failed.
525    #[test]
526    fn brotli_decode_is_dispatched_and_not_refused() {
527        let mut notes = FilterNotes::default();
528        // Deliberately invalid Brotli. Success here would mean the name was
529        // silently ignored; what must happen is that the BROTLI decoder
530        // refuses it, which is a differently-shaped error from
531        // `UnsupportedFilter` and is what distinguishes "wired" from "not".
532        let e = apply_one(
533            b"BrotliDecode",
534            None,
535            &[0xff; 32],
536            &mut notes,
537            &never_cancelled,
538        )
539        .unwrap_err();
540        assert!(
541            !matches!(e, FilterError::UnsupportedFilter(_)),
542            "/BrotliDecode must reach its decoder, got {e:?}"
543        );
544    }
545
546    #[test]
547    fn runlength_runs_in_the_cascade() {
548        let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
549        assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
550    }
551
552    #[test]
553    fn lzw_notes_reach_the_caller_through_the_cascade() {
554        // A stream that does not begin with a ClearCode still decodes,
555        // and the non-conformance is COUNTED rather than absorbed.
556        let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
557        let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
558        assert_eq!(data, b"A");
559        assert_eq!(notes.lzw_framing_anomalies, 1);
560    }
561
562    #[test]
563    fn non_name_filter_entry_is_error() {
564        let d = dict_with_filter(Object::Integer(5));
565        assert_eq!(
566            decode_stream(&d, b"x").unwrap_err(),
567            FilterError::BadFilterEntry
568        );
569    }
570
571    #[test]
572    fn flate_roundtrip_via_pipeline() {
573        use flate2::Compression;
574        use flate2::write::ZlibEncoder;
575        use std::io::Write as _;
576
577        let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
578        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
579        enc.write_all(&original).unwrap();
580        let compressed = enc.finish().unwrap();
581
582        let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
583        assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
584    }
585}