pdfcer-model 0.186.0

pdfcer COS model layer: objects, lexer, parser, filters, xref, object streams, recovery, Document/DocumentView, the full and incremental writer, standard-handler crypto, content parsing and the page tree. Depends on nothing else in the workspace; re-exported by pdfcer-core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! # Stream filters (ISO 32000-1 §7.4) — the decode pipeline
//!
//! Decodes stream data through its `/Filter` chain. Spec sources:
//! `filter__pipeline.md` (cascade rules), `filter__flate.md`,
//! `filter__predictors.md` in the PDF-spec RAG; Table 5 of
//! `iso32000__s__7.3.8.md` for the `/Filter`//`/DecodeParms` shapes.
//! Clause numbers are ISO 32000-1:2008.
//!
//! ## Fail-clean is a TYPE-LEVEL contract here
//!
//! Every decoder returns `Result<Vec<u8>, FilterError>`, and **no code
//! path returns undecoded or partial bytes as if they had decoded**
//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 4).
//! This is a deliberate divergence from observed prior art: the audited
//! oxidize-pdf filter layer falls back to returning raw bytes when
//! zlib/predictor decoding fails, which silently corrupts downstream
//! consumers. pdfcer's corrupted-stream regression tests (one per
//! filter) pin the opposite behavior: corrupt in → `Err` out, never
//! plausible-looking garbage. Truncated-but-partially-decodable
//! streams also `Err` in Pass 1; a *labeled* best-effort mode for
//! damaged-file recovery is a later, explicit, corpus-driven feature —
//! never a silent default.
//!
//! ## Resource ceiling (ARCHITECTURE.md §10.1 — pdfcer policy, not spec)
//!
//! Deflate's worst case is ~1032:1 expansion — a 1 MB stream can claim
//! a gigabyte. Every decode enforces [`MAX_DECODED_LEN`] *incrementally*
//! (abort mid-decode when crossed, never inflate-then-check). `/DL` is
//! a hint (Table 5) and is deliberately NOT the bound.
//!
//! ## This module handles BYTE-STREAM filters only (decision 005 R23)
//!
//! A byte-stream filter consumes bytes, produces bytes, and composes
//! with the next stage of the cascade. An **image codec** —
//! `DCTDecode`, `CCITTFaxDecode`, `JBIG2Decode`, `JPXDecode` — does
//! not: its output is *samples* whose geometry and colour model are
//! declared by the codestream itself, and §8.9.5 Table 89 goes as far
//! as making the codestream's declarations **outrank the image
//! dictionary** for JPXDecode. A `Vec<u8>` return type has nowhere to
//! put that information, and re-deriving it would mean parsing hostile
//! input twice.
//!
//! So [`decode_stream`] never decodes an image codec. Reaching one
//! returns [`FilterError::ImageCodec`], which says "this is a codec,
//! decode it through `pdfcer_core::image_codec`" — deliberately distinct
//! from [`FilterError::UnsupportedFilter`], which says "pdfcer does not
//! implement this filter at all." The full rationale is in
//! `docs/decisions/005-image-codecs.md` §1.2, §4.6 and §5.2.
//!
//! ## Coverage
//!
//! - **FlateDecode** (with PNG/TIFF predictors) — object streams, xref
//!   streams, content streams, and most images.
//! - **ASCIIHexDecode / ASCII85Decode** ([`ascii`]) — the ASCII
//!   armouring filters. They compress nothing, but they are the only
//!   two filters that make an inline image's data length unambiguous
//!   (§8.9.7), which is why they land with the image-rendering slice
//!   rather than later.
//! - **LZWDecode** ([`lzw`], Pass 2.1) — legacy but still present in
//!   pre-PDF-1.2 files and legacy tooling output. Shares the predictor
//!   stage with Flate; `/EarlyChange` is its one extra parameter.
//! - **RunLengthDecode** ([`runlength`], Pass 2.1) — trivial, no
//!   parameters, self-limiting.
//!
//! Any other name — a codec handled elsewhere, a crypt filter, or
//! something non-standard — is *recognized* and refused with a precise
//! diagnostic rather than guessed at, the same detect-don't-misparse
//! posture as the xref layer.
//!
//! ## Notes vs errors
//!
//! Some streams decode correctly while still being *non-conformant* in
//! a way an operator should be able to see (an LZW stream with no
//! `ClearCode`, for instance). Those are counted in [`FilterNotes`] and
//! surfaced by [`decode_stream_with_notes`] — "fuzzy, never sneaky"
//! applied at the filter layer. [`decode_stream`] is the same decode
//! with the notes dropped, for the many callers (xref streams, object
//! streams, content streams) that have nowhere to put them.

