flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
//! Byte-identity demonstration: flpdf plain rewrite == `qpdf --static-id`.
//!
//! This is the capstone of the qpdf byte-identical roadmap. It is gated on the
//! `qpdf-zlib-compat` feature because byte-identity requires flpdf's deflate
//! output to match qpdf's classic-libz output (the Pure-Rust miniz_oxide default
//! produces equivalent but not byte-identical compression). Three independent
//! pieces must all line up:
//!
//!   1. Stream-dictionary key order — `/Length` pulled out, `/Filter` last on
//!      re-filtered streams (matches `QPDFWriter::unparseObject`).
//!   2. Trailer on the `trailer ` line with keys sorted and `/ID` last.
//!   3. No newline before `endstream` ([`NewlineBeforeEndstream::Never`]) —
//!      qpdf's default output writes exactly `/Length` bytes then `endstream`.
//!
//! plus deflate parity (this feature) and the deterministic `--static-id` trailer
//! `/ID`. With all of these, flpdf's full rewrite is `cmp`-diff-0 against the
//! committed `qpdf --static-id` golden references.
//!
//! CAVEAT: byte-identity pins to the linked libz version (captured with zlib1g
//! 1:1.3.dfsg-3.1ubuntu2.1 / qpdf 11.9.0); a different libz may shift the deflate
//! bytes and require re-blessing the goldens.

#![cfg(feature = "qpdf-zlib-compat")]

mod common;
use common::PdfCanonicalTestExt;

use common::{write_with_settings, WriterTestSettings};
use flpdf::{ObjectRef, ObjectStreamMode, Pdf, StreamDataMode, XrefEntry};
use std::io::Cursor;
use std::path::Path;

/// Full-rewrite `fixture` with the qpdf-matching option set and return the bytes.
fn rewrite_qpdf_equivalent(fixture: &str) -> Vec<u8> {
    rewrite_qpdf_equivalent_mode(fixture, ObjectStreamMode::Disable)
}

/// Full-rewrite `fixture` with an explicit object-stream mode and the
/// qpdf-matching option set.
fn rewrite_qpdf_equivalent_mode(fixture: &str, mode: ObjectStreamMode) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
    let mut pdf = Pdf::open(std::io::BufReader::new(file)).unwrap();

    let opts = WriterTestSettings {
        object_streams: mode,
        static_id: true,
        // qpdf's default output writes no newline before endstream.
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };
    // compress_streams defaults to Yes (decode + re-encode to single FlateDecode).

    let mut out = Vec::new();
    write_with_settings(&mut pdf, &mut out, &opts).unwrap();
    out
}

fn catalog_metadata_observation(bytes: &[u8]) -> (Option<ObjectRef>, Vec<u8>, Vec<u8>) {
    let mut pdf = Pdf::open(std::io::Cursor::new(bytes.to_vec())).expect("open metadata PDF");
    let metadata = pdf
        .root_handle()
        .expect("catalog handle")
        .try_get_key(b"/Metadata")
        .expect("catalog Metadata key");
    let object_ref = metadata.object_ref();
    let dictionary = metadata
        .try_get_stream_dict()
        .expect("metadata stream dictionary");
    let filter = dictionary
        .try_get_key(b"/Filter")
        .expect("metadata Filter lookup")
        .unparse();
    let packet = metadata
        .get_stream_data(flpdf::writer::DecodeLevel::All)
        .expect("decode XMP metadata packet");
    (object_ref, filter, packet.as_ref().clone())
}

fn golden(fixture_stem: &str) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/golden/references")
        .join(fixture_stem)
        .join("static-id.pdf");
    std::fs::read(&path).unwrap_or_else(|e| panic!("read golden {path:?}: {e}"))
}

/// Report the first differing byte offset for a readable failure message.
fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> {
    if a == b {
        return None;
    }
    let common = a.len().min(b.len());
    for i in 0..common {
        if a[i] != b[i] {
            return Some(i);
        }
    }
    Some(common)
}

