laminapdf-syntax 0.7.0

PDF syntax in Rust: the object model, lexer and parser, stream filters, decryption, and resource limits for untrusted input.
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
//! Stream filters (ISO 32000-1 ยง7.4): `FlateDecode` (via `miniz_oxide`), `LZWDecode`,
//! `ASCIIHexDecode`, `ASCII85Decode` and `RunLengthDecode`, with the PNG and TIFF predictors.
//! The image codecs (DCT, JPX, CCITT, JBIG2) are left to their readers: [`decode`] reports them
//! as unsupported.
//!
//! Decoding is bounded by [`Limits`]: every filter stage's output is capped by
//! [`Limits::max_stream_decoded`] and charged to the call's [`DecodeBudget`]
//! ([`Limits::max_decoded_total`]), and a `/Filter` chain may hold at most
//! [`Limits::max_filter_chain`] filters.
//!
//! ```
//! use laminapdf_syntax::filters::{decode, flate_encode};
//! use laminapdf_syntax::{DecodeBudget, Dict, Limits, Object};
//!
//! let dict: Dict = [("Filter", Object::name("FlateDecode"))].into_iter().collect();
//! let limits = Limits::default();
//! let mut budget = DecodeBudget::new(&limits);
//! let decoded = decode(&dict, &flate_encode(b"hello"), &limits, &mut budget)?;
//! assert_eq!(decoded.data, b"hello");
//! assert!(!decoded.flate_truncated);
//! assert_eq!(budget.remaining(), limits.max_decoded_total() - 5);
//! # Ok::<(), laminapdf_syntax::Error>(())
//! ```

use miniz_oxide::inflate::TINFLStatus;

use crate::error::{Error, Result};
use crate::limits::{DecodeBudget, Limit, Limits};
use crate::object::{Dict, Object};

mod lzw;
mod text;

/// A filter's data that can't be decoded, with what is wrong.
const fn bad(message: &'static str) -> Error {
    Error::InvalidStructure {
        kind: "stream filter",
        message,
    }
}

/// A filter stage's output, refused past its cap with the limit it would break.
struct Output {
    data: Vec<u8>,
    cap: usize,
    over: Limit,
    /// The filter skipped characters outside its alphabet ([`Decoded::characters_skipped`]).
    skipped: bool,
}

impl Output {
    const fn new(cap: usize, over: Limit) -> Self {
        Self {
            data: Vec::new(),
            cap,
            over,
            skipped: false,
        }
    }

    /// The cap for a stage of a call within `limits`, with `budget` left.
    fn within(limits: &Limits, budget: DecodeBudget) -> Self {
        let stream_cap = limits.max_stream_decoded();
        if budget.remaining() < stream_cap {
            Self::new(budget.remaining(), Limit::DecodedTotal)
        } else {
            Self::new(stream_cap, Limit::StreamDecoded)
        }
    }

    fn room(&self, more: usize) -> Result<()> {
        if self.data.len().saturating_add(more) > self.cap {
            return Err(Error::limit(self.over, None));
        }
        Ok(())
    }

    fn push(&mut self, byte: u8) -> Result<()> {
        self.room(1)?;
        self.data.push(byte);
        Ok(())
    }

    fn extend(&mut self, bytes: &[u8]) -> Result<()> {
        self.room(bytes.len())?;
        self.data.extend_from_slice(bytes);
        Ok(())
    }

    fn fill(&mut self, byte: u8, count: usize) -> Result<()> {
        self.room(count)?;
        self.data.resize(self.data.len() + count, byte);
        Ok(())
    }

    fn set(&mut self, at: usize, byte: u8) {
        if let Some(slot) = self.data.get_mut(at) {
            *slot = byte;
        }
    }

    const fn len(&self) -> usize {
        self.data.len()
    }

    /// Notes that the filter skipped a character outside its alphabet.
    const fn skip(&mut self) {
        self.skipped = true;
    }

    fn into_inner(self) -> Vec<u8> {
        self.data
    }
}

/// Runs `filter` on `input` within `limits`, charging its output to `budget`; sets `skipped`
/// when the filter skipped characters outside its alphabet.
fn stage(
    input: &[u8],
    limits: &Limits,
    budget: &mut DecodeBudget,
    flags: &mut Flags,
    filter: impl FnOnce(&[u8], &mut Output) -> Result<()>,
) -> Result<Vec<u8>> {
    let mut out = Output::within(limits, *budget);
    match filter(input, &mut out) {
        // A prefix read stops at its cap and keeps what it has (`decode_prefix`).
        Err(Error::LimitExceeded {
            limit: Limit::StreamDecoded,
            ..
        }) if flags.prefix => flags.cut = true,
        other => other?,
    }
    flags.skipped |= out.skipped;
    let data = out.into_inner();
    budget.spend(data.len());
    Ok(data)
}