pub mod ascii;
/// `/BrotliDecode` — a PDF Association EXTENSION, not ISO 32000-2. See the
/// module docs before believing any citation you find for it.
pub mod brotli;
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)] // test assertions
mod cancel_tests;
pub mod flate;
pub mod lzw;
pub mod predictor;
pub mod runlength;
mod stream;

pub use stream::{MAX_DECODE_RATIO, ReadStatus, StreamDecoder};

use crate::object::{Dict, Object};

/// Hard ceiling on a single stream's decoded size.
///
/// pdfcer policy (ARCHITECTURE.md §10.1): no Annex C limit exists for
/// this; 256 MiB decoded is beyond any legitimate single stream
/// (content streams are KBs; even a 300-DPI A4 uncompressed RGB image
/// is ~35 MB) while bounding a decompression bomb's blast radius.
pub const MAX_DECODED_LEN: usize = 256 * 1024 * 1024;

/// Scratch-chunk size every incremental decoder works in: large enough
/// to amortize the per-call overhead, small enough that a ceiling
/// overshoots by a negligible amount.
pub(crate) const CHUNK: usize = 64 * 1024;

/// A decoder that produces its output a chunk at a time.
///
/// Both the whole-stream decode ([`drain`]) and the windowed
/// [`StreamDecoder`] drive the same `pull`, so the two cannot disagree
/// about a stream's bytes.
pub(crate) trait Pull {
    /// Append the next chunk to `out`; `Ok(true)` once the stream has
    /// ended (anything appended by that call is still output).
    fn pull(&mut self, out: &mut Vec<u8>) -> Result<bool, FilterError>;
}

/// How far one filter stage may decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Bound {
    /// Decode to the end; crossing [`MAX_DECODED_LEN`] is an error.
    Ceiling,
    /// Decode this many bytes and stop: the caller knows the stage's
    /// output length (an image's `h * ceil(w*nc*bpc/8)`), so bytes past it
    /// are never produced and the ceiling does not apply.
    StopAt(usize),
}

impl Bound {
    /// The bound on the bytes a stage produces BEFORE its predictor runs.
    /// A PNG predictor adds one tag byte per row, so the pre-predictor
    /// length is `rows * (row + 1)` with `rows = ceil(n / row)`.
    fn before(self, params: Option<&predictor::Params>) -> Self {
        match (self, params) {
            (Self::StopAt(n), Some(p)) if p.predictor >= 10 => {
                let row = p.row_data_bytes().max(1);
                Self::StopAt(n.div_ceil(row).saturating_mul(row.saturating_add(1)))
            }
            (b, _) => b,
        }
    }

    /// Cut a stage's output to the bound.
    fn clip(self, mut out: Vec<u8>) -> Vec<u8> {
        if let Self::StopAt(n) = self {
            out.truncate(n);
        }
        out
    }
}

/// Run `p` to its end, or to `bound`, asking `cancelled` before every
/// [`CHUNK`]-sized pull.
pub(crate) fn drain(
    p: &mut impl Pull,
    bound: Bound,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    let mut out = Vec::new();
    loop {
        if cancelled() {
            return Err(FilterError::Cancelled);
        }
        let done = p.pull(&mut out)?;
        match bound {
            Bound::StopAt(n) if out.len() >= n => return Ok(bound.clip(out)),
            Bound::Ceiling if out.len() > MAX_DECODED_LEN => {
                return Err(FilterError::OutputTooLarge);
            }
            _ => {}
        }
        if done {
            return Ok(out);
        }
    }
}