fn assert_cmp_diff_zero(fixture: &str, stem: &str) {
    let actual = rewrite_qpdf_equivalent(fixture);
    let expected = golden(stem);
    if let Some(off) = first_diff(&actual, &expected) {
        let lo = off.saturating_sub(16);
        panic!(
            "{fixture}: not byte-identical to qpdf --static-id golden \
             (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
             flpdf : {:?}\ngolden: {:?}",
            actual.len(),
            expected.len(),
            &actual[lo..(off + 16).min(actual.len())],
            &expected[lo..(off + 16).min(expected.len())],
        );
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct PdfaSnapshot {
    language: Vec<u8>,
    mark_info: Vec<u8>,
    metadata_ref_valid: bool,
    metadata_filter: Vec<u8>,
    metadata_packet: Vec<u8>,
    output_intent_subtype: Vec<u8>,
    profile_ref_valid: bool,
    profile_n: Vec<u8>,
    profile_filter: Vec<u8>,
    icc_payload: Vec<u8>,
    struct_tree_ref_valid: bool,
    struct_element_ref_valid: bool,
    parent_tree_ref_valid: bool,
    associated_file: Option<(Vec<u8>, bool, Vec<u8>)>,
}

fn pdfa_snapshot(bytes: &[u8]) -> PdfaSnapshot {
    let mut pdf = Pdf::open(std::io::Cursor::new(bytes.to_vec())).expect("open PDF/A fixture");
    let catalog = pdf.root_handle().expect("catalog handle");
    let language = catalog
        .try_get_key(b"/Lang")
        .expect("catalog Lang")
        .unparse();
    let mark_info = catalog
        .try_get_key(b"/MarkInfo")
        .expect("catalog MarkInfo")
        .unparse();

    let metadata = catalog.try_get_key(b"/Metadata").expect("catalog Metadata");
    let metadata_ref_valid = metadata.object_ref().is_some();
    let metadata_dict = metadata
        .try_get_stream_dict()
        .expect("Metadata stream dictionary");
    let metadata_filter = metadata_dict
        .try_get_key(b"/Filter")
        .expect("Metadata Filter")
        .unparse();
    let metadata_packet = metadata
        .get_stream_data(flpdf::writer::DecodeLevel::All)
        .expect("decode XMP packet")
        .as_ref()
        .clone();

    let output_intents = catalog
        .try_get_key(b"/OutputIntents")
        .expect("catalog OutputIntents");
    let output_intent = output_intents
        .try_get_array_item(0)
        .expect("first OutputIntent");
    let output_intent_subtype = output_intent
        .try_get_key(b"/S")
        .expect("OutputIntent subtype")
        .unparse();
    let profile = output_intent
        .try_get_key(b"/DestOutputProfile")
        .expect("DestOutputProfile stream");
    let profile_ref_valid = profile.object_ref().is_some();
    let profile_dict = profile
        .try_get_stream_dict()
        .expect("ICC profile dictionary");
    let profile_n = profile_dict
        .try_get_key(b"/N")
        .expect("ICC component count")
        .unparse();
    let profile_filter = profile_dict
        .try_get_key(b"/Filter")
        .expect("ICC profile Filter")
        .unparse();
    let icc_payload = profile
        .get_stream_data(flpdf::writer::DecodeLevel::All)
        .expect("decode ICC profile")
        .as_ref()
        .clone();

    let struct_tree = catalog
        .try_get_key(b"/StructTreeRoot")
        .expect("catalog StructTreeRoot");
    let struct_tree_ref_valid = struct_tree.object_ref().is_some();
    let struct_element_ref_valid = struct_tree
        .try_get_key(b"/K")
        .expect("StructTreeRoot K")
        .object_ref()
        .is_some();
    let parent_tree_ref_valid = struct_tree
        .try_get_key(b"/ParentTree")
        .expect("StructTreeRoot ParentTree")
        .object_ref()
        .is_some();

    let associated_files = catalog.try_get_key(b"/AF").expect("catalog AF lookup");
    let associated_file = if associated_files.try_is_null().expect("AF type") {
        None
    } else {
        let filespec = associated_files
            .try_get_array_item(0)
            .expect("first associated Filespec");
        let relationship = filespec
            .try_get_key(b"/AFRelationship")
            .expect("Filespec AFRelationship")
            .unparse();
        let embedded_file = filespec
            .try_get_key(b"/EF")
            .expect("Filespec EF")
            .try_get_key(b"/F")
            .expect("embedded file stream");
        let embedded_file_ref_valid = embedded_file.object_ref().is_some();
        let embedded_file_payload = embedded_file
            .get_stream_data(flpdf::writer::DecodeLevel::All)
            .expect("read associated-file payload")
            .as_ref()
            .clone();
        Some((relationship, embedded_file_ref_valid, embedded_file_payload))
    };

    PdfaSnapshot {
        language,
        mark_info,
        metadata_ref_valid,
        metadata_filter,
        metadata_packet,
        output_intent_subtype,
        profile_ref_valid,
        profile_n,
        profile_filter,
        icc_payload,
        struct_tree_ref_valid,
        struct_element_ref_valid,
        parent_tree_ref_valid,
        associated_file,
    }
}

fn assert_cmp_diff_zero_mode_named(fixture: &str, mode: ObjectStreamMode, stem: &str, name: &str) {
    let actual = rewrite_qpdf_equivalent_mode(fixture, mode);
    assert_cmp_diff_zero_named(&actual, stem, name);
}

fn assert_mode_cmp_diff_zero(fixture: &str, mode: ObjectStreamMode) {
    assert_cmp_diff_zero_mode_named(&format!("{fixture}.pdf"), mode, fixture, "static-id.pdf");
}

/// Full-rewrite `fixture` with an explicit object-stream `mode` + forced version
/// (qpdf-matching options).
fn rewrite_mode_force_qpdf_equivalent(
    fixture: &str,
    mode: ObjectStreamMode,
    force: &str,
) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
    let mut pdf = Pdf::open(std::io::BufReader::new(file)).unwrap();

    let opts = WriterTestSettings {
        object_streams: mode,
        force_version: Some(force.to_string()),
        static_id: true,
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };

    let mut out = Vec::new();
    write_with_settings(&mut pdf, &mut out, &opts).unwrap();
    out
}

/// Read a named golden under `references/<stem>/`.
fn golden_named(stem: &str, name: &str) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/golden/references")
        .join(stem)
        .join(name);
    std::fs::read(&path).unwrap_or_else(|e| panic!("read golden {path:?}: {e}"))
}

/// Full-rewrite `fixture` in `--stream-data=preserve` mode with the qpdf-matching
/// option set (matches `qpdf --static-id --stream-data=preserve`).
fn rewrite_preserve_qpdf_equivalent(fixture: &str) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
    let mut pdf = Pdf::open(std::io::BufReader::new(file)).unwrap();

    let opts = WriterTestSettings {
        static_id: true,
        stream_data: Some(StreamDataMode::Preserve),
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };

    let mut out = Vec::new();
    write_with_settings(&mut pdf, &mut out, &opts).unwrap();
    out
}