/// Decoded stream data.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Decoded {
    /// The decoded bytes.
    pub data: Vec<u8>,
    /// True when Flate data was truncated or had a bad checksum and the partial output was
    /// kept (the reader reports it as the `flate-truncated` warning).
    pub flate_truncated: bool,
    /// True when `ASCIIHexDecode` or `ASCII85Decode` data held characters outside the filter's
    /// alphabet, which were skipped as other readers skip them (the reader reports it as the
    /// `filter-characters-skipped` warning).
    ///
    /// Added in 0.4.0.
    pub characters_skipped: bool,
}

/// Zlib-compresses `data` at the default level (6).
///
/// Added in 0.2.0.
#[must_use]
pub fn flate_encode(data: &[u8]) -> Vec<u8> {
    miniz_oxide::deflate::compress_to_vec_zlib(data, 6)
}

/// Inflates zlib `data`, refusing output larger than [`Limits::max_stream_decoded`] or than
/// what is left of `budget`, and charges the output to `budget`.
///
/// Truncated streams and bad checksums are tolerated when some output was produced, as
/// real-world readers do ([`Decoded::flate_truncated`] reports it).
///
/// # Errors
/// [`Error::LimitExceeded`] ([`Limit::StreamDecoded`] or [`Limit::DecodedTotal`]) when the
/// output would exceed either cap, [`Error::Decompress`] when the data is not inflatable at all.
///
/// Added in 0.2.0.
pub fn flate_decode(data: &[u8], limits: &Limits, budget: &mut DecodeBudget) -> Result<Decoded> {
    flate_stage(data, limits, budget, &mut Flags::default())
}

/// [`flate_decode`], keeping the output so far when a prefix read reaches its cap.
fn flate_stage(data: &[u8], limits: &Limits, budget: &mut DecodeBudget, flags: &mut Flags) -> Result<Decoded> {
    let stream_cap = limits.max_stream_decoded();
    let (cap, over) = if budget.remaining() < stream_cap {
        (budget.remaining(), Limit::DecodedTotal)
    } else {
        (stream_cap, Limit::StreamDecoded)
    };
    let (data, flate_truncated) = match miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, cap) {
        Ok(out) => (out, false),
        Err(e) => match e.status {
            TINFLStatus::HasMoreOutput if flags.prefix && over == Limit::StreamDecoded => {
                flags.cut = true;
                (e.output, false)
            }
            TINFLStatus::HasMoreOutput => return Err(Error::limit(over, None)),
            TINFLStatus::Adler32Mismatch | TINFLStatus::FailedCannotMakeProgress if !e.output.is_empty() => {
                (e.output, true)
            }
            _ => return Err(Error::Decompress("invalid zlib data")),
        },
    };
    budget.spend(data.len());
    Ok(Decoded {
        data,
        flate_truncated,
        characters_skipped: false,
    })
}

/// A filter's full name for its inline-image abbreviation (ISO 32000-2 ยง8.9.7, Table 92):
/// `AHx` is `ASCIIHexDecode`, `CCF` is `CCITTFaxDecode`โ€ฆ; a full name comes back as it is.
///
/// Added in 0.4.0.
#[must_use]
pub fn full_name(name: &[u8]) -> &[u8] {
    match name {
        b"AHx" => b"ASCIIHexDecode",
        b"A85" => b"ASCII85Decode",
        b"LZW" => b"LZWDecode",
        b"Fl" => b"FlateDecode",
        b"RL" => b"RunLengthDecode",
        b"CCF" => b"CCITTFaxDecode",
        b"DCT" => b"DCTDecode",
        other => other,
    }
}

/// Decodes stream `data` according to `/Filter` and `/DecodeParms` in `dict`, within
/// `limits` and `budget` (see the [module docs](self)).
///
/// `dict` values are expected to be direct (the reader resolves references first). Data
/// without a filter is returned as is and costs no budget.
///
/// # Errors
/// [`Error::UnsupportedFilter`] for the image codecs (DCT, JPX, CCITT, JBIG2) and `/Crypt` (decryption needs
/// the file key, so the reader decrypts the stream when it loads it and removes `/Crypt` from
/// the chain before calling this), [`Error::LimitExceeded`] for a chain longer than
/// [`Limits::max_filter_chain`] or output over a decode limit, plus any decode error.
///
/// Added in 0.2.0.
pub fn decode(dict: &Dict, data: &[u8], limits: &Limits, budget: &mut DecodeBudget) -> Result<Decoded> {
    decode_with(dict, data, limits, budget, &mut Flags::default())
}