/// [`drain`] followed by the stage's `/Predictor` from `parms`, with the
/// bound applied to the predicted output.
pub(crate) fn drain_predicted(
    p: &mut impl Pull,
    parms: Option<&Dict>,
    bound: Bound,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    let params = predictor::Params::from_dict(parms)?;
    let raw = drain(p, bound.before(params.as_ref()), cancelled)?;
    let out = match params {
        None => raw,
        Some(p) => predictor::unpredict_polled(raw, &p, cancelled)?,
    };
    Ok(bound.clip(out))
}

/// The poll the uncancellable entry points pass: never cancelled.
pub(crate) fn never_cancelled() -> bool {
    false
}

/// A filter-decode error.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum FilterError {
    /// The compressed data is invalid (bad zlib header, corrupt
    /// deflate stream, checksum structurally unreadable, …).
    #[error("corrupt {filter} data: {detail}")]
    Corrupt {
        /// Which filter failed.
        filter: &'static str,
        /// Human-readable failure detail from the underlying decoder.
        detail: String,
    },
    /// The stream ended before the filter's own end-of-data — a
    /// truncated stream (§7.3.8.2 extent inconsistency).
    #[error("{filter} stream truncated")]
    Truncated {
        /// Which filter detected the truncation.
        filter: &'static str,
    },
    /// Decoded output crossed [`MAX_DECODED_LEN`] (pdfcer guard) — the
    /// decode was aborted mid-stream.
    #[error("decoded output exceeds MAX_DECODED_LEN ({MAX_DECODED_LEN} bytes)")]
    OutputTooLarge,
    /// `/DecodeParms` carried an invalid parameter combination
    /// (unknown `Predictor` value, zero `Columns`, bad
    /// `BitsPerComponent`, …).
    #[error("invalid decode parameters: {0}")]
    BadParams(&'static str),
    /// Predicted data length is not a whole number of rows — wrong
    /// parameters or truncation (`filter__predictors.md` row
    /// arithmetic).
    #[error("predicted data is not a whole number of rows")]
    RaggedRows,
    /// A PNG row carried an algorithm tag outside 0–4 (RFC 2083 §6:
    /// an error).
    #[error("unknown PNG predictor tag {0}")]
    UnknownPngTag(u8),
    /// A standard filter pdfcer doesn't implement yet (Pass 1 scope).
    /// The payload is the filter name as written.
    #[error("filter {0:?} is not yet supported")]
    UnsupportedFilter(String),
    /// The chain reaches an image codec, which [`decode_stream`] does
    /// not handle **by design** (decision 005 R23). Decode it through
    /// `pdfcer_core::image_codec::decode_image`, which has the `&Document`
    /// and the image dictionary that these codecs require, and which
    /// returns the codec-declared geometry and colour model that a
    /// `Vec<u8>` cannot carry.
    ///
    /// Deliberately distinct from [`FilterError::UnsupportedFilter`]:
    /// that one means "pdfcer cannot decode this at all", this one means
    /// "you called the wrong entry point." A caller that only wants
    /// bytes (an xref stream, an object stream) genuinely cannot
    /// proceed, so it is still an error there — but the operator-facing
    /// message stays honest about which of the two situations it is.
    #[error("filter {0:?} is an image codec; decode it via image_codec::decode_image")]
    ImageCodec(String),
    /// `/Filter` held something other than a name or array of names.
    #[error("malformed /Filter entry")]
    BadFilterEntry,
    /// The caller's cancel poll answered `true` mid-decode
    /// ([`decode_stream_cancellable`]); no partial output is returned.
    #[error("decode cancelled by the caller")]
    Cancelled,
}

