caj2pdf-core 0.5.0

Platform-neutral CAJ-family conversion 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
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
// SPDX-License-Identifier: MIT

//! Narrow repairs for link destinations and absent optional appearances.
//!
//! This module only identifies candidates. The caller must prove that the
//! relevant page or appearance target is absent before replacing an object.

use super::parser::{
    Syntax, destination_page, exact_name, exact_reference, exact_unsigned, parse_object_head,
};
use super::{FragmentObject, ObjectTail, Reader};
use crate::fallible::reserve_exact;
use crate::pdf::PdfRef;
use crate::{Cancellation, Error, ErrorKind, Limits, RangedSource, Result};

/// The parsed object form. A scalar destination must be linked from an actual
/// link annotation before its null replacement can be used.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum LinkRepairKind {
    Link,
    ScalarDestination,
}

/// The reference that makes a narrow link repair eligible.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum LinkRepairTarget {
    /// A direct destination array begins with this page reference.
    DirectPage(PdfRef),
    /// A link's `/Dest` value refers to a separate destination object.
    IndirectArray(PdfRef),
    /// One missing optional appearance; the destination page must remain live.
    AbsentAppearance { missing: PdfRef, page: PdfRef },
}

/// A complete, bounded replacement object plus the evidence needed to decide
/// whether it may be used. `replacement` retains the original object number.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct LinkRepairCandidate {
    pub object: PdfRef,
    pub kind: LinkRepairKind,
    pub target: LinkRepairTarget,
    /// A link's non-destination fields still refer to its indirect `/Dest`.
    /// Nulling that destination would also change those unrelated fields.
    pub retains_destination_reference: bool,
    pub replacement: Vec<u8>,
}

fn is_link_with_destination(head: &super::parser::ObjectHead) -> bool {
    let Some(dictionary) = head.dictionary.as_ref() else {
        return false;
    };
    dictionary
        .value(b"Subtype")
        .and_then(exact_name)
        .is_some_and(|name| name == b"Link")
        && dictionary.value(b"Dest").is_some()
        && dictionary.value(b"A").is_none()
        && dictionary
            .value(b"Type")
            .is_none_or(|value| exact_name(value).is_some_and(|name| name == b"Annot"))
}

/// Inspect one already indexed, complete PDF object without scanning adjacent
/// fragment bytes. Streams and unrelated object types return `None`.
///
/// A link dictionary candidate has only its parsed `/Dest` key/value pair
/// removed; every other original byte is preserved. A standalone destination
/// array is replaced with a generation-zero `null` object. Both rewrites are
/// bounded by the existing PDF syntax and allocation limits.
pub(crate) fn inspect_link_destination_candidate<S: RangedSource, C: Cancellation>(
    source: &mut S,
    fragment: FragmentObject,
    limits: &Limits,
    cancellation: &C,
) -> Result<Option<LinkRepairCandidate>> {
    inspect_link_candidate(source, fragment, None, limits, cancellation)
}

/// Inspect a link after the caller proves a reference absent. Prefer the
/// measured optional appearance repair; otherwise inspect its destination.
pub(crate) fn inspect_link_missing_target_candidate<S: RangedSource, C: Cancellation>(
    source: &mut S,
    fragment: FragmentObject,
    missing: PdfRef,
    limits: &Limits,
    cancellation: &C,
) -> Result<Option<LinkRepairCandidate>> {
    inspect_link_candidate(source, fragment, Some(missing), limits, cancellation)
}