/// The first bytes of a stream ([`decode_prefix`]) and whether they are all of it.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Prefix {
    /// At most the bytes asked for, decoded.
    pub decoded: Decoded,
    /// Whether the stream decodes to no more than these bytes.
    pub complete: bool,
}

/// The first `max` bytes `data` decodes to, as [`decode`] decodes them, decoding at most one byte
/// more to know whether there is more: a viewer that shows the start of a stream never decodes
/// the rest. `limits` still apply, so when `max` is at or past
/// [`Limits::max_stream_decoded`] a longer stream is refused as [`decode`] refuses it.
///
/// # Errors
/// As [`decode`].
///
/// Added in 0.6.0.
pub fn decode_prefix(
    dict: &Dict,
    data: &[u8],
    limits: &Limits,
    budget: &mut DecodeBudget,
    max: usize,
) -> Result<Prefix> {
    let mut flags = Flags {
        want: Some(max.saturating_add(1)),
        ..Flags::default()
    };
    let mut decoded = decode_with(dict, data, limits, budget, &mut flags)?;
    let complete = !flags.cut && decoded.data.len() <= max;
    decoded.data.truncate(max);
    Ok(Prefix { decoded, complete })
}

/// What a decode notes as it goes, and whether it reads a prefix.
#[derive(Debug, Default)]
struct Flags {
    /// A prefix read: the bytes the chain's output needs (`max` + 1). Only the last stage stops
    /// early; the ones before it decode under the document's limits, since a later filter needs
    /// its whole input to decode the first bytes right.
    want: Option<usize>,
    /// The current stage reads a prefix: it stops at the stream cap and keeps its output.
    prefix: bool,
    /// A stage stopped at the cap.
    cut: bool,
    /// Characters outside a filter's alphabet were skipped.
    skipped: bool,
}

fn decode_with(
    dict: &Dict,
    data: &[u8],
    limits: &Limits,
    budget: &mut DecodeBudget,
    flags: &mut Flags,
) -> Result<Decoded> {
    let filters: Vec<&[u8]> = match dict.get("Filter") {
        None | Some(Object::Null) => Vec::new(),
        Some(Object::Name(n)) => vec![n.as_bytes()],
        Some(Object::Array(items)) => items
            .iter()
            .map(|o| match o {
                Object::Name(n) => Ok(n.as_bytes()),
                _ => Err(Error::Type {
                    expected: "name",
                    context: "/Filter",
                }),
            })
            .collect::<Result<_>>()?,
        Some(_) => {
            return Err(Error::Type {
                expected: "name or array",
                context: "/Filter",
            });
        }
    };
    if filters.len() > limits.max_filter_chain() {
        return Err(Error::limit(Limit::FilterChain, None));
    }
    let all_parms = dict.get("DecodeParms");
    let mut current: Option<Vec<u8>> = None;
    let mut flate_truncated = false;
    let document_limits = *limits;
    for (i, filter) in filters.iter().enumerate() {
        let input = current.as_deref().unwrap_or(data);
        let parms = match all_parms {
            Some(Object::Array(a)) => a.get(i).and_then(Object::as_dict),
            Some(o) if i == 0 => o.as_dict(),
            _ => None,
        };
        // A prefix read caps its last stage at the rows its first bytes need.
        let stage_cap = flags
            .want
            .filter(|_| i + 1 == filters.len())
            .map(|want| predicted_len(want, parms))
            .filter(|&cap| cap < document_limits.max_stream_decoded());
        flags.prefix = stage_cap.is_some();
        let stage_limits = stage_cap.map_or(document_limits, |cap| document_limits.with_max_stream_decoded(cap));
        let limits = &stage_limits;
        let decoded = match full_name(filter) {
            b"FlateDecode" => {
                let raw = flate_stage(input, limits, budget, flags)?;
                flate_truncated |= raw.flate_truncated;
                apply_predictor(raw.data, parms)?
            }
            b"LZWDecode" => {
                let early = int_param(parms, "EarlyChange", 1) != 0;
                let raw = stage(input, limits, budget, flags, |data, out| lzw::decode(data, early, out))?;
                apply_predictor(raw, parms)?
            }
            b"ASCIIHexDecode" => stage(input, limits, budget, flags, text::ascii_hex)?,
            b"ASCII85Decode" => stage(input, limits, budget, flags, text::ascii85)?,
            b"RunLengthDecode" => stage(input, limits, budget, flags, text::run_length)?,
            other => return Err(Error::UnsupportedFilter(String::from_utf8_lossy(other).into_owned())),
        };
        current = Some(decoded);
    }
    Ok(Decoded {
        data: current.unwrap_or_else(|| data.to_vec()),
        flate_truncated,
        characters_skipped: flags.skipped,
    })
}