/// Divergences that did **not** stop a stream from decoding.
///
/// Separate from [`FilterError`] because the operator's question is
/// different: an error means "these bytes are unusable", a note means
/// "these bytes are fine but the file that produced them is not
/// conformant." Accumulated across the whole `/Filter` chain.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FilterNotes {
    /// LZW streams that did not begin with a `ClearCode`, or that ended
    /// without an `EndOfInformation`. Both are non-conformant (TIFF 6.0
    /// §13; ISO 32000-1 §7.4.4.2), both are recovered, both are
    /// reported. See [`lzw`] for the sourced recovery rules.
    pub lzw_framing_anomalies: usize,
}

/// Decode a stream's raw bytes through its full `/Filter` chain.
///
/// `dict` is the stream dictionary; `raw` its encoded bytes (the
/// `data_span` slice). Handles the Table 5 shapes: `/Filter` absent
/// (identity), a single name, or an array of zero or more names
/// applied **in array order** (decode order = written order, Table 5);
/// `/DecodeParms` correspondingly a dict, an array (with `null` for
/// parameterless positions), or absent.
///
/// # Errors
///
/// [`FilterError`] — see the variants; fail-clean per the module docs.
pub fn decode_stream(dict: &Dict, raw: &[u8]) -> Result<Vec<u8>, FilterError> {
    decode_stream_with_notes(dict, raw).map(|(data, _)| data)
}

/// [`decode_stream`], keeping the non-fatal [`FilterNotes`].
///
/// Use this wherever the notes have somewhere to go — the image path
/// surfaces them in the renderer's diagnostics. Every other caller
/// (xref streams, object streams, content streams) has no diagnostics
/// channel and uses [`decode_stream`].
///
/// # Errors
///
/// Identical to [`decode_stream`].
pub fn decode_stream_with_notes(
    dict: &Dict,
    raw: &[u8],
) -> Result<(Vec<u8>, FilterNotes), FilterError> {
    let filters = filter_names(dict)?;
    let mut notes = FilterNotes::default();
    let data = decode_prefix(dict, raw, filters.len(), &mut notes)?;
    Ok((data, notes))
}

/// [`decode_stream_with_notes`], abandoning the decode once `cancelled`
/// returns `true`.
///
/// `cancelled` is polled before each filter stage, before every
/// 64 KiB chunk the Flate, LZW, Brotli and RunLength decoders produce,
/// and once per row of a `/Predictor` stage, so a caller that stops
/// wanting a large stream waits for one chunk or row rather than the
/// whole decode. `ASCIIHexDecode` and `ASCII85Decode` run each stage
/// whole. The [`MAX_DECODED_LEN`] ceiling applies unchanged.
///
/// The poll is a plain closure so the caller chooses the flag (an
/// `AtomicBool`, a render token, a deadline); it should be cheap, since
/// it runs once per chunk and row.
///
/// # Errors
///
/// As [`decode_stream`], plus [`FilterError::Cancelled`] once
/// `cancelled` returns `true`. No partial output is returned.
///
/// # Examples
///
/// ```
/// use pdfcer_model::filters::{FilterError, decode_stream_cancellable};
/// use pdfcer_model::object::{Dict, Name, Object};
///
/// let mut dict = Dict::new();
/// dict.insert(Name::from(b"Filter"), Object::Name(Name::from(b"ASCIIHexDecode")));
///
/// let (bytes, _notes) = decode_stream_cancellable(&dict, b"4869>", &|| false)?;
/// assert_eq!(bytes, b"Hi");
///
/// let refused = decode_stream_cancellable(&dict, b"4869>", &|| true);
/// assert_eq!(refused, Err(FilterError::Cancelled));
/// # Ok::<(), FilterError>(())
/// ```
pub fn decode_stream_cancellable(
    dict: &Dict,
    raw: &[u8],
    cancelled: &dyn Fn() -> bool,
) -> Result<(Vec<u8>, FilterNotes), FilterError> {
    let filters = filter_names(dict)?;
    let mut notes = FilterNotes::default();
    let data = decode_prefix_polled(dict, raw, filters.len(), &mut notes, cancelled)?;
    Ok((data, notes))
}