fn inspect_link_candidate<S: RangedSource, C: Cancellation>(
    source: &mut S,
    fragment: FragmentObject,
    missing_appearance: Option<PdfRef>,
    limits: &Limits,
    cancellation: &C,
) -> Result<Option<LinkRepairCandidate>> {
    limits.validate()?;
    let range = fragment.range;
    let reference = fragment.reference;
    if reference.generation != 0 {
        return Ok(None);
    }
    let end = range.end().ok_or(Error::pdf(
        ErrorKind::Malformed,
        range.offset,
        Some((reference.number, reference.generation)),
        "link object source range overflows",
    ))?;
    if end > source.size() {
        return Err(Error::truncated(
            range.offset,
            range.length,
            source.size().saturating_sub(range.offset),
        ));
    }
    let mut reader = Reader::new(source, range, limits, cancellation)?;
    limits
        .check_input_size(range.length)
        .map_err(reader.locator(0, Some(reference)))?;
    let head = reader.load_head(0, Some(reference))?;
    let ObjectTail::EndObject { end } = head.tail else {
        return Ok(None);
    };
    let mut rest = end as u64;
    reader.skip_space(&mut rest)?;
    if rest != range.length {
        return Err(reader.malformed(
            rest,
            Some(reference),
            "link repair object has trailing non-whitespace bytes",
        ));
    }

    let likely_link = is_link_with_destination(&head);
    let array_page = head
        .scalar
        .as_ref()
        .and_then(|span| destination_page(&head.bytes[span.clone()]));
    if !likely_link && array_page.is_none() {
        return Ok(None);
    }

    let maximum = reader.syntax_limit();
    if range.length > maximum {
        return Err(
            Error::limit("PDF link repair object bytes", maximum, range.length)
                .at(range.offset)
                .in_pdf(Some((reference.number, reference.generation))),
        );
    }
    // `maximum` is at most the 4 MiB object syntax limit.
    let length = usize::try_from(range.length).expect("object syntax limit fits usize");
    let complete = reader.bytes(0, length)?;
    if !complete.starts_with(&head.bytes) {
        return Err(reader.malformed(
            0,
            Some(reference),
            "link repair source changed while reading",
        ));
    }
    let complete = parse_object_head(complete)
        .map_err(|issue| reader.parse_issue(0, Some(reference), issue))?;
    // `complete` extends `head.bytes`, which parsed to this reference with its
    // `endobj` keyword inside those bytes. Every earlier token is delimited
    // within the shared prefix, so a successful parse of the longer buffer
    // reads the same header, value, and tail; only a byte glued to `endobj`
    // can differ, and that fails the parse above.
    debug_assert_eq!(complete.reference, reference);
    debug_assert!(matches!(complete.tail, ObjectTail::EndObject { end: tail } if tail == end));
    if !Syntax::new(&complete.bytes[end..]).at_end() {
        return Err(reader.malformed(
            end as u64,
            Some(reference),
            "link repair object has trailing non-whitespace bytes",
        ));
    }

    debug_assert_eq!(is_link_with_destination(&complete), likely_link);
    if likely_link {
        let dictionary = complete.dictionary.as_ref().expect("classified dictionary");
        reader.reject_duplicate_names(dictionary, 0, Some(reference))?;
        let destination = dictionary.entry(b"Dest").expect("classified destination");
        let appearance = missing_appearance.and_then(|missing| {
            let page = destination_page(destination.value(&dictionary.bytes))?;
            let appearance = dictionary.entry(b"AP")?;
            // Only the measured /AP << /N absent >> and zero-width /BS
            // qualify. No rollover/down/state maps or other reference aliases.
            if missing.generation != 0
                || single_entry(appearance.value(&dictionary.bytes), b"N").and_then(exact_reference)
                    != Some(missing)
                || dictionary
                    .value(b"BS")
                    .and_then(|value| single_entry(value, b"W"))
                    .and_then(exact_unsigned)
                    != Some(0)
                || complete
                    .references
                    .iter()
                    .filter(|target| **target == missing)
                    .count()
                    != 1
            {
                return None;
            }
            Some((
                appearance,
                LinkRepairTarget::AbsentAppearance { missing, page },
            ))
        });
        let (removed, target) = if let Some(appearance) = appearance {
            appearance
        } else {
            let target = if let Some(page) = destination_page(destination.value(&dictionary.bytes))
            {
                LinkRepairTarget::DirectPage(page)
            } else if let Some(array) = exact_reference(destination.value(&dictionary.bytes)) {
                LinkRepairTarget::IndirectArray(array)
            } else {
                return Ok(None);
            };
            (destination, target)
        };
        let retains_destination_reference = match target {
            LinkRepairTarget::IndirectArray(array) => {
                complete
                    .references
                    .iter()
                    .filter(|reference| **reference == array)
                    .count()
                    != 1
            }
            LinkRepairTarget::DirectPage(_) | LinkRepairTarget::AbsentAppearance { .. } => false,
        };
        // The parser records the dictionary at `dictionary_start` in
        // `complete.bytes` and each entry's nonempty pair relative to it, so
        // the absolute pair lies inside the object.
        let dictionary_start = complete
            .dictionary_start
            .expect("classified dictionary offset");
        let pair_start = dictionary_start + removed.pair.start;
        let pair_end = dictionary_start + removed.pair.end;
        debug_assert!(pair_start < pair_end && pair_end <= complete.bytes.len());
        let mut replacement = Vec::new();
        let refused = Error::limit(
            "PDF link repair allocation",
            limits.max_allocation_bytes,
            complete.bytes.len() as u64,
        )
        .at(range.offset)
        .in_pdf(Some((reference.number, reference.generation)));
        let additional = complete.bytes.len() - (pair_end - pair_start);
        reserve_exact(&mut replacement, additional, refused)?;
        replacement.extend_from_slice(&complete.bytes[..pair_start]);
        replacement.extend_from_slice(&complete.bytes[pair_end..]);
        return Ok(Some(LinkRepairCandidate {
            object: reference,
            kind: LinkRepairKind::Link,
            target,
            retains_destination_reference,
            replacement,
        }));
    }

    let page = array_page.expect("classified destination array");
    // At most 29 bytes for a 32-bit object number. The parsed destination
    // object needs more than one byte, so `syntax_limit` came from
    // `max_allocation_bytes / 32` and the allocation limit is at least 64.
    let replacement = format!("{} 0 obj\nnull\nendobj\n", reference.number).into_bytes();
    debug_assert!(replacement.len() as u64 <= limits.max_allocation_bytes);
    Ok(Some(LinkRepairCandidate {
        object: reference,
        kind: LinkRepairKind::ScalarDestination,
        target: LinkRepairTarget::DirectPage(page),
        retains_destination_reference: false,
        replacement,
    }))
}