/// Assert `actual` is byte-identical to the named golden under `references/<stem>/`.
fn assert_cmp_diff_zero_named(actual: &[u8], stem: &str, name: &str) {
    let expected = golden_named(stem, name);
    if let Some(off) = first_diff(actual, &expected) {
        let lo = off.saturating_sub(16);
        panic!(
            "{stem}/{name}: not byte-identical to qpdf golden \
             (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
             flpdf : {:?}\ngolden: {:?}",
            actual.len(),
            expected.len(),
            &actual[lo..(off + 16).min(actual.len())],
            &expected[lo..(off + 16).min(expected.len())],
        );
    }
}

#[test]
fn force_below_1_5_downgrades_xref_stream_source_byte_identical_to_qpdf() {
    // The xref-stream -> classic-table DOWNGRADE path is new (ipc6 only ever did
    // table -> stream UPGRADES). Anchor it to qpdf: flpdf preserve+force1.4 on an
    // ObjStm/xref-stream source must be byte-identical to qpdf's classic-table
    // output (qpdf --object-streams=preserve --force-version=1.4 --static-id).
    let actual = rewrite_mode_force_qpdf_equivalent(
        "three-page-objstm.pdf",
        ObjectStreamMode::Preserve,
        "1.4",
    );
    let expected = golden_named("three-page-objstm", "downgrade-force14.pdf");
    if let Some(off) = first_diff(&actual, &expected) {
        let lo = off.saturating_sub(16);
        panic!(
            "xref-stream downgrade not byte-identical to qpdf golden \
             (flpdf={} bytes, golden={} bytes, first diff at byte {off})\n\
             flpdf : {:?}\ngolden: {:?}",
            actual.len(),
            expected.len(),
            &actual[lo..(off + 16).min(actual.len())],
            &expected[lo..(off + 16).min(expected.len())],
        );
    }
}

#[test]
fn one_two_three_page_mode_matrix_is_byte_identical_to_qpdf() {
    for fixture in ["one-page", "two-page", "three-page"] {
        for mode in [ObjectStreamMode::Disable, ObjectStreamMode::Preserve] {
            assert_mode_cmp_diff_zero(fixture, mode);
        }
    }
}

#[test]
fn compressed_metadata_xmp_rewrite_matches_qpdf_and_preserves_decoded_packet() {
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/compressed-metadata.pdf");
    let input = std::fs::read(&fixture_path).expect("read compressed metadata fixture");
    let (input_ref, input_filter, input_packet) = catalog_metadata_observation(&input);
    assert!(
        input_ref.is_some(),
        "input /Metadata reference must be indirect"
    );
    assert_eq!(input_filter, b"/FlateDecode");

    let actual = rewrite_qpdf_equivalent("compressed-metadata.pdf");
    assert_cmp_diff_zero_named(&actual, "compressed-metadata", "static-id.pdf");
    let (output_ref, output_filter, output_packet) = catalog_metadata_observation(&actual);
    assert!(
        output_ref.is_some(),
        "output /Metadata reference must remain valid"
    );
    assert_eq!(
        output_filter, b"null",
        "qpdf removes the source filter for clear XMP"
    );
    assert_eq!(
        output_packet, input_packet,
        "decoded XMP packet bytes must survive"
    );
}

#[test]
fn pdfa_part_fixtures_round_trip_like_qpdf() {
    for (part, fixture, stem) in [
        (1, "pdfa-1b.pdf", "pdfa-1b"),
        (2, "pdfa-2b.pdf", "pdfa-2b"),
        (3, "pdfa-3b.pdf", "pdfa-3b"),
    ] {
        let input_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(fixture);
        let input = std::fs::read(&input_path)
            .unwrap_or_else(|error| panic!("read {input_path:?}: {error}"));
        let before = pdfa_snapshot(&input);
        assert!(
            before.metadata_ref_valid,
            "PDF/A-{part}b Metadata reference"
        );
        assert!(before.profile_ref_valid, "PDF/A-{part}b ICC reference");
        assert!(
            before.struct_tree_ref_valid,
            "PDF/A-{part}b StructTreeRoot reference"
        );
        assert!(
            before.struct_element_ref_valid,
            "PDF/A-{part}b StructElem reference"
        );
        assert!(
            before.parent_tree_ref_valid,
            "PDF/A-{part}b ParentTree reference"
        );
        let marker = format!("pdfaid:part=\"{part}\"");
        assert!(
            before
                .metadata_packet
                .windows(marker.len())
                .any(|window| window == marker.as_bytes()),
            "XMP must identify PDF/A part {part}"
        );
        assert_eq!(before.metadata_filter, b"/FlateDecode");
        assert_eq!(before.profile_filter, b"null");
        assert_eq!(before.associated_file.is_some(), part == 3);

        let mut expected_after = before.clone();
        expected_after.metadata_filter = b"null".to_vec();
        expected_after.profile_filter = b"/FlateDecode".to_vec();
        let actual = rewrite_qpdf_equivalent(fixture);
        assert_cmp_diff_zero_named(&actual, stem, "static-id.pdf");
        assert_eq!(
            pdfa_snapshot(&actual),
            expected_after,
            "decoded PDF/A-{part}b payloads and references must survive qpdf-equivalent rewrite"
        );
    }
}