/// The bytes a filter must put out for its predictor (ยง7.4.4.4) to give `want` bytes: whole rows,
/// each with its filter byte for a PNG predictor; `want` itself without a predictor, or with
/// parameters the predictor refuses anyway.
fn predicted_len(want: usize, parms: Option<&Dict>) -> usize {
    let predictor = int_param(parms, "Predictor", 1);
    if predictor <= 1 {
        return want;
    }
    let colors = int_param(parms, "Colors", 1);
    let bpc = int_param(parms, "BitsPerComponent", 8);
    let columns = int_param(parms, "Columns", 1);
    let row_bits = colors.checked_mul(bpc).and_then(|b| b.checked_mul(columns));
    let Some(row) = row_bits.and_then(|b| usize::try_from(b).ok()).map(|b| b.div_ceil(8)) else {
        return want;
    };
    if row == 0 {
        return want;
    }
    let raw_row = if predictor >= 10 { row + 1 } else { row };
    want.div_ceil(row).saturating_mul(raw_row)
}

fn int_param(parms: Option<&Dict>, key: &str, default: i64) -> i64 {
    parms.and_then(|p| p.get_int(key)).unwrap_or(default)
}

fn apply_predictor(data: Vec<u8>, parms: Option<&Dict>) -> Result<Vec<u8>> {
    let predictor = int_param(parms, "Predictor", 1);
    if predictor <= 1 {
        return Ok(data);
    }
    if predictor == 2 {
        return tiff_unpredict(data, parms);
    }
    if !(10..=15).contains(&predictor) {
        return Err(Error::UnsupportedFilter(format!("/Predictor {predictor}")));
    }
    let colors = int_param(parms, "Colors", 1);
    let bpc = int_param(parms, "BitsPerComponent", 8);
    let columns = int_param(parms, "Columns", 1);
    let bad = |message| Error::InvalidStructure {
        kind: "PNG predictor",
        message,
    };
    if !(1..=32).contains(&colors) || ![1, 2, 4, 8, 16].contains(&bpc) || !(1..=1 << 24).contains(&columns) {
        return Err(bad("parameters out of range"));
    }
    // Do the row-length math in u64 so it is exact on 32-bit targets (wasm32) as well:
    // 32 colours ร— 16 bits ร— 2^24 columns is 2^33 bits, which would overflow a 32-bit usize.
    let bits_per_pixel = u64::try_from(colors * bpc).map_err(|_| bad("overflow"))?;
    let columns = u64::try_from(columns).map_err(|_| bad("overflow"))?;
    let row_bits = bits_per_pixel.checked_mul(columns).ok_or(bad("overflow"))?;
    let row_len = row_bits.div_ceil(8);
    // A row is a filter byte plus `row_len` bytes, so a row wider than the whole input can
    // never be complete. Rejecting it caps the `prev` row buffer at the input size instead
    // of letting crafted parameters force a large allocation.
    let input_len = u64::try_from(data.len()).map_err(|_| bad("overflow"))?;
    if row_len > input_len.saturating_add(1) {
        return Err(bad("row length exceeds stream data"));
    }
    let row_len = usize::try_from(row_len).map_err(|_| bad("overflow"))?;
    let bpp = usize::try_from(bits_per_pixel.div_ceil(8).max(1)).map_err(|_| bad("overflow"))?;
    png_unpredict(&data, row_len, bpp)
}