/// A complete direct dictionary with exactly one named value. The surrounding
/// object has already passed strict parsing; no nested profile is guessed.
fn single_entry<'a>(bytes: &'a [u8], key: &[u8]) -> Option<&'a [u8]> {
    let mut syntax = Syntax::new(bytes);
    let entries = syntax.dictionary(0).ok()?;
    if entries.len() != 1 || entries[0].name() != key || !syntax.at_end() {
        return None;
    }
    Some(entries[0].value(bytes))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Context;
    use crate::NeverCancel;
    use crate::pdf::PdfRange;

    /// Serves `first` until `switch(reads, starts)` holds for a read, then
    /// `second`. `reads` counts earlier reads; `starts` counts reads at the
    /// object start, including this one. One source type keeps every test on
    /// the same generic instantiation.
    struct Source {
        first: Vec<u8>,
        second: Vec<u8>,
        reads: usize,
        starts: usize,
        switch: fn(usize, usize) -> bool,
        largest_request: usize,
    }

    impl Source {
        fn new(bytes: Vec<u8>) -> Self {
            Self::switching(bytes, Vec::new(), |_, _| false)
        }

        fn switching(first: Vec<u8>, second: Vec<u8>, switch: fn(usize, usize) -> bool) -> Self {
            Self {
                first,
                second,
                reads: 0,
                starts: 0,
                switch,
                largest_request: 0,
            }
        }
    }

    impl RangedSource for Source {
        fn size(&self) -> u64 {
            self.first.len() as u64
        }

        fn read_at(&mut self, offset: u64, destination: &mut [u8]) -> Result<usize> {
            self.largest_request = self.largest_request.max(destination.len());
            if offset == 0 {
                self.starts += 1;
            }
            let bytes = if (self.switch)(self.reads, self.starts) {
                &self.second
            } else {
                &self.first
            };
            let start = offset as usize;
            let count = destination.len().min(bytes.len().saturating_sub(start));
            destination[..count].copy_from_slice(&bytes[start..start + count]);
            self.reads += 1;
            Ok(count)
        }
    }

    fn inspect(bytes: &[u8]) -> Result<Option<LinkRepairCandidate>> {
        let mut source = Source::new(bytes.to_vec());
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: bytes.len() as u64,
            },
        };
        inspect_link_destination_candidate(&mut source, fragment, &Limits::default(), &NeverCancel)
    }

    #[test]
    fn absent_appearance_reuses_bounded_cancellable_source_checked_reads() {
        use crate::test_support::CancelAfter;
        let bytes =
            b"9 0 obj\n<</Subtype/Link/BS<</W 0>>/Dest[6 0 R/Fit]/AP<</N 99 0 R>>>>\nendobj\n";
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: bytes.len() as u64,
            },
        };
        let missing = PdfRef {
            number: 99,
            generation: 0,
        };
        let limits = Limits {
            io_chunk_bytes: 1,
            ..Limits::default()
        };
        let mut source = Source::new(bytes.to_vec());
        let signal = CancelAfter::never();
        let candidate =
            inspect_link_missing_target_candidate(&mut source, fragment, missing, &limits, &signal)
                .unwrap()
                .unwrap();
        assert_eq!(
            candidate.target,
            LinkRepairTarget::AbsentAppearance {
                missing,
                page: PdfRef {
                    number: 6,
                    generation: 0
                },
            }
        );
        assert!(source.largest_request <= 1);
        assert!(
            candidate
                .replacement
                .windows(16)
                .any(|part| part == b"/Dest[6 0 R/Fit]")
        );
        assert!(!candidate.replacement.windows(3).any(|part| part == b"/AP"));
        for allowed in 0..signal.queries() {
            let mut source = Source::new(bytes.to_vec());
            assert!(matches!(
                inspect_link_missing_target_candidate(
                    &mut source,
                    fragment,
                    missing,
                    &limits,
                    &CancelAfter::new(allowed),
                ),
                Err(Error {
                    kind: ErrorKind::Cancelled,
                    ..
                })
            ));
        }
        let changed = String::from_utf8(bytes.to_vec())
            .unwrap()
            .replace("99 0 R", "98 0 R");
        let mut source = Source::switching(bytes.to_vec(), changed.into_bytes(), |_, starts| {
            starts >= 2
        });
        assert!(
            inspect_link_missing_target_candidate(
                &mut source,
                fragment,
                missing,
                &Limits::default(),
                &NeverCancel,
            )
            .is_err()
        );
        let mut oversized = bytes.to_vec();
        oversized.extend(std::iter::repeat_n(b' ', 256));
        let mut source = Source::new(oversized);
        let mut fragment = fragment;
        fragment.range.length = source.size();
        let limits = Limits {
            max_allocation_bytes: 4096,
            ..limits
        };
        assert!(matches!(
            inspect_link_missing_target_candidate(
                &mut source,
                fragment,
                missing,
                &limits,
                &NeverCancel,
            ),
            Err(Error {
                kind: ErrorKind::LimitExceeded { .. },
                ..
            })
        ));
    }

    #[test]
    fn removes_only_a_direct_link_destination_pair() {
        let bytes = b"9 0 obj\n<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /AP << /Dest (appearance) >> /Dest [6 0 R /Fit] /Border [0 0 0] >>\nendobj\n";
        let candidate = inspect(bytes).unwrap().unwrap();
        assert_eq!(candidate.kind, LinkRepairKind::Link);
        assert_eq!(
            candidate.target,
            LinkRepairTarget::DirectPage(PdfRef {
                number: 6,
                generation: 0
            })
        );
        assert_eq!(candidate.object.number, 9);
        let replacement = candidate.replacement;
        assert!(replacement.windows(5).any(|window| window == b"/Rect"));
        assert!(replacement.windows(7).any(|window| window == b"/Border"));
        let parsed = parse_object_head(replacement).unwrap();
        let dictionary = parsed.dictionary.unwrap();
        assert!(dictionary.value(b"Dest").is_none());
        assert!(
            dictionary
                .value(b"AP")
                .unwrap()
                .windows(5)
                .any(|window| window == b"/Dest")
        );
    }

    #[test]
    fn recognizes_indirect_links_and_nulls_scalar_arrays() {
        let link = inspect(b"9 0 obj\n<</Subtype/Link /Dest 42 0 R /Rect [0 0 2 2]>>\nendobj\n")
            .unwrap()
            .unwrap();
        assert_eq!(
            link.target,
            LinkRepairTarget::IndirectArray(PdfRef {
                number: 42,
                generation: 0
            })
        );
        assert!(link.replacement.windows(5).any(|window| window == b"/Rect"));

        let array = inspect(b"9 0 obj\n[6 0 R /XYZ null null 1]\nendobj\n")
            .unwrap()
            .unwrap();
        assert_eq!(array.kind, LinkRepairKind::ScalarDestination);
        assert_eq!(
            array.target,
            LinkRepairTarget::DirectPage(PdfRef {
                number: 6,
                generation: 0
            })
        );
        assert_eq!(array.replacement, b"9 0 obj\nnull\nendobj\n");
    }

    #[test]
    fn ignores_streams_strings_and_unrelated_dictionaries() {
        assert!(inspect(b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit] /Length 0>>\nstream\n\nendstream\nendobj\n").unwrap().is_none());
        assert!(
            inspect(b"9 0 obj\n(Note /Subtype /Link /Dest [6 0 R /Fit])\nendobj\n")
                .unwrap()
                .is_none()
        );
        assert!(
            inspect(b"9 0 obj\n<</Subtype/Widget /Dest [6 0 R /Fit]>>\nendobj\n")
                .unwrap()
                .is_none()
        );
        assert!(
            inspect(b"9 0 obj\n<</Subtype/Link /Dest (named)>>\nendobj\n")
                .unwrap()
                .is_none()
        );
        assert!(inspect(b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit] /A <</S/URI /URI (example)>> >>\nendobj\n").unwrap().is_none());
    }

    #[test]
    fn rejects_duplicate_destination_and_wrong_object_header() {
        let duplicate =
            b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit] /Dest [7 0 R /Fit]>>\nendobj\n";
        assert!(matches!(
            inspect(duplicate),
            Err(Error {
                kind: ErrorKind::Malformed,
                context: Context::Pdf { repair: true, .. },
                ..
            })
        ));
        let wrong = b"10 0 obj\n[6 0 R /Fit]\nendobj\n";
        assert!(matches!(
            inspect(wrong),
            Err(Error {
                kind: _,
                offset: Some(0),
                context: Context::Pdf { .. },
                ..
            })
        ));
    }

    #[test]
    fn small_io_chunks_bound_reads() {
        let bytes = b"9 0 obj\n[6 0 R /Fit]\nendobj\n";
        let mut source = Source::new(bytes.to_vec());
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: bytes.len() as u64,
            },
        };
        let limits = Limits {
            io_chunk_bytes: 3,
            ..Limits::default()
        };
        let candidate =
            inspect_link_destination_candidate(&mut source, fragment, &limits, &NeverCancel)
                .unwrap()
                .unwrap();
        assert_eq!(candidate.kind, LinkRepairKind::ScalarDestination);
        assert!(source.largest_request <= 3);
    }

    #[test]
    fn rejects_a_large_candidate_before_buffering_its_full_span() {
        let mut bytes = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj\n".to_vec();
        bytes.extend(std::iter::repeat_n(b' ', 256));
        let mut source = Source::new(bytes);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: source.size(),
            },
        };
        let limits = Limits {
            io_chunk_bytes: 8,
            max_allocation_bytes: 4096,
            ..Limits::default()
        };
        assert!(matches!(
            inspect_link_destination_candidate(&mut source, fragment, &limits, &NeverCancel),
            Err(Error {
                kind: ErrorKind::LimitExceeded {
                    resource: "PDF link repair object bytes",
                    ..
                },
                context: Context::Pdf { .. },
                ..
            })
        ));
        assert!(source.largest_request <= 8);
    }

    #[test]
    fn candidate_span_is_checked_against_the_input_limit() {
        let bytes = b"9 0 obj\n[6 0 R /Fit]\nendobj\n";
        let mut source = Source::new(bytes.to_vec());
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: bytes.len() as u64,
            },
        };
        let limits = Limits {
            max_input_bytes: 8,
            ..Limits::default()
        };
        let error =
            inspect_link_destination_candidate(&mut source, fragment, &limits, &NeverCancel)
                .expect_err("an oversized candidate span was read");
        assert!(matches!(
            error,
            Error { kind: ErrorKind::LimitExceeded { resource: "input bytes", limit: 8, attempted }, offset: Some(0), context: Context::Pdf { object: Some((9, 0)), .. }, .. } if attempted == bytes.len() as u64
        ));
        assert_eq!(source.largest_request, 0);
    }

    #[test]
    fn rejects_a_source_that_changes_between_candidate_reads() {
        let bytes = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj\n";
        let mut changed = bytes.to_vec();
        let digit = changed
            .windows(5)
            .position(|window| window == b"6 0 R")
            .unwrap();
        changed[digit] = b'7';
        let mut source = Source::switching(bytes.to_vec(), changed, |reads, _| reads > 0);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: bytes.len() as u64,
            },
        };
        assert!(matches!(
            inspect_link_destination_candidate(
                &mut source,
                fragment,
                &Limits::default(),
                &NeverCancel
            ),
            Err(Error {
                kind: _,
                context: Context::Pdf { .. },
                reason: "link repair source changed while reading",
                ..
            })
        ));
    }

    #[test]
    fn truncated_located_range_is_rejected_before_reading() {
        let prefix = b"CAJ!!";
        let object = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj\n";
        let mut bytes = prefix.to_vec();
        bytes.extend_from_slice(object);
        let mut source = Source::new(bytes);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: prefix.len() as u64,
                length: object.len() as u64 + 3,
            },
        };
        let error = inspect_link_destination_candidate(
            &mut source,
            fragment,
            &Limits::default(),
            &NeverCancel,
        )
        .expect_err("truncated link object was accepted");
        assert!(matches!(
            error,
            Error { kind: ErrorKind::Truncated { expected, available }, offset: Some(offset), .. } if offset == prefix.len() as u64
                && expected == object.len() as u64 + 3
                && available == object.len() as u64
        ));
        assert_eq!(source.largest_request, 0);
    }

    #[test]
    fn nonzero_generation_is_excluded_without_reading() {
        let object = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj\n";
        let mut source = Source::new(object.to_vec());
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 1,
            },
            range: PdfRange {
                offset: 0,
                length: object.len() as u64,
            },
        };
        assert!(
            inspect_link_destination_candidate(
                &mut source,
                fragment,
                &Limits::default(),
                &NeverCancel,
            )
            .unwrap()
            .is_none()
        );
        assert_eq!(source.largest_request, 0);
    }

    #[test]
    fn rejects_non_whitespace_after_a_link_object_with_absolute_offset() {
        let prefix = b"CAJ!!";
        let object = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj";
        let tail = b"\r\n<container-tail>";
        let mut bytes = prefix.to_vec();
        bytes.extend_from_slice(object);
        bytes.extend_from_slice(tail);
        let mut source = Source::new(bytes);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: prefix.len() as u64,
                length: (object.len() + tail.len()) as u64,
            },
        };
        let error = inspect_link_destination_candidate(
            &mut source,
            fragment,
            &Limits::default(),
            &NeverCancel,
        )
        .expect_err("object span swallowed the container tail");
        assert!(matches!(
            error,
            Error { kind: ErrorKind::Malformed, offset: Some(offset), context: Context::Pdf { object: Some((9, 0)), repair: false }, reason: "link repair object has trailing non-whitespace bytes", .. } if offset == (prefix.len() + object.len() + 2) as u64
        ));
    }

    #[test]
    fn rejects_changed_link_form_between_head_and_full_read() {
        let first = b"9 0 obj\n<</Subtype/Link /Dest [6 0 R /Fit]>>\nendobj\n".to_vec();
        let mut second = first.clone();
        let subtype = second
            .windows(5)
            .position(|window| window == b"/Link")
            .unwrap();
        second[subtype..subtype + 5].copy_from_slice(b"/Null");
        // Only the first read sees the original bytes.
        let mut source = Source::switching(first, second, |reads, _| reads > 0);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: source.size(),
            },
        };
        assert!(matches!(
            inspect_link_destination_candidate(
                &mut source,
                fragment,
                &Limits::default(),
                &NeverCancel,
            ),
            Err(Error {
                kind: ErrorKind::Malformed,
                context: Context::Pdf { repair: false, .. },
                reason: "link repair source changed while reading",
                ..
            })
        ));
        assert!(source.reads >= 2);
    }

    #[test]
    fn rejects_trailing_bytes_that_appear_after_the_bounded_head_read() {
        let object = b"9 0 obj\n[6 0 R /Fit]\nendobj";
        let mut first = object.to_vec();
        first.extend(std::iter::repeat_n(b' ', 1024));
        let mut second = first.clone();
        // Beyond the 512-byte head window, so the head prefix still matches.
        second[800] = b'x';
        // The tail changes once a second read restarts at the object start,
        // between the whitespace scan and the complete candidate read.
        let mut source = Source::switching(first, second, |_, starts| starts >= 2);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: source.size(),
            },
        };
        let error = inspect_link_destination_candidate(
            &mut source,
            fragment,
            &Limits::default(),
            &NeverCancel,
        )
        .expect_err("changed trailing bytes were accepted");
        assert!(matches!(
            error,
            Error { kind: ErrorKind::Malformed, offset: Some(offset), context: Context::Pdf { object: Some((9, 0)), repair: false }, reason: "link repair object has trailing non-whitespace bytes", .. } if offset == object.len() as u64
        ));
    }

    #[test]
    fn identifies_an_indirect_destination_used_by_another_link_field() {
        let ordinary = inspect(b"9 0 obj\n<</Subtype/Link /Dest 42 0 R /AP 43 0 R>>\nendobj\n")
            .unwrap()
            .unwrap();
        assert!(!ordinary.retains_destination_reference);

        let shared = inspect(b"9 0 obj\n<</Subtype/Link /Dest 42 0 R /AP 42 0 R>>\nendobj\n")
            .unwrap()
            .unwrap();
        assert_eq!(
            shared.target,
            LinkRepairTarget::IndirectArray(PdfRef {
                number: 42,
                generation: 0
            })
        );
        assert!(shared.retains_destination_reference);
        assert!(
            shared
                .replacement
                .windows(10)
                .any(|window| window == b"/AP 42 0 R")
        );
    }

    #[test]
    fn rejects_a_keyword_glued_to_endobj_after_the_bounded_head_read() {
        // The 512-byte head window ends exactly after `endobj`, so the head
        // parses; the complete read then sees a byte glued to that keyword.
        let mut object = b"9 0 obj\n[6 0 R /Fit".to_vec();
        object.resize(512 - b"]\nendobj".len(), b' ');
        object.extend_from_slice(b"]\nendobj");
        assert_eq!(object.len(), 512);
        let mut first = object.clone();
        first.extend_from_slice(&[b' '; 16]);
        let mut second = first.clone();
        second[512] = b'x';
        let mut source = Source::switching(first, second, |_, starts| starts >= 2);
        let fragment = FragmentObject {
            reference: PdfRef {
                number: 9,
                generation: 0,
            },
            range: PdfRange {
                offset: 0,
                length: source.size(),
            },
        };
        let error = inspect_link_destination_candidate(
            &mut source,
            fragment,
            &Limits::default(),
            &NeverCancel,
        )
        .expect_err("a glued endobj keyword was accepted");
        assert!(matches!(
            error,
            Error {
                kind: ErrorKind::Malformed,
                offset: Some(512),
                context: Context::Pdf {
                    object: Some((9, 0)),
                    repair: false
                },
                reason: "PDF keyword lacks a delimiter",
                ..
            }
        ));
    }
}