/// A direct `/Root` survives when Preserve selects a cross-reference stream.
///
/// `canonical_trailer_entries` omits `/Root`, and the cross-reference stream
/// serializer reads it only from the trailer plan, so the live route has to
/// serialize an inline Catalog itself. Before this cutover the live route was
/// always classic-table, where the trailer handle carried `/Root`; selecting a
/// stream without wiring the direct Catalog drops it and makes the output
/// unreadable.
#[test]
fn direct_root_survives_a_preserve_cross_reference_stream() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("direct-root-objstm.pdf");
    std::fs::write(&input, direct_root_object_stream_pdf()).expect("write fixture");
    let expected_path = directory.path().join("qpdf.pdf");

    let status = std::process::Command::new(oracle)
        .args(["--deterministic-id", "--object-streams=preserve"])
        .arg(&input)
        .arg(&expected_path)
        .status()
        .expect("qpdf runs");
    assert!(
        status.success(),
        "qpdf must rewrite the direct-root fixture"
    );

    let file = std::fs::File::open(&input).expect("open fixture");
    let mut pdf = Pdf::open(std::io::BufReader::new(file)).expect("fixture parses");
    let opts = WriterTestSettings {
        object_streams: ObjectStreamMode::Preserve,
        deterministic_id: true,
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };
    let mut actual = Vec::new();
    write_with_settings(&mut pdf, &mut actual, &opts).expect("rewrite succeeds");

    let expected = std::fs::read(&expected_path).expect("qpdf output");
    if let Some(off) = first_diff(&actual, &expected) {
        panic!(
            "direct-root Preserve output diverged from qpdf 11.9.0 \
             (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})",
            actual.len(),
            expected.len(),
        );
    }
}

/// A PDF whose trailer holds an inline Catalog and whose cross-reference stream
/// marks one object as a member of a source object stream.
fn direct_root_object_stream_pdf() -> Vec<u8> {
    fn deflate(data: &[u8]) -> Vec<u8> {
        use std::io::Write;
        let mut encoder =
            flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(data).expect("deflate write");
        encoder.finish().expect("deflate finish")
    }

    let member = b"<< /Type /Metadata /Note (in-objstm) >>";
    let first = b"5 0 ";
    let mut objstm_data = first.to_vec();
    objstm_data.extend_from_slice(member);
    let mut out = b"%PDF-1.5\n%\xe2\xe3\xcf\xd3\n".to_vec();
    let mut offsets = std::collections::BTreeMap::new();
    let bodies: [(u32, Vec<u8>); 2] = [
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Meta 5 0 R >>"
                .to_vec(),
        ),
    ];
    for (number, body) in bodies {
        offsets.insert(number, out.len());
        out.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
        out.extend_from_slice(&body);
        out.extend_from_slice(b"\nendobj\n");
    }
    offsets.insert(4, out.len());
    out.extend_from_slice(
        format!(
            "4 0 obj\n<< /Type /ObjStm /N 1 /First {} /Length {} >>\nstream\n",
            first.len(),
            objstm_data.len()
        )
        .as_bytes(),
    );
    out.extend_from_slice(&objstm_data);
    out.extend_from_slice(b"\nendstream\nendobj\n");

    let xref_offset = out.len();
    let mut rows: Vec<[u8; 7]> = Vec::new();
    let row = |kind: u8, field2: u32, field3: u16| {
        let mut entry = [0u8; 7];
        entry[0] = kind;
        entry[1..5].copy_from_slice(&field2.to_be_bytes());
        entry[5..7].copy_from_slice(&field3.to_be_bytes());
        entry
    };
    rows.push(row(0, 0, 65535));
    rows.push(row(0, 0, 65535));
    for number in [2u32, 3, 4] {
        rows.push(row(1, offsets[&number] as u32, 0));
    }
    rows.push(row(2, 4, 0));
    rows.push(row(1, xref_offset as u32, 0));
    let table: Vec<u8> = rows.concat();
    let compressed = deflate(&table);
    out.extend_from_slice(
        format!(
            "6 0 obj\n<< /Type /XRef /Size 7 /W [1 4 2] \
             /Root << /Type /Catalog /Pages 2 0 R >> /Filter /FlateDecode /Length {} >>\nstream\n",
            compressed.len()
        )
        .as_bytes(),
    );
    out.extend_from_slice(&compressed);
    out.extend_from_slice(b"\nendstream\nendobj\n");
    out.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
    out
}

/// `--preserve-unreferenced` with source object streams, compared against the
/// pinned qpdf 11.9.0 binary rather than a committed golden.
///
/// This axis has no golden reference, and it is the axis this cutover actually
/// changes: with `preserve_unreferenced` the planner skips its eligibility
/// filter, so every source container survives into the live walk. Run the
/// oracle at test time for the ObjStm fixtures instead of leaving the axis
/// unpinned.
#[test]
fn preserve_unreferenced_with_source_object_streams_matches_qpdf_11_9() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let directory = tempfile::tempdir().expect("tempdir");
    for fixture in [
        "null-visible-matrix-objstm.pdf",
        "null-visible-preserve-empty-removed.pdf",
        "null-visible-stale-generation-objstm.pdf",
        "null-visible-preserve-signature.pdf",
        "three-page-objstm.pdf",
        "shared-stream-objstm.pdf",
    ] {
        let input = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(fixture);
        let expected_path = directory.path().join(format!("{fixture}.qpdf"));
        let status = std::process::Command::new(oracle)
            .args([
                "--deterministic-id",
                "--object-streams=preserve",
                "--preserve-unreferenced",
            ])
            .arg(&input)
            .arg(&expected_path)
            .status()
            .expect("qpdf runs");
        // Exit 3 is qpdf's "succeeded with warnings"; it still writes the file
        // and is the expected status for the damaged fixtures here.
        assert!(
            matches!(status.code(), Some(0 | 3)),
            "{fixture}: qpdf --preserve-unreferenced must produce output, got {:?}",
            status.code()
        );

        let actual = rewrite_qpdf_equivalent_preserve_unreferenced(fixture);
        let expected = std::fs::read(&expected_path).expect("qpdf output");
        if let Some(off) = first_diff(&actual, &expected) {
            panic!(
                "{fixture}: --preserve-unreferenced output diverged from qpdf 11.9.0 \
                 (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})",
                actual.len(),
                expected.len(),
            );
        }
    }
}