/// Apply the first `take` filters of `dict`'s chain to `raw`.
///
/// Exists so `pdfcer_core::image_codec` can run the **byte-stream prefix**
/// of a chain that ends in an image codec (e.g.
/// `/Filter [/ASCII85Decode /DCTDecode]`, which is a real and legal
/// shape) and then dispatch the terminal codec itself. `take` equal to
/// the full chain length is the ordinary [`decode_stream`] case.
///
/// # Errors
///
/// [`FilterError`] from any stage; in particular
/// [`FilterError::ImageCodec`] if a codec name falls inside the prefix,
/// which means the caller mis-computed where the chain's byte-stream
/// part ends.
#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
pub fn decode_prefix(
    dict: &Dict,
    raw: &[u8],
    take: usize,
    notes: &mut FilterNotes,
) -> Result<Vec<u8>, FilterError> {
    decode_prefix_polled(dict, raw, take, notes, &never_cancelled)
}

/// [`decode_prefix_polled`] for a prefix whose output length the caller
/// already knows (an uncoded image's `h * ceil(w*nc*bpc/8)`, decision
/// 227): the last stage stops after `expected` bytes and never decodes
/// the rest, and [`MAX_DECODED_LEN`] does not apply to it, so a
/// legitimate image larger than the ceiling decodes. Earlier stages keep
/// the ceiling. The caller refuses an `expected` the raw bytes could not
/// produce, and budgets the memory.
///
/// # Errors
///
/// As [`decode_prefix_polled`].
#[doc(hidden)] // workspace-internal: called by pdfcer-image-codec, not API
pub fn decode_prefix_bounded(
    dict: &Dict,
    raw: &[u8],
    take: usize,
    expected: usize,
    notes: &mut FilterNotes,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    decode_prefix_inner(dict, raw, take, Some(expected), notes, cancelled)
}

/// [`decode_prefix`] under a cancel poll, as [`decode_stream_cancellable`]
/// describes.
///
/// # Errors
///
/// As [`decode_prefix`], plus [`FilterError::Cancelled`].
#[doc(hidden)] // workspace-internal: called by pdfcer-image-codec, not API
pub fn decode_prefix_polled(
    dict: &Dict,
    raw: &[u8],
    take: usize,
    notes: &mut FilterNotes,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    decode_prefix_inner(dict, raw, take, None, notes, cancelled)
}

fn decode_prefix_inner(
    dict: &Dict,
    raw: &[u8],
    take: usize,
    expected: Option<usize>,
    notes: &mut FilterNotes,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    let filters = filter_names(dict)?;
    let take = take.min(filters.len());
    let mut data: Vec<u8> = raw.to_vec();
    for (i, name) in filters.iter().enumerate().take(take) {
        if cancelled() {
            return Err(FilterError::Cancelled);
        }
        let parms = decode_parms_for(dict, i, filters.len());
        let bound = match expected {
            Some(n) if i + 1 == take => Bound::StopAt(n),
            _ => Bound::Ceiling,
        };
        data = apply_one(name, parms, &data, bound, notes, cancelled)?;
    }
    Ok(data)
}