/// Reverses TIFF predictor 2 (horizontal differencing): each sample is the difference from the
/// same component of the pixel to its left, for 8- and 16-bit samples.
fn tiff_unpredict(mut data: Vec<u8>, parms: Option<&Dict>) -> Result<Vec<u8>> {
    let colors = int_param(parms, "Colors", 1);
    let bpc = int_param(parms, "BitsPerComponent", 8);
    let columns = int_param(parms, "Columns", 1);
    let bad = |message| Error::InvalidStructure {
        kind: "TIFF predictor",
        message,
    };
    if !(1..=32).contains(&colors) || !(1..=1 << 24).contains(&columns) {
        return Err(bad("parameters out of range"));
    }
    let bytes = match bpc {
        8 => 1,
        16 => 2,
        _ => {
            return Err(Error::UnsupportedFilter(format!(
                "/Predictor 2 with {bpc} bits per component"
            )));
        }
    };
    let colors = usize::try_from(colors).map_err(|_| bad("overflow"))?;
    let columns = usize::try_from(columns).map_err(|_| bad("overflow"))?;
    let pixel = colors * bytes;
    let row = pixel.checked_mul(columns).ok_or(bad("overflow"))?;
    for line in data.chunks_mut(row) {
        for at in (pixel..line.len()).step_by(bytes) {
            let left = at - pixel;
            if bytes == 1 {
                let value = line
                    .get(at)
                    .copied()
                    .unwrap_or(0)
                    .wrapping_add(line.get(left).copied().unwrap_or(0));
                if let Some(slot) = line.get_mut(at) {
                    *slot = value;
                }
            } else {
                let read = |line: &[u8], i: usize| {
                    u16::from_be_bytes([line.get(i).copied().unwrap_or(0), line.get(i + 1).copied().unwrap_or(0)])
                };
                let value = read(line, at).wrapping_add(read(line, left)).to_be_bytes();
                if let Some(slot) = line.get_mut(at..at + 2) {
                    slot.copy_from_slice(&value);
                }
            }
        }
    }
    Ok(data)
}

/// Reverses PNG row filters. Each input row is a filter-type byte followed by `row_len`
/// bytes; a short final row is decoded as far as it goes.
fn png_unpredict(data: &[u8], row_len: usize, bpp: usize) -> Result<Vec<u8>> {
    let mut out = Vec::with_capacity(data.len());
    let mut prev = vec![0u8; row_len];
    let mut cur = vec![0u8; row_len];
    for chunk in data.chunks(row_len + 1) {
        let Some((&kind, row)) = chunk.split_first() else {
            continue;
        };
        let cur = cur.get_mut(..row.len()).unwrap_or_default();
        unfilter_row(kind, row, &prev, cur, bpp)?;
        out.extend_from_slice(cur);
        prev.iter_mut().zip(&*cur).for_each(|(p, c)| *p = *c);
    }
    Ok(out)
}

/// Reverses one row's PNG filter (PNG ยง9.2): `raw` (the row after its filter-type byte) into
/// `out`, given the previous row's unfiltered bytes (zeros for the first row) and the bytes
/// per complete pixel (at least 1). Flate's PNG predictors (ยง7.4.4.4) and PNG images share it.
///
/// # Errors
/// [`Error::InvalidStructure`] for a filter type other than 0โ€“4.
///
/// Added in 0.2.0.
pub fn unfilter_row(filter: u8, raw: &[u8], prev: &[u8], out: &mut [u8], bpp: usize) -> Result<()> {
    for i in 0..raw.len() {
        let x = raw.get(i).copied().unwrap_or(0);
        let a = i.checked_sub(bpp).and_then(|j| out.get(j)).copied().unwrap_or(0);
        let b = prev.get(i).copied().unwrap_or(0);
        let c = i.checked_sub(bpp).and_then(|j| prev.get(j)).copied().unwrap_or(0);
        let value = match filter {
            0 => x,
            1 => x.wrapping_add(a),
            2 => x.wrapping_add(b),
            3 => x.wrapping_add(a.midpoint(b)),
            4 => x.wrapping_add(paeth(a, b, c)),
            _ => {
                return Err(Error::InvalidStructure {
                    kind: "PNG predictor",
                    message: "unknown row filter",
                });
            }
        };
        if let Some(o) = out.get_mut(i) {
            *o = value;
        }
    }
    Ok(())
}