/// The QDF form of the source-backed Preserve route must admit the same
/// signature dictionary that qpdf keeps when `preserve-unreferenced` disables
/// the ordinary compressible-object eligibility filter.
///
/// Keep the two already-fixed damaged ObjStm fixtures in this exact-option
/// comparison as regression controls. The signature fixture was the RED case
/// for `flpdf-lhzo`: qpdf succeeded and emitted the member, while the old body
/// validator rejected it before emission.
#[test]
fn qdf_preserve_unreferenced_signature_objstm_matches_qpdf_11_9() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let directory = tempfile::tempdir().expect("tempdir");
    for fixture in [
        "null-visible-preserve-signature.pdf",
        "null-visible-preserve-empty-removed.pdf",
        "null-visible-stale-generation-objstm.pdf",
        "trailer-external-file-keys.pdf",
    ] {
        let input = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(fixture);
        let expected_path = directory.path().join(format!("{fixture}.qpdf"));
        let status = std::process::Command::new(oracle)
            .args(["--static-id", "--qdf", "--preserve-unreferenced"])
            .arg(&input)
            .arg(&expected_path)
            .status()
            .expect("qpdf runs");
        if fixture == "null-visible-preserve-signature.pdf" {
            assert_eq!(
                status.code(),
                Some(0),
                "{fixture}: qpdf signature rewrite must succeed without warnings"
            );
        }
        assert!(
            matches!(status.code(), Some(0 | 3)),
            "{fixture}: qpdf --qdf --preserve-unreferenced must produce output, got {:?}",
            status.code()
        );

        let actual = rewrite_qdf_preserve_unreferenced(fixture).unwrap_or_else(|error| {
            panic!("{fixture}: flpdf --qdf --preserve-unreferenced must succeed like qpdf: {error}")
        });
        let expected = std::fs::read(&expected_path).expect("qpdf output");
        if let Some(off) = first_diff(&actual, &expected) {
            panic!(
                "{fixture}: --qdf --preserve-unreferenced output diverged from qpdf 11.9.0 \
                 (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})",
                actual.len(),
                expected.len(),
            );
        }
    }
}

/// qpdf's `QPDF_Stream::pipeStreamData` reads the parsed in-body payload even
/// when the stream dictionary also carries the external-file keys `/F`,
/// `/FFilter`, and `/FDecodeParms`; `QPDFWriter::unparseObject` preserves those
/// keys while replacing `/Length` with the emitted payload length
/// (`QPDF_Stream.cc:605-620`, `QPDFWriter.cc:1239-1314,1440-1455`). Keep this
/// preserve-mode edge compared against the live qpdf 11.9.0 oracle.
#[test]
fn preserve_external_file_stream_matches_qpdf_11_9() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let input = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/external-file-stream.pdf");
    let directory = tempfile::tempdir().expect("tempdir");
    let expected_path = directory.path().join("qpdf.pdf");
    let status = std::process::Command::new(oracle)
        .args(["--static-id", "--stream-data=preserve"])
        .arg(&input)
        .arg(&expected_path)
        .status()
        .expect("qpdf runs");
    assert!(
        matches!(status.code(), Some(0 | 3)),
        "qpdf preserve rewrite must produce output, got {:?}",
        status.code()
    );

    let actual = rewrite_preserve_qpdf_equivalent("external-file-stream.pdf");
    let expected = std::fs::read(&expected_path).expect("qpdf output");
    if let Some(off) = first_diff(&actual, &expected) {
        let lo = off.saturating_sub(16);
        panic!(
            "external-file stream preserve output diverged from qpdf 11.9.0 \
             (flpdf={} bytes, qpdf={} bytes, first diff at byte {off})\n\
             flpdf : {:?}\nqpdf  : {:?}",
            actual.len(),
            expected.len(),
            &actual[lo..(off + 16).min(actual.len())],
            &expected[lo..(off + 16).min(expected.len())],
        );
    }
}