/// Apply a single named filter.
///
/// Abbreviated spellings (Table 94) are accepted alongside the full
/// names because inline images legally use them; `pdfcer_model::content`
/// normalizes the ones it sees, but a stream dictionary that spells a
/// filter the short way is not worth refusing.
fn apply_one(
    name: &[u8],
    parms: Option<&Dict>,
    data: &[u8],
    bound: Bound,
    notes: &mut FilterNotes,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
    match name {
        b"FlateDecode" | b"Fl" => flate::decode_polled(data, parms, bound, cancelled),
        // EXTN-BROTLI-1 §5.2. NO ABBREVIATION: the extension defines none,
        // and Table 92's abbreviations exist for inline images, which this
        // filter `SHALL NOT` be used for. MuPDF accepts a `/Br` alias that
        // does not exist in the extension -- that is MuPDF's behaviour, not
        // the specification, and pdfcer does not follow it. Accepting `/Br`
        // would make pdfcer read files no conformant writer produces and no
        // other reader agrees on.
        b"BrotliDecode" => brotli::decode_polled(data, parms, bound, cancelled),
        // §7.4.2/§7.4.3 — parameterless (Table 6), so `parms` is
        // deliberately not forwarded.
        b"ASCIIHexDecode" | b"AHx" => ascii::decode_hex(data).map(|d| bound.clip(d)),
        b"ASCII85Decode" | b"A85" => ascii::decode_85(data).map(|d| bound.clip(d)),
        b"LZWDecode" | b"LZW" => lzw::decode_polled(data, parms, bound, notes, cancelled),
        // §7.4.5 — parameterless (Table 6).
        b"RunLengthDecode" | b"RL" => runlength::decode_polled(data, bound, cancelled),
        // Image codecs are a TERMINAL stage, not a byte-stream filter
        // (R23). Named separately so the operator-facing message says
        // "wrong entry point", not "unsupported".
        b"DCTDecode" | b"DCT" | b"CCITTFaxDecode" | b"CCF" | b"JBIG2Decode" | b"JPXDecode"
        | b"JXLDecode" => Err(FilterError::ImageCodec(
            String::from_utf8_lossy(name).into_owned(),
        )),
        // Anything else: a crypt filter, or a non-standard name.
        // Refused with a precise diagnostic rather than guessed at.
        other => Err(FilterError::UnsupportedFilter(
            String::from_utf8_lossy(other).into_owned(),
        )),
    }
}

/// Extract the ordered filter-name list from `/Filter` (name, array of
/// names, or absent → empty).
#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
    match dict.get(b"Filter") {
        None => Ok(Vec::new()),
        Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
        Some(Object::Array(items)) => items
            .iter()
            .map(|o| match o {
                Object::Name(n) => Ok(n.as_bytes().to_vec()),
                _ => Err(FilterError::BadFilterEntry),
            })
            .collect(),
        Some(_) => Err(FilterError::BadFilterEntry),
    }
}

/// The `/DecodeParms` entry for filter position `i` of `total`
/// (Table 5 shape rules). `None` = defaults. A malformed entry is
/// treated as absent — the individual filter then validates whatever
/// it actually needs; parameters it never looks at can't hurt it.
fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
    match parms {
        Object::Dict(d) if total == 1 => Some(d),
        Object::Array(items) => match items.get(i) {
            Some(Object::Dict(d)) => Some(d),
            _ => None, // null / absent position = defaults (Table 5)
        },
        _ => None,
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing
)]
mod tests {
    use super::*;
    use crate::object::Name;

    fn dict_with_filter(filter: Object) -> Dict {
        let mut d = Dict::new();
        d.insert(Name::from(b"Filter"), filter);
        d
    }

    fn png_flate(columns: i64) -> Dict {
        let mut parms = Dict::new();
        parms.insert(Name::from(b"Predictor"), Object::Integer(10));
        parms.insert(Name::from(b"Columns"), Object::Integer(columns));
        let mut d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
        d.insert(Name::from(b"DecodeParms"), Object::Dict(parms));
        d
    }

    #[test]
    fn a_bounded_prefix_stops_at_the_expected_length_through_a_png_predictor() {
        // Four PNG `None` rows of two bytes; the caller expects five.
        let rows = [0u8, 1, 2, 0, 3, 4, 0, 5, 6, 0, 7, 8];
        let raw = flate::encode(&rows);
        let mut notes = FilterNotes::default();
        let out =
            decode_prefix_bounded(&png_flate(2), &raw, 1, 5, &mut notes, &never_cancelled).unwrap();
        assert_eq!(out, [1, 2, 3, 4, 5]);
    }

    #[test]
    fn a_bounded_prefix_bounds_only_its_last_stage() {
        // ASCIIHex then Flate: the hex stage decodes whole, the Flate stage
        // stops at three bytes.
        let inner = flate::encode(b"abcdef");
        let hex: Vec<u8> = inner
            .iter()
            .flat_map(|b| format!("{b:02x}").into_bytes())
            .collect();
        let d = dict_with_filter(Object::Array(vec![
            Object::Name(Name::from(b"ASCIIHexDecode")),
            Object::Name(Name::from(b"FlateDecode")),
        ]));
        let mut notes = FilterNotes::default();
        let out = decode_prefix_bounded(&d, &hex, 2, 3, &mut notes, &never_cancelled).unwrap();
        assert_eq!(out, b"abc");
    }