/// The Paeth predictor (PNG ยง9.4): of `a` (left), `b` (up) and `c` (up-left), the one closest
/// to `a + b - c`.
///
/// Added in 0.2.0.
#[must_use]
pub fn paeth(a: u8, b: u8, c: u8) -> u8 {
    let (ia, ib, ic) = (i16::from(a), i16::from(b), i16::from(c));
    let p = ia + ib - ic;
    let (pa, pb, pc) = ((p - ia).abs(), (p - ib).abs(), (p - ic).abs());
    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn limits(max_stream: usize) -> Limits {
        Limits::default().with_max_stream_decoded(max_stream)
    }

    fn inflate(data: &[u8], max_stream: usize) -> Result<Vec<u8>> {
        let limits = limits(max_stream);
        flate_decode(data, &limits, &mut DecodeBudget::new(&limits)).map(|d| d.data)
    }

    fn decode_with(dict: &Dict, data: &[u8], max_stream: usize) -> Result<Vec<u8>> {
        let limits = limits(max_stream);
        decode(dict, data, &limits, &mut DecodeBudget::new(&limits)).map(|d| d.data)
    }

    fn flate_chain(n: usize) -> Dict {
        [("Filter", Object::Array(vec![Object::name("FlateDecode"); n]))]
            .into_iter()
            .collect()
    }

    fn encode_times(data: &[u8], n: usize) -> Vec<u8> {
        (0..n).fold(data.to_vec(), |acc, _| flate_encode(&acc))
    }

    fn predictor_parms(columns: i64) -> Dict {
        [("Predictor", 12), ("Columns", columns)].into_iter().collect()
    }

    #[test]
    fn flate_round_trips() {
        let data = b"hello hello hello".to_vec();
        assert_eq!(inflate(&flate_encode(&data), 1024), Ok(data));
    }

    #[test]
    fn flate_decode_accepts_output_at_the_stream_limit() {
        assert_eq!(inflate(&flate_encode(&[0u8; 1000]), 1000).map(|d| d.len()), Ok(1000));
    }

    #[test]
    fn flate_decode_refuses_output_past_the_stream_limit() {
        assert_eq!(
            inflate(&flate_encode(&[0u8; 1001]), 1000),
            Err(Error::LimitExceeded {
                limit: Limit::StreamDecoded,
                at: None
            })
        );
    }

    #[test]
    fn flate_decode_charges_its_output_to_the_budget() {
        let limits = Limits::default();
        let mut budget = DecodeBudget::new(&limits);
        flate_decode(&flate_encode(&[0u8; 100]), &limits, &mut budget).unwrap();
        assert_eq!(budget.remaining(), limits.max_decoded_total() - 100);
    }

    #[test]
    fn flate_decode_accepts_output_that_spends_the_whole_budget() {
        let limits = Limits::default().with_max_decoded_total(100);
        let mut budget = DecodeBudget::new(&limits);
        assert!(flate_decode(&flate_encode(&[0u8; 100]), &limits, &mut budget).is_ok());
    }

    #[test]
    fn flate_decode_refuses_output_past_the_remaining_budget() {
        let limits = Limits::default().with_max_decoded_total(150);
        let mut budget = DecodeBudget::new(&limits);
        let data = flate_encode(&[0u8; 100]);
        flate_decode(&data, &limits, &mut budget).unwrap();
        assert_eq!(
            flate_decode(&data, &limits, &mut budget),
            Err(Error::LimitExceeded {
                limit: Limit::DecodedTotal,
                at: None
            })
        );
    }

    #[test]
    fn flate_decode_keeps_truncated_output_and_flags_it() {
        let full = flate_encode(&[7u8; 4000]);
        let cut = full.get(..full.len() - 6).unwrap();
        let limits = Limits::default();
        let decoded = flate_decode(cut, &limits, &mut DecodeBudget::new(&limits)).unwrap();
        assert!(decoded.flate_truncated && !decoded.data.is_empty());
    }

    #[test]
    fn flate_decode_rejects_garbage() {
        assert!(inflate(b"not zlib", 1000).is_err());
    }

    #[test]
    fn decode_accepts_a_filter_chain_at_the_limit() {
        let limits = Limits::default().with_max_filter_chain(3);
        let decoded = decode(
            &flate_chain(3),
            &encode_times(b"x", 3),
            &limits,
            &mut DecodeBudget::new(&limits),
        );
        assert_eq!(decoded.map(|d| d.data), Ok(b"x".to_vec()));
    }

    #[test]
    fn decode_rejects_a_filter_chain_past_the_limit() {
        let limits = Limits::default().with_max_filter_chain(3);
        assert_eq!(
            decode(
                &flate_chain(4),
                &encode_times(b"x", 4),
                &limits,
                &mut DecodeBudget::new(&limits)
            ),
            Err(Error::LimitExceeded {
                limit: Limit::FilterChain,
                at: None
            })
        );
    }

    #[test]
    fn decode_charges_every_stage_of_a_chain_to_the_budget() {
        let limits = Limits::default();
        let mut budget = DecodeBudget::new(&limits);
        let encoded = encode_times(&[0u8; 1000], 2);
        let once = flate_encode(&[0u8; 1000]).len();
        decode(&flate_chain(2), &encoded, &limits, &mut budget).unwrap();
        assert_eq!(budget.remaining(), limits.max_decoded_total() - 1000 - once);
    }

    #[test]
    fn png_up_predictor_adds_previous_row() {
        // Two rows of 2 columns, filter type 2 (Up).
        let encoded = [2, 1, 2, 2, 1, 1];
        assert_eq!(png_unpredict(&encoded, 2, 1), Ok(vec![1, 2, 2, 3]));
    }

    #[test]
    fn png_paeth_and_sub_predictors_decode() {
        let encoded = [1, 5, 1, 4, 0, 0];
        assert_eq!(png_unpredict(&encoded, 2, 1), Ok(vec![5, 6, 5, 6]));
    }

    #[test]
    fn decode_applies_predictor_after_flate() {
        let dict: Dict = [
            ("Filter", Object::name("FlateDecode")),
            ("DecodeParms", Object::Dict(predictor_parms(2))),
        ]
        .into_iter()
        .collect();
        let encoded = flate_encode(&[2, 1, 2, 2, 1, 1]);
        assert_eq!(decode_with(&dict, &encoded, 1024), Ok(vec![1, 2, 2, 3]));
    }

    #[test]
    fn decode_should_reject_predictor_row_longer_than_stream_data() {
        // 32 colours ร— 16 bits ร— 16,777,215 columns โ‰ˆ 1 GiB per row; the stream holds 6 bytes.
        let parms: Dict = [
            ("Predictor", 12),
            ("Colors", 32),
            ("BitsPerComponent", 16),
            ("Columns", 16_777_215),
        ]
        .into_iter()
        .collect();
        let dict: Dict = [
            ("Filter", Object::name("FlateDecode")),
            ("DecodeParms", Object::Dict(parms)),
        ]
        .into_iter()
        .collect();
        let encoded = flate_encode(&[2, 1, 2, 2, 1, 1]);
        assert_eq!(
            decode_with(&dict, &encoded, 1024),
            Err(Error::InvalidStructure {
                kind: "PNG predictor",
                message: "row length exceeds stream data",
            })
        );
    }

    #[test]
    fn decode_should_reject_out_of_range_predictor_colors() {
        let parms: Dict = [("Predictor", 12), ("Colors", 33)].into_iter().collect();
        let dict: Dict = [
            ("Filter", Object::name("FlateDecode")),
            ("DecodeParms", Object::Dict(parms)),
        ]
        .into_iter()
        .collect();
        assert!(decode_with(&dict, &flate_encode(&[0, 1]), 1024).is_err());
    }

    #[test]
    fn decode_runs_a_chain_of_text_and_lzw_filters() {
        // "Hello" as hex, then that text as ASCII85: decoded in the chain's order.
        let dict: Dict = [("Filter", Object::Array(vec![Object::name("A85"), Object::name("AHx")]))]
            .into_iter()
            .collect();
        assert_eq!(decode_with(&dict, b"1cRBN2IeXT2J,,~>", 100), Ok(b"Hello".to_vec()));
    }

    #[test]
    fn decode_charges_a_text_filter_to_the_limits() {
        let dict: Dict = [("Filter", Object::name("RunLengthDecode"))].into_iter().collect();
        assert!(matches!(
            decode_with(&dict, &[200, b'x'], 10),
            Err(Error::LimitExceeded { .. })
        ));
    }

    #[test]
    fn tiff_predictor_adds_the_pixel_to_the_left() {
        let parms: Dict = [("Predictor", 2), ("Colors", 2), ("Columns", 3)].into_iter().collect();
        assert_eq!(
            apply_predictor(vec![1, 10, 1, 1, 1, 1, 5, 5, 0, 0, 1, 2], Some(&parms)),
            Ok(vec![1, 10, 2, 11, 3, 12, 5, 5, 5, 5, 6, 7])
        );
    }

    #[test]
    fn decode_reports_unsupported_filter() {
        let dict: Dict = [("Filter", Object::name("DCTDecode"))].into_iter().collect();
        assert_eq!(
            decode_with(&dict, b"", 10),
            Err(Error::UnsupportedFilter("DCTDecode".into()))
        );
    }

    #[test]
    fn decode_does_not_pass_crypt_through() {
        // Undecrypted data must never be treated as plaintext: the reader strips `/Crypt`
        // only after decrypting.
        let dict: Dict = [("Filter", Object::name("Crypt"))].into_iter().collect();
        assert_eq!(
            decode_with(&dict, b"x", 10),
            Err(Error::UnsupportedFilter("Crypt".into()))
        );
    }

    fn prefix(dict: &Dict, data: &[u8], max: usize) -> Result<Prefix> {
        let limits = Limits::default();
        decode_prefix(dict, data, &limits, &mut DecodeBudget::new(&limits), max)
    }

    #[test]
    fn a_prefix_of_a_bomb_decodes_only_what_is_asked_and_one_byte_more() {
        let bomb = flate_encode(&vec![7u8; Limits::default().max_stream_decoded() + 1]);
        let limits = Limits::default();
        let mut budget = DecodeBudget::new(&limits);
        let read = decode_prefix(&flate_chain(1), &bomb, &limits, &mut budget, 16).unwrap();
        assert_eq!((read.decoded.data, read.complete), (vec![7u8; 16], false));
        // At most 17 bytes were decoded, so the call's budget is nearly whole.
        assert!(budget.remaining() >= limits.max_decoded_total() - 17);
    }

    #[test]
    fn a_prefix_as_long_as_the_stream_is_complete() {
        let read = prefix(&flate_chain(1), &flate_encode(b"BT ET"), 5).unwrap();
        assert_eq!((read.decoded.data.as_slice(), read.complete), (&b"BT ET"[..], true));
    }

    #[test]
    fn a_prefix_through_a_text_filter_stops_at_the_cap() {
        let dict: Dict = [("Filter", Object::name("ASCIIHexDecode"))].into_iter().collect();
        let read = prefix(&dict, b"414243444546>", 3).unwrap();
        assert_eq!((read.decoded.data.as_slice(), read.complete), (&b"ABC"[..], false));
    }

    #[test]
    fn a_prefix_past_the_stream_limit_is_refused_as_decode_refuses_it() {
        let bomb = flate_encode(&vec![0u8; 2000]);
        let limits = limits(1000);
        let read = decode_prefix(&flate_chain(1), &bomb, &limits, &mut DecodeBudget::new(&limits), 5000);
        assert!(matches!(
            read,
            Err(Error::LimitExceeded {
                limit: Limit::StreamDecoded,
                ..
            })
        ));
    }

    /// `data` decoded whole, and its first `max` bytes as a prefix read decodes them.
    fn whole_and_prefix(dict: &Dict, data: &[u8], max: usize) -> (Vec<u8>, Prefix) {
        let limits = Limits::default();
        let whole = decode(dict, data, &limits, &mut DecodeBudget::new(&limits))
            .unwrap()
            .data;
        (whole, prefix(dict, data, max).unwrap())
    }

    fn chain(names: &[&str]) -> Dict {
        [("Filter", Object::Array(names.iter().map(|n| Object::name(n)).collect()))]
            .into_iter()
            .collect()
    }

    fn text_of(n: usize) -> Vec<u8> {
        (0..n).map(|i| b'a' + u8::try_from(i % 26).unwrap()).collect()
    }

    #[test]
    fn a_prefix_through_hex_then_flate_is_the_start_of_the_whole() {
        let hex: Vec<u8> = flate_encode(&text_of(5000))
            .iter()
            .flat_map(|b| format!("{b:02x}").into_bytes())
            .collect();
        let (whole, read) = whole_and_prefix(&chain(&["AHx", "Fl"]), &hex, 100);
        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..100], false));
        assert!(!read.decoded.flate_truncated);
    }

    #[test]
    fn a_prefix_through_two_flates_is_the_start_of_the_whole() {
        let twice = flate_encode(&flate_encode(&text_of(5000)));
        let (whole, read) = whole_and_prefix(&chain(&["FlateDecode", "FlateDecode"]), &twice, 100);
        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..100], false));
    }

    #[test]
    fn a_prefix_through_a_png_predictor_wider_than_it_is_the_start_of_the_whole() {
        // Rows of 5000 bytes, each with the Up filter byte (2).
        let rows: Vec<u8> = (0..4)
            .flat_map(|r| [vec![2u8], vec![u8::try_from(r).unwrap(); 5000]].concat())
            .collect();
        let parms: Dict = [("Predictor", Object::from(12)), ("Columns", Object::from(5000))]
            .into_iter()
            .collect();
        let dict: Dict = [
            ("Filter", Object::name("FlateDecode")),
            ("DecodeParms", Object::Dict(parms)),
        ]
        .into_iter()
        .collect();
        let (whole, read) = whole_and_prefix(&dict, &flate_encode(&rows), 10);
        assert_eq!((read.decoded.data.as_slice(), read.complete), (&whole[..10], false));
    }
}