/// `QPDFWriter::getTrimmedTrailer` removes only xref-structural keys; the
/// external-file keys `/F`, `/FFilter`, and `/FDecodeParms` remain ordinary
/// trailer entries and their references participate in qpdf's live walk
/// (`QPDFWriter.cc:1160-1236,2009-2031`).
#[test]
fn trailer_external_file_keys_match_qpdf_11_9() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let fixture = "trailer-external-file-keys.pdf";
    let input = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let directory = tempfile::tempdir().expect("tempdir");
    let expected_path = directory.path().join("qpdf.pdf");
    let status = std::process::Command::new(oracle)
        .args(["--static-id"])
        .arg(&input)
        .arg(&expected_path)
        .status()
        .expect("qpdf runs");
    assert_eq!(status.code(), Some(0), "qpdf rewrite must succeed");

    let actual = rewrite_qpdf_equivalent(fixture);
    let expected = std::fs::read(&expected_path).expect("qpdf output");
    assert_eq!(
        actual, expected,
        "trailer external-file keys must match qpdf"
    );

    let mut output = Pdf::open(Cursor::new(actual)).expect("open rewritten output");
    let trailer = output.trailer();
    assert_eq!(trailer.try_get_key(b"/F").unwrap().unparse(), b"2 0 R");
    assert_eq!(
        trailer.try_get_key(b"/FFilter").unwrap().unparse(),
        b"/ASCIIHexDecode"
    );
    assert_eq!(
        trailer.try_get_key(b"/FDecodeParms").unwrap().unparse(),
        b"<< /Columns 1 >>"
    );
}

#[test]
fn trailer_external_file_keys_generate_match_qpdf_11_9() {
    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable");
        return;
    };
    let fixture = "trailer-external-file-keys.pdf";
    let input = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let directory = tempfile::tempdir().expect("tempdir");
    let expected_path = directory.path().join("qpdf.pdf");
    let status = std::process::Command::new(oracle)
        .args(["--static-id", "--object-streams=generate"])
        .arg(&input)
        .arg(&expected_path)
        .status()
        .expect("qpdf runs");
    assert_eq!(status.code(), Some(0), "qpdf generate rewrite must succeed");

    let actual = rewrite_qpdf_equivalent_mode(fixture, ObjectStreamMode::Generate);
    let expected = std::fs::read(&expected_path).expect("qpdf output");
    assert_eq!(
        actual, expected,
        "Generate must retain trailer external-file keys like qpdf"
    );
}

/// The pinned qpdf 11.9.0 oracle, or `None` when it is unavailable. Comparing
/// against a different qpdf is not a parity result, so the version is checked.
fn pinned_qpdf() -> Option<&'static str> {
    let output = std::process::Command::new("qpdf").arg("--version").output();
    output.ok().and_then(|output| {
        String::from_utf8_lossy(&output.stdout)
            .lines()
            .next()
            .is_some_and(|line| line == "qpdf version 11.9.0")
            .then_some("qpdf")
    })
}

fn rewrite_qpdf_equivalent_preserve_unreferenced(fixture: &str) -> Vec<u8> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
    let mut pdf = Pdf::open(std::io::BufReader::new(file)).unwrap();

    let opts = WriterTestSettings {
        object_streams: ObjectStreamMode::Preserve,
        // qpdf is invoked with `--deterministic-id`, whose content hash differs
        // from `--static-id`'s fixed value; setting both here would pick the
        // static one and diverge in the trailer `/ID` alone.
        deterministic_id: true,
        preserve_unreferenced_objects: true,
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };

    let mut out = Vec::new();
    write_with_settings(&mut pdf, &mut out, &opts).unwrap();
    out
}

fn rewrite_qdf_preserve_unreferenced(fixture: &str) -> flpdf::Result<Vec<u8>> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
    let mut pdf = Pdf::open(std::io::BufReader::new(file))?;

    let opts = WriterTestSettings {
        object_streams: ObjectStreamMode::Preserve,
        qdf: true,
        static_id: true,
        preserve_unreferenced_objects: true,
        newline_before_endstream: flpdf::NewlineBeforeEndstream::Never,
        ..WriterTestSettings::default()
    };

    let mut out = Vec::new();
    write_with_settings(&mut pdf, &mut out, &opts)?;
    Ok(out)
}

/// Preserve mode on a source with no object streams has nothing to preserve:
/// `preserveObjectStreams` returns before it builds any mapping
/// (`QPDFWriter.cc:1941-1945`), so the walk, the version floor and the
/// cross-reference form all match Disable (`:1097-1106`, `:2172-2173`,
/// `:3023-3025`).
///
/// This states the equivalence directly rather than leaving it implied by the
/// two separate golden comparisons above. It does not, on its own, pin which
/// internal route serves the case: both routes match the same golden bytes for
/// these fixtures, so reverting the routing keeps this test green. The
/// `--preserve-unreferenced` oracle comparison above does pin the routing --
/// reverting it makes that test fail -- because that axis skips the planner's
/// eligibility filter and reaches the live walk with every source container.
#[test]
fn preserve_with_no_source_object_streams_matches_disable_byte_for_byte() {
    for fixture in [
        "one-page",
        "two-page",
        "three-page",
        "preserve-no-source-objstm-xref",
    ] {
        let disable =
            rewrite_qpdf_equivalent_mode(&format!("{fixture}.pdf"), ObjectStreamMode::Disable);
        let preserve =
            rewrite_qpdf_equivalent_mode(&format!("{fixture}.pdf"), ObjectStreamMode::Preserve);
        assert_eq!(
            disable, preserve,
            "{fixture}: Preserve-with-no-source-ObjStm diverged from Disable"
        );
    }
}