    #[test]
    fn no_filter_is_identity() {
        let d = Dict::new();
        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
    }

    #[test]
    fn empty_filter_array_is_identity() {
        // Table 5: an array of ZERO names is legal.
        let d = dict_with_filter(Object::Array(vec![]));
        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
    }

    #[test]
    fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
        // R23: `decode_stream` never decodes a codec, and says so in a
        // way distinguishable from "pdfcer cannot do this at all".
        for name in [
            &b"DCTDecode"[..],
            b"CCITTFaxDecode",
            b"JBIG2Decode",
            b"JPXDecode",
            b"JXLDecode",
        ] {
            let d = dict_with_filter(Object::Name(Name::from(name)));
            let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
            assert_eq!(
                e,
                FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
            );
        }
    }

    #[test]
    fn unsupported_filter_is_named_in_error() {
        let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
        let e = decode_stream(&d, b"anything").unwrap_err();
        assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
    }

    /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
    ///
    /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
    /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
    /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
    /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
    /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
    ///
    /// This is a behaviour-versus-specification split, and following the
    /// behaviour would be the worse choice in both directions — pdfcer would
    /// read files no conformant writer emits, and would disagree with every
    /// reader that is not MuPDF. Pinned as a test so a future reader who
    /// meets a `/Br` in the wild adds it deliberately, with a decision
    /// record, rather than as an obvious-looking omission.
    #[test]
    fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
        let mut notes = FilterNotes::default();
        let e = apply_one(
            b"Br",
            None,
            b"anything",
            Bound::Ceiling,
            &mut notes,
            &never_cancelled,
        )
        .unwrap_err();
        assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
    }

    /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
    ///
    /// Asserted through the DISPATCH rather than by calling `brotli::decode`
    /// directly: the filter module's own tests prove the decoder works, and
    /// this proves the name is wired to it. Those are different claims, and
    /// `Pass 2.x`'s history has an instance of each passing while the other
    /// failed.
    #[test]
    fn brotli_decode_is_dispatched_and_not_refused() {
        let mut notes = FilterNotes::default();
        // Deliberately invalid Brotli. Success here would mean the name was
        // silently ignored; what must happen is that the BROTLI decoder
        // refuses it, which is a differently-shaped error from
        // `UnsupportedFilter` and is what distinguishes "wired" from "not".
        let e = apply_one(
            b"BrotliDecode",
            None,
            &[0xff; 32],
            Bound::Ceiling,
            &mut notes,
            &never_cancelled,
        )
        .unwrap_err();
        assert!(
            !matches!(e, FilterError::UnsupportedFilter(_)),
            "/BrotliDecode must reach its decoder, got {e:?}"
        );
    }

    #[test]
    fn runlength_runs_in_the_cascade() {
        let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
        assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
    }

    #[test]
    fn lzw_notes_reach_the_caller_through_the_cascade() {
        // A stream that does not begin with a ClearCode still decodes,
        // and the non-conformance is COUNTED rather than absorbed.
        let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
        let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
        assert_eq!(data, b"A");
        assert_eq!(notes.lzw_framing_anomalies, 1);
    }

    #[test]
    fn non_name_filter_entry_is_error() {
        let d = dict_with_filter(Object::Integer(5));
        assert_eq!(
            decode_stream(&d, b"x").unwrap_err(),
            FilterError::BadFilterEntry
        );
    }

    #[test]
    fn flate_roundtrip_via_pipeline() {
        use flate2::Compression;
        use flate2::write::ZlibEncoder;
        use std::io::Write as _;

        let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
        enc.write_all(&original).unwrap();
        let compressed = enc.finish().unwrap();

        let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
        assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
    }
}