/// A source xref stream with no type-2 rows must not make Preserve retain an
/// object-stream layout. qpdf's `preserveObjectStreams` returns at its empty
/// source-membership check, so both Preserve and Disable emit the same
/// classic-xref rewrite (`QPDFWriter.cc:1939-1945,2172-2173,3023-3025`).
/// Compare both modes with the live qpdf 11.9.0 output as well as with each
/// other so this is an observable source-xref-form regression case, not only a
/// comparison against a shared golden.
#[test]
fn preserve_no_source_objstm_xref_stream_matches_qpdf_11_9() {
    let fixture = "preserve-no-source-objstm-xref.pdf";
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);

    // Pin what makes this fixture the regression case: a source cross-reference
    // *stream* carrying no type-2 rows. Without this, swapping the file for any
    // classic-xref document would leave every assertion below green and quietly
    // remove the source-xref-form coverage this test claims.
    let source = std::fs::read(&fixture_path).expect("fixture is readable");
    // Resolve `startxref` and inspect the section it points at rather than
    // searching the whole file for markers: a raw search accepts a decoy
    // string such as `(/Type /XRef)` in unreachable content, and a raw
    // exclusion misses a CRLF classic table.
    let startxref = source
        .windows(b"startxref".len())
        .rposition(|window| window == b"startxref")
        .expect("fixture has a startxref");
    let offset: usize = String::from_utf8_lossy(&source[startxref + b"startxref".len()..])
        .split_whitespace()
        .next()
        .expect("startxref carries an offset")
        .parse()
        .expect("startxref offset is numeric");
    assert!(
        !source[offset..].starts_with(b"xref"),
        "the fixture's last cross-reference section must be a stream, not a classic table"
    );
    let source_pdf = Pdf::open(std::io::Cursor::new(source)).expect("fixture opens");
    assert!(
        source_pdf
            .get_xref_table()
            .values()
            .all(|entry| !matches!(entry, XrefEntry::Compressed { .. })),
        "the fixture must have no type-2 rows, or it is no longer the empty-membership case"
    );

    // The local mode and output-form assertions do not need the oracle, so
    // they run everywhere. Only the byte comparison against qpdf is gated;
    // otherwise an environment without the pinned binary would silently stop
    // checking that a source xref stream is not carried into the rewrite.
    let preserve = rewrite_qpdf_equivalent_mode(fixture, ObjectStreamMode::Preserve);
    let disable = rewrite_qpdf_equivalent_mode(fixture, ObjectStreamMode::Disable);
    assert_eq!(
        preserve, disable,
        "empty source membership must produce the Disable-equivalent bytes"
    );
    // `startxref\n` also contains `xref\n`, so anchor on a standalone section
    // header followed by its first subsection. Without the leading newline and
    // the `0 ` subsection start, an output with no xref section at all would
    // still satisfy this assertion.
    assert!(
        preserve
            .windows(b"\nxref\n0 ".len())
            .any(|window| window == b"\nxref\n0 "),
        "an empty source membership must use a classic xref table"
    );
    assert!(
        !preserve
            .windows(b"/Type /XRef".len())
            .any(|window| window == b"/Type /XRef"),
        "the source xref stream must not be carried into the rewritten output"
    );

    let Some(oracle) = pinned_qpdf() else {
        eprintln!("[SKIP cmp_diff_zero_tests] qpdf 11.9.0 is unavailable for the byte comparison");
        return;
    };
    let directory = tempfile::tempdir().expect("tempdir");
    let expected_path = directory.path().join("qpdf.pdf");
    let status = std::process::Command::new(oracle)
        .args(["--static-id", "--object-streams=preserve"])
        .arg(&fixture_path)
        .arg(&expected_path)
        .status()
        .expect("qpdf runs");
    assert_eq!(status.code(), Some(0), "qpdf preserve rewrite must succeed");
    let expected = std::fs::read(&expected_path).expect("qpdf output");
    assert_eq!(preserve, expected, "Preserve output must match qpdf 11.9.0");
}

#[test]
fn disable_xref_stream_source_downgrades_to_classic_table_byte_identical_to_qpdf() {
    assert_cmp_diff_zero_mode_named(
        "null-visible-matrix-objstm.pdf",
        ObjectStreamMode::Disable,
        "null-visible-matrix-objstm",
        "disable.pdf",
    );
}

#[test]
fn preserve_object_stream_mode_is_byte_identical_to_qpdf_static_id_matrix() {
    let cases = [
        ("three-page-objstm.pdf", "three-page-objstm", "preserve.pdf"),
        (
            "objstm-lin-od-indirect-length.pdf",
            "objstm-lin-od-indirect-length",
            "static-id.pdf",
        ),
        (
            "objstm-lin-od-indirect-length-flate.pdf",
            "objstm-lin-od-indirect-length-flate",
            "static-id.pdf",
        ),
        (
            "kept-indirect-length.pdf",
            "kept-indirect-length",
            "static-id.pdf",
        ),
    ];
    for (fixture, stem, name) in cases {
        assert_cmp_diff_zero_mode_named(fixture, ObjectStreamMode::Preserve, stem, name);
    }
}

#[test]
fn preserve_nonmonotonic_source_indices_match_qpdf_source_number_order() {
    let fixture = "nonmonotonic-objstm-index.pdf";
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .join(fixture);
    let source = std::fs::read(path).unwrap();
    let source_pdf = Pdf::open(Cursor::new(source)).unwrap();
    let source_xref = source_pdf.get_xref_table();
    assert_eq!(
        source_xref.get(&ObjectRef::new(3, 0)),
        Some(&XrefEntry::Compressed {
            stream: 4,
            index: 0,
        })
    );
    assert_eq!(
        source_xref.get(&ObjectRef::new(2, 0)),
        Some(&XrefEntry::Compressed {
            stream: 4,
            index: 1,
        })
    );

    let actual = rewrite_qpdf_equivalent_mode(fixture, ObjectStreamMode::Preserve);
    assert_cmp_diff_zero_named(&actual, "nonmonotonic-objstm-index", "preserve.pdf");

    let output_pdf = Pdf::open(Cursor::new(actual.clone())).unwrap();
    let output_xref = output_pdf.get_xref_table();
    assert_eq!(
        output_xref.get(&ObjectRef::new(3, 0)),
        Some(&XrefEntry::Compressed {
            stream: 2,
            index: 0,
        })
    );
    assert_eq!(
        output_xref.get(&ObjectRef::new(4, 0)),
        Some(&XrefEntry::Compressed {
            stream: 2,
            index: 1,
        })
    );

    let mut rewritten = Pdf::open(Cursor::new(actual)).unwrap();
    let catalog = rewritten
        .resolve_canonical_object(rewritten.root_ref().unwrap())
        .unwrap();
    assert_eq!(
        catalog.try_get_key(b"/Pages").unwrap().object_ref(),
        Some(ObjectRef::new(3, 0))
    );
    assert_eq!(
        catalog.try_get_key(b"/Extra").unwrap().object_ref(),
        Some(ObjectRef::new(4, 0))
    );
}

#[test]
fn lone_flate_l9_plain_rewrite_is_byte_identical_to_qpdf_static_id() {
    // A lone /FlateDecode source compressed at level 9: flpdf must preserve the
    // bytes verbatim (qpdf default), so re-encoding at level 6 would diverge.
    assert_cmp_diff_zero("lone-flate-l9.pdf", "lone-flate-l9");
}

#[test]
fn od_indirect_length_plain_rewrite_drops_orphan_holder_byte_identical_to_qpdf() {
    // The catalog's /OpenAction reaches a JavaScript stream (obj 6) with an
    // INDIRECT /Length (7 0 R); the holder (obj 7) is reachable ONLY through
    // that /Length edge. Once /Length is normalized to a direct integer the
    // holder orphans, and qpdf garbage-collects it. The plain full-rewrite path
    // must drop it too, shifting object numbers contiguously — not
    // emit it as a trailing integer object.
    assert_cmp_diff_zero(
        "objstm-lin-od-indirect-length.pdf",
        "objstm-lin-od-indirect-length",
    );
}

#[test]
fn od_indirect_length_flate_plain_rewrite_drops_orphan_holder_byte_identical_to_qpdf() {
    // Same orphan structure, but the JS stream is a lone /FlateDecode (the
    // writer's verbatim-preserve path): /Length is direct-ized to the
    // compressed byte count when the holder is dropped.
    assert_cmp_diff_zero(
        "objstm-lin-od-indirect-length-flate.pdf",
        "objstm-lin-od-indirect-length-flate",
    );
}

#[test]
fn od_indirect_length_preserve_drops_orphan_holder_byte_identical_to_qpdf() {
    // --stream-data=preserve keeps the stream bytes verbatim, but qpdf still
    // direct-izes every stream's /Length and GCs the orphaned holder.
    // The orphan-drop gate must therefore fire for preserve too, not only when
    // streams are recompressed.
    let actual = rewrite_preserve_qpdf_equivalent("objstm-lin-od-indirect-length.pdf");
    assert_cmp_diff_zero_named(&actual, "objstm-lin-od-indirect-length", "preserve.pdf");
}

#[test]
fn od_indirect_length_flate_preserve_drops_orphan_holder_byte_identical_to_qpdf() {
    // Same as above with a lone /FlateDecode JS stream: under preserve the
    // compressed bytes are kept verbatim and /Length is direct-ized to the
    // compressed byte count when the holder is dropped.
    let actual = rewrite_preserve_qpdf_equivalent("objstm-lin-od-indirect-length-flate.pdf");
    assert_cmp_diff_zero_named(
        &actual,
        "objstm-lin-od-indirect-length-flate",
        "preserve.pdf",
    );
}

#[test]
fn kept_indirect_length_preserve_directizes_kept_holder_byte_identical_to_qpdf() {
    // The dual of the orphan case: the image XObject's indirect /Length holder is
    // ALSO referenced by the catalog (/KeepHolder), so it stays live. qpdf still
    // direct-izes the stream's /Length even under preserve (it normalizes EVERY
    // stream's /Length to a direct integer), keeping the holder as a now
    // length-unreferenced live integer. flpdf must match.
    let actual = rewrite_preserve_qpdf_equivalent("kept-indirect-length.pdf");
    assert_cmp_diff_zero_named(&actual, "kept-indirect-length", "preserve.pdf");
}

#[test]
fn kept_indirect_length_plain_rewrite_directizes_length_keeps_holder_byte_identical_to_qpdf() {
    // Dual of the orphan case: an image XObject (obj 5) declares
    // /Filter /DCTDecode — which flpdf cannot decode, so it is passed through
    // verbatim — and carries an INDIRECT /Length (6 0 R) whose holder (obj 6) is
    // ALSO referenced by the catalog (/KeepHolder 6 0 R). qpdf direct-izes the
    // /Length to the raw byte count (every emitted stream gets a direct /Length)
    // while KEEPING the holder (it has another live reference). The decode-failure
    // passthrough path used to leak the renumbered indirect /Length; this pins it
    // byte-identical to qpdf.
    assert_cmp_diff_zero("kept-indirect-length.pdf", "kept-indirect-length");
}