flpdf 0.5.1

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
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
//! qpdf correspondence: QPDFWriter.cc standard-write object placement and renumber planning.
//! Logical object placements for the qpdf-shaped plain writer pipeline.

use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};
use std::io::{Read, Seek};

use crate::pdf_version::{parse_qpdf_writer_version, QpdfVersionParts};
use crate::writer::object_streams::{self, ObjectStreamGroup, ObjectStreamMode};
use crate::writer::plain::body;
use crate::writer::plain::xref::{materialized_id_handle, IdPlan, TrailerPlan};
use crate::writer::rewrite_renumber::{
    CanonicalCatalogFirstRenumber, NewNumberLookup, ObjectStreamRenumber, StreamParametersRemoved,
};
use crate::writer::{ObjectWriterEmission, WriterOptions};
use crate::{CompressStreams, ObjectRef, Pdf, XrefEntry, XrefForm};

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PlannedMember {
    pub(crate) source: ObjectRef,
    pub(crate) output: ObjectRef,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PlannedObjectStreamOrigin {
    SourceBacked(ObjectRef),
    Synthetic,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PlannedIndirectObject {
    Source {
        source: ObjectRef,
        output: ObjectRef,
    },
    ObjectStream {
        origin: PlannedObjectStreamOrigin,
        output: ObjectRef,
        members: Vec<PlannedMember>,
    },
}

#[derive(Clone, Debug)]
pub(crate) struct CachedStreamOutput {
    pub(crate) dict: crate::ObjectHandle,
    pub(crate) data: Vec<u8>,
    pub(crate) refiltered: bool,
    pub(crate) parameters_removed: bool,
    pub(crate) fingerprint: StreamCacheFingerprint,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StreamCacheFingerprint {
    stream: (usize, u64),
    dictionary: (usize, u64),
    parameter_handles: Vec<(usize, u64)>,
}

pub(crate) fn stream_cache_fingerprint(
    handle: &crate::ObjectHandle,
) -> crate::Result<StreamCacheFingerprint> {
    let dictionary = handle
        .as_stream_dict()
        .ok_or_else(|| crate::Error::Internal("canonical stream dictionary is missing".into()))?;
    let mut parameter_handles = Vec::new();
    for key in [
        b"/Filter".as_slice(),
        b"/DecodeParms".as_slice(),
        b"/F".as_slice(),
        b"/FFilter".as_slice(),
        b"/FDecodeParms".as_slice(),
    ] {
        let value = dictionary.try_get_key(key)?;
        if value.try_is_null()? {
            continue;
        }
        value.try_dereference()?;
        parameter_handles.push(value.mutation_fingerprint());
    }
    Ok(StreamCacheFingerprint {
        stream: handle.mutation_fingerprint(),
        dictionary: dictionary.mutation_fingerprint(),
        parameter_handles,
    })
}

#[derive(Clone, Debug)]
pub(crate) struct PlainWritePlan {
    pub(crate) version: String,
    pub(crate) objects: Vec<PlannedIndirectObject>,
    /// Remapped Catalog identity when the source `/Root` is indirect.
    pub(crate) root: Option<ObjectRef>,
    /// Canonical Catalog handle when the source `/Root` is direct.
    pub(crate) direct_root: Option<crate::ObjectHandle>,
    pub(crate) old_to_new: HashMap<ObjectRef, ObjectRef>,
    pub(crate) removed_refs: BTreeSet<ObjectRef>,
    pub(crate) cached_stream_outputs: HashMap<ObjectRef, CachedStreamOutput>,
    pub(crate) trailer: TrailerPlan,
}

impl PlainWritePlan {
    pub(crate) fn generated_object_stream_count(&self) -> usize {
        self.objects
            .iter()
            .filter(|object| {
                matches!(
                    object,
                    PlannedIndirectObject::ObjectStream {
                        origin: PlannedObjectStreamOrigin::Synthetic,
                        ..
                    }
                )
            })
            .count()
    }

    pub(crate) fn build<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        options: &WriterOptions,
    ) -> crate::Result<Self> {
        let source_root_ref = pdf.root_ref();
        let source_root_handle = if source_root_ref.is_none() {
            let root_candidate = pdf.trailer_key_handle(b"Root");
            if root_candidate.is_null() {
                return Err(crate::Error::Missing("/Root"));
            }
            Some(pdf.root_handle()?)
        } else {
            None
        };
        let source_had_compressed_objects = source_has_compressed_entries(pdf);
        let explicitly_removed: BTreeSet<ObjectRef> =
            pdf.deleted_object_refs().into_iter().collect();
        let cached_stream_outputs: RefCell<HashMap<ObjectRef, CachedStreamOutput>> =
            RefCell::new(HashMap::new());
        let stream_parameters_removed = |handle: &crate::ObjectHandle| {
            let Some(source) = handle.object_ref() else {
                return if handle.is_data_modified() {
                    Ok(false)
                } else {
                    body::canonical_stream_will_be_refiltered(handle, options)
                };
            };
            if let Some(cached) = cached_stream_outputs.borrow().get(&source) {
                if cached.fingerprint == stream_cache_fingerprint(handle)? {
                    return Ok(cached.parameters_removed);
                }
            }

            // QPDFWriter::willFilterStream retains the produced buffer for the
            // later unparseObject emission (`QPDFWriter.cc:1239-1314,1539-1560`).
            // Cache every indirect source stream, not only data-modified ones,
            // so deferred providers are invoked once across planning and emit.
            let (dict, data, refiltered, parameters_removed) =
                body::canonical_stream_output_with_status(handle, options, true, false)?;
            let fingerprint = stream_cache_fingerprint(handle)?;
            cached_stream_outputs.borrow_mut().insert(
                source,
                CachedStreamOutput {
                    dict,
                    data,
                    refiltered,
                    parameters_removed,
                    fingerprint,
                },
            );
            Ok(parameters_removed)
        };

        let placement = match options.object_streams {
            ObjectStreamMode::Disable => {
                let renumber = CanonicalCatalogFirstRenumber::build_qpdf_with_stream_policy(
                    pdf,
                    true,
                    options.preserve_unreferenced_objects,
                    &explicitly_removed,
                    Some(&stream_parameters_removed),
                )?;
                let mut placement = build_sources_from_pairs(renumber.pairs());
                placement.removed_refs = explicitly_removed;
                placement
            }
            ObjectStreamMode::Preserve => {
                if !source_had_compressed_objects {
                    let renumber = CanonicalCatalogFirstRenumber::build_qpdf_with_stream_policy(
                        pdf,
                        true,
                        options.preserve_unreferenced_objects,
                        &explicitly_removed,
                        Some(&stream_parameters_removed),
                    )?; // cov:ignore: malformed canonical source graphs are rejected before placement
                    let mut placement = build_sources_from_pairs(renumber.pairs());
                    placement.removed_refs = explicitly_removed;
                    placement
                } else {
                    let mut packing =
                        object_streams::plan_qpdf_preserve_object_streams_with_unreferenced(
                            pdf,
                            options.preserve_unreferenced_objects,
                        )?; // cov:ignore: malformed source graph is rejected by the preserve planner
                    packing
                        .removed_refs
                        .extend(explicitly_removed.iter().copied());
                    for group in &mut packing.groups {
                        group
                            .members_mut()
                            .retain(|member| !packing.removed_refs.contains(member));
                    }
                    packing.groups.retain(|group| !group.members().is_empty());
                    retain_reachable_object_stream_members(
                        pdf,
                        &mut packing.groups,
                        &packing.removed_refs,
                        options.preserve_unreferenced_objects,
                        Some(&stream_parameters_removed),
                    )?; // cov:ignore: LLVM maps this covered preserve-group call terminator to a zero-count continuation region
                    let groups = &packing.groups;
                    let removed = &packing.removed_refs;
                    let renumber = renumber_plain(
                        pdf,
                        groups,
                        removed,
                        options.preserve_unreferenced_objects,
                        Some(&stream_parameters_removed),
                    )?; // cov:ignore: planner groups are produced by the same validated source walk
                    build_container_aware(renumber, packing.groups, packing.removed_refs)?
                }
            }
            ObjectStreamMode::Generate => {
                let mut compressible = object_streams::compressible_objgens_qpdf_plan(pdf)?;
                compressible
                    .removed_refs
                    .extend(explicitly_removed.iter().copied());
                compressible
                    .eligible
                    .retain(|member| !compressible.removed_refs.contains(member));
                let groups = object_streams::even_split_into_streams(&compressible.eligible);
                let mut renumber_groups: Vec<ObjectStreamGroup> = groups
                    .iter()
                    .cloned()
                    .map(|members| ObjectStreamGroup::Synthetic { members })
                    .collect();
                let removed = &compressible.removed_refs;
                // qpdf's Generate pass only puts its reachable compressible set
                // into synthetic ObjStms (`QPDFWriter.cc:1970-2007`), while
                // `enqueueObjectsStandard` separately seeds every source object
                // when preserve-unreferenced is enabled (`QPDFWriter.cc:2907-2914`).
                // Keep that distinction: preserved orphans receive plain slots
                // instead of being silently dropped from the generated rewrite.
                // cov:ignore-start: LLVM attributes this covered Generate-group call to its opening line; the writer contract test exercises the complete call
                retain_reachable_object_stream_members(
                    pdf,
                    &mut renumber_groups,
                    removed,
                    options.preserve_unreferenced_objects,
                    Some(&stream_parameters_removed),
                )?;
                // cov:ignore-end
                let renumber = renumber_plain(
                    pdf,
                    &renumber_groups,
                    removed,
                    options.preserve_unreferenced_objects,
                    Some(&stream_parameters_removed),
                )?; // cov:ignore: llvm-cov assigns no executable counter to this multiline-call terminator; the Generate preserve path is exercised by the writer contract test.
                build_container_aware(renumber, renumber_groups, compressible.removed_refs)?
            }
        };

        let root = source_root_ref.and_then(|source| placement.old_to_new.get(&source).copied());
        if source_root_ref.is_some() && root.is_none() {
            return Err(crate::Error::Unsupported(
                "plain writer plan: /Root absent from renumber map".to_string(),
            ));
        }
        let direct_root = source_root_handle;
        let has_object_stream = placement
            .objects
            .iter()
            .any(|object| matches!(object, PlannedIndirectObject::ObjectStream { .. }));

        let form = if has_object_stream {
            XrefForm::Stream
        } else {
            XrefForm::Table
        };
        let mut version = crate::writer::effective_pdf_version(
            pdf.version(),
            options,
            false,
            has_object_stream || form == XrefForm::Stream,
        )
        .to_string();
        // If a source version cannot be numerically compared, the canonical
        // writer keeps its raw value. PDF 1.5 introduced xref streams, so
        // repair the header to that floor exactly as the full-rewrite path
        // does whenever this plan actually uses a stream form.
        if form == XrefForm::Stream
            && parse_qpdf_writer_version(&version)
                .is_none_or(|current| current < QpdfVersionParts::new(1, 5))
        {
            version = "1.5".to_string();
        }

        let source_id0 = live_source_id0(pdf)?;
        let deterministic_id = crate::writer::uses_deterministic_id(options);
        let generated_id = if deterministic_id || options.copy_encryption.is_some() {
            None
        } else {
            Some(crate::writer::generate_id_handle(
                source_id0.as_deref(),
                options.static_id,
            ))
        };
        let max_output = placement
            .objects
            .iter()
            .map(|object| match object {
                PlannedIndirectObject::Source { output, .. }
                | PlannedIndirectObject::ObjectStream { output, .. } => output.number,
            })
            .max()
            .unwrap_or(0);
        let trailer_size = usize::try_from(max_output)
            .ok()
            .and_then(|size| size.checked_add(usize::from(form == XrefForm::Stream) + 1))
            .ok_or_else(|| {
                // cov:ignore-start: ObjectRef numbers are u32 and fit usize on supported targets
                // ObjectRef numbers are u32, so this overflow arm is unreachable on
                // the supported 64-bit targets.
                crate::Error::Unsupported("plain writer trailer /Size overflows usize".into())
            })?
            // cov:ignore-end
            ;
        let trailer_handle = crate::writer::build_writer_trailer_handle(
            pdf,
            trailer_size,
            root,
            direct_root.as_ref(),
            options,
            None,
            deterministic_id,
            generated_id.as_ref(),
        )?; // cov:ignore: LLVM attributes this validated trailer-call continuation to the call setup
        let id = if deterministic_id {
            IdPlan::Deterministic {
                source_id0,
                info_suffix: crate::writer::deterministic_id_info_suffix(pdf),
            }
        } else {
            IdPlan::Materialized {
                value: materialized_id_handle(&trailer_handle.try_get_key(b"/ID")?)?,
            }
        };
        let encrypt = trailer_handle.try_get_key(b"/Encrypt")?.object_ref();
        let direct_root_bytes = if root.is_none() {
            let root_handle = trailer_handle.try_get_key(b"/Root")?;
            let map = |object_ref| {
                placement
                    .old_to_new
                    .get(&object_ref)
                    .copied()
                    .ok_or_else(|| {
                        // cov:ignore-start: the direct Catalog is collected
                        // by the same traversal that builds this map, so a
                        // live reference cannot be absent at emission.
                        crate::Error::Unsupported(format!(
                            "plain writer: direct /Root reference {} {} R absent from renumber map",
                            object_ref.number, object_ref.generation
                        ))
                        // cov:ignore-end
                    }) // cov:ignore: the direct-root reference map is exercised; LLVM places the successful closure-exit counter on this continuation line.
            };
            let mut bytes = Vec::new();
            root_handle.write_object_with_ref_map_and_removed(
                &mut bytes,
                &map,
                &placement.removed_refs,
            )?; // cov:ignore: the direct Catalog serializer is exercised; LLVM maps this call terminator to a zero-count continuation region.
            Some(bytes)
        } else {
            None
        };
        let structural_filtered = matches!(
            crate::writer::effective_stream_policy(options),
            Some(CompressStreams::Yes)
        );
        let trailer = TrailerPlan {
            form,
            canonical_entries: canonical_trailer_entries(
                pdf,
                &placement.old_to_new,
                &placement.removed_refs,
            )?, // cov:ignore: malformed live trailer graphs are rejected at the helper boundary
            root,
            direct_root: direct_root_bytes,
            id,
            encrypt,
            structural_filtered,
            qdf: options.qdf,
        };

        let plan = Self {
            version,
            objects: placement.objects,
            root,
            direct_root,
            old_to_new: placement.old_to_new,
            removed_refs: placement.removed_refs,
            cached_stream_outputs: cached_stream_outputs.into_inner(),
            trailer,
        };
        plan.validate()?;
        Ok(plan)
    }

    pub(crate) fn validate(&self) -> crate::Result<()> {
        let mut outputs = BTreeSet::new();
        let mut sources = BTreeSet::new();
        let mut source_backed_containers = BTreeSet::new();
        let mut has_object_stream = false;

        for object in &self.objects {
            match object {
                PlannedIndirectObject::Source { source, output } => {
                    require_not_removed(&self.removed_refs, *source, "source")?;
                    require_unique_output(&mut outputs, *output)?;
                    require_unique_source(&mut sources, *source)?;
                    require_matching_mapping(&self.old_to_new, *source, *output)?;
                }
                PlannedIndirectObject::ObjectStream {
                    origin,
                    output,
                    members,
                } => {
                    has_object_stream = true;
                    require_unique_output(&mut outputs, *output)?;
                    if let PlannedObjectStreamOrigin::SourceBacked(source) = origin {
                        // A removed source container still owns the preserved
                        // membership and output identity. qpdf reconstructs it
                        // from a null placeholder while treating ordinary
                        // references to the removed source as null.
                        source_backed_containers.insert(*source);
                        require_unique_source(&mut sources, *source)?;
                        require_matching_mapping(&self.old_to_new, *source, *output)?;
                    }
                    for member in members {
                        require_not_removed(&self.removed_refs, member.source, "ObjStm member")?;
                        if member.output.generation != 0 {
                            return Err(crate::Error::Unsupported(format!(
                                "plain writer plan: ObjStm output member {} {} R must have generation 0",
                                member.output.number, member.output.generation
                            )));
                        }
                        require_unique_source(&mut sources, member.source)?;
                        require_matching_mapping(&self.old_to_new, member.source, member.output)?;
                        if !outputs.insert(member.output.number) {
                            return Err(crate::Error::Unsupported(format!(
                                "plain writer plan: output object {} has multiple placements",
                                member.output.number
                            )));
                        }
                    }
                }
            }
        }

        if let Some(removed) = self.removed_refs.iter().find(|removed| {
            self.old_to_new.contains_key(removed) && !source_backed_containers.contains(removed)
        }) {
            return Err(crate::Error::Unsupported(format!(
                "plain writer plan: removed source {} {} R remains in old-to-new map",
                removed.number, removed.generation
            )));
        }

        if let Some(extra) = self
            .old_to_new
            .keys()
            .find(|source| !sources.contains(source))
        {
            return Err(crate::Error::Unsupported(format!(
                "plain writer plan: source {} {} R has no placement",
                extra.number, extra.generation
            )));
        }

        match (
            self.root,
            self.direct_root.as_ref(),
            self.trailer.root,
            self.trailer.direct_root.as_ref(),
        ) {
            (Some(root), None, Some(trailer_root), None) => {
                if !self.old_to_new.values().any(|&output| output == root) {
                    return Err(crate::Error::Unsupported(format!(
                        "plain writer plan: root {} {} R is absent from old-to-new map",
                        root.number, root.generation
                    )));
                }
                if trailer_root != root {
                    return Err(crate::Error::Unsupported(format!(
                        "plain writer plan: trailer root {} {} R differs from plan root {} {} R",
                        trailer_root.number, trailer_root.generation, root.number, root.generation
                    )));
                }
            }
            (None, Some(_), None, Some(_)) => {}
            _ => {
                return Err(crate::Error::Unsupported(
                    "plain writer plan: Catalog root form is inconsistent".to_string(),
                ));
            }
        }

        if let Some(&max_output) = outputs.last() {
            for number in 1..=max_output {
                if !outputs.contains(&number) {
                    return Err(crate::Error::Unsupported(format!(
                        "plain writer plan: output object {number} has no placement"
                    )));
                }
            }
        } // cov:ignore: a valid plan always places the mapped root, so outputs is nonempty

        if has_object_stream || self.trailer.form == XrefForm::Stream {
            let version = parse_qpdf_writer_version(&self.version).ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "plain writer plan: invalid PDF version {}",
                    self.version
                ))
            })?;
            if version < QpdfVersionParts::new(1, 5) {
                return Err(crate::Error::Unsupported(format!(
                    "plain writer plan: PDF {} cannot contain object or xref streams",
                    self.version
                )));
            }
        }

        Ok(())
    }

    pub(crate) fn new_for_original(&self, source: ObjectRef) -> Option<ObjectRef> {
        self.old_to_new.get(&source).copied()
    }
}

struct PlacementPlan {
    objects: Vec<PlannedIndirectObject>,
    old_to_new: HashMap<ObjectRef, ObjectRef>,
    removed_refs: BTreeSet<ObjectRef>,
}

fn live_source_id0<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<Option<Vec<u8>>> {
    let id = pdf.trailer().try_get_key(b"/ID")?;
    let Some(values) = id.try_as_array()? else {
        return Ok(None);
    };
    let Some(first) = values.first() else {
        return Ok(None);
    };
    first.try_dereference()?;
    Ok(first.as_string().filter(|bytes| !bytes.is_empty()))
}

/// Snapshot the writer-owned trailer entries from qpdf's live canonical
/// trailer handle, preserving the handle graph until each value is emitted.
///
/// qpdf's `getTrimmedTrailer`/`writeTrailer` path works from the live trailer,
/// while `enqueueObjectsStandard` applies `getKeys()` null visibility before
/// it seeds the object queue (`QPDFWriter.cc:1163-1192, 2009-2029, 2916-2924`).
/// The legacy `Pdf::trailer()` dictionary is a construction-time snapshot and
/// cannot represent a later `trailer()` mutation. Direct dictionaries
/// and arrays are serialized through the canonical writer boundary so nested
/// dictionary nulls are omitted and array null positions remain present.
pub(crate) fn canonical_trailer_entries(
    pdf: &mut Pdf<impl Read + Seek>,
    map: &HashMap<ObjectRef, ObjectRef>,
    removed_refs: &BTreeSet<ObjectRef>,
) -> crate::Result<Vec<(Vec<u8>, Vec<u8>)>> {
    canonical_trailer_entries_with_visibility(pdf, map, removed_refs, true)
}

/// Snapshot trailer entries while preserving qpdf's mode-independent
/// top-level null visibility. `QPDFWriter::getTrimmedTrailer` applies the
/// `getKeys()` rule before `writeTrailer` for plain, QDF, and encrypted output
/// alike (`QPDFWriter.cc:1163-1192, 2009-2029, 2917-2926`).
pub(crate) fn canonical_trailer_entries_with_visibility(
    pdf: &mut Pdf<impl Read + Seek>,
    map: &HashMap<ObjectRef, ObjectRef>,
    removed_refs: &BTreeSet<ObjectRef>,
    suppress_null_values: bool,
) -> crate::Result<Vec<(Vec<u8>, Vec<u8>)>> {
    let trailer = pdf.trailer();
    let entries = trailer.try_as_dictionary()?.unwrap_or_default();
    let mut serialized = Vec::with_capacity(entries.len());
    for (key, value) in entries {
        if is_writer_owned_trailer_key(&key) {
            continue;
        }
        if value
            .object_ref()
            .is_some_and(|object_ref| object_ref.number == 0 || removed_refs.contains(&object_ref))
            || (suppress_null_values && value.try_is_null()?)
        {
            continue;
        }

        let mut value_bytes = Vec::new();
        if let Some(object_ref) = value.object_ref() {
            let mapped = map.get(&object_ref).copied().ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "plain writer: trailer /{} reference {object_ref} absent from renumber map",
                    String::from_utf8_lossy(key.strip_prefix(b"/").unwrap_or(&key))
                ))
            })?;
            value_bytes.extend_from_slice(mapped.to_string().as_bytes());
        } else {
            let map_ref = |object_ref: ObjectRef| {
                map.get(&object_ref).copied().ok_or_else(|| {
                    crate::Error::Unsupported(format!(
                        "plain writer: trailer nested reference {object_ref} absent from renumber map"
                    ))
                })
            };
            value.write_object_with_ref_map_and_removed(
                &mut value_bytes,
                &map_ref,
                removed_refs,
            )?;
        }

        // Keep qpdf's decoded key for the writer's raw-name sort. The xref
        // emitter escapes it only after sorting, since escaping can change
        // the bytewise order (e.g. `/ A` versus `/!A`).
        serialized.push((key, value_bytes));
    }
    Ok(serialized)
}

fn is_writer_owned_trailer_key(key: &[u8]) -> bool {
    matches!(
        key,
        b"/ID"
            | b"/Encrypt"
            | b"/Prev"
            | b"/Root"
            | b"/Size"
            | b"/Type"
            | b"/F"
            | b"/FFilter"
            | b"/FDecodeParms"
            | b"/W"
            | b"/Index"
            | b"/Length"
            | b"/Filter"
            | b"/DecodeParms"
            | b"/XRefStm"
    )
}

fn build_sources_from_pairs(
    pairs: impl IntoIterator<Item = (ObjectRef, ObjectRef)>,
) -> PlacementPlan {
    let pairs: Vec<(ObjectRef, ObjectRef)> = pairs.into_iter().collect();
    let old_to_new = pairs
        .iter()
        .map(|&(output, source)| (source, output))
        .collect();
    let objects = pairs
        .into_iter()
        .map(|(output, source)| PlannedIndirectObject::Source { source, output })
        .collect();
    PlacementPlan {
        objects,
        old_to_new,
        removed_refs: BTreeSet::new(),
    }
}

fn renumber_plain<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    groups: &[ObjectStreamGroup],
    removed_refs: &BTreeSet<ObjectRef>,
    preserve_unreferenced_objects: bool,
    stream_parameters_removed: StreamParametersRemoved<'_>,
) -> crate::Result<ObjectStreamRenumber> {
    ObjectStreamRenumber::build_with_stream_policy(
        pdf,
        groups,
        true,
        removed_refs,
        preserve_unreferenced_objects,
        stream_parameters_removed,
    )
}

fn retain_reachable_object_stream_members<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    groups: &mut Vec<ObjectStreamGroup>,
    removed_refs: &BTreeSet<ObjectRef>,
    preserve_unreferenced_objects: bool,
    stream_parameters_removed: StreamParametersRemoved<'_>,
) -> crate::Result<()> {
    if groups.is_empty() {
        return Ok(());
    }
    // cov:ignore-start: LLVM attributes this covered reachability call to an argument line; the preserve and Generate writer tests exercise the complete call
    let reachable = CanonicalCatalogFirstRenumber::build_qpdf_with_stream_policy(
        pdf,
        true,
        preserve_unreferenced_objects,
        removed_refs,
        stream_parameters_removed,
    )?;
    // cov:ignore-end
    for group in groups.iter_mut() {
        group
            .members_mut()
            .retain(|member| reachable.new_for_original(*member).is_some());
    }
    groups.retain(|group| !group.members().is_empty());
    Ok(())
}

fn build_container_aware(
    renumber: ObjectStreamRenumber,
    groups: Vec<ObjectStreamGroup>,
    removed_refs: BTreeSet<ObjectRef>,
) -> crate::Result<PlacementPlan> {
    let old_to_new: HashMap<ObjectRef, ObjectRef> = renumber
        .pairs()
        .map(|(output, source)| (source, output))
        .collect();
    let member_sources: BTreeSet<ObjectRef> = groups
        .iter()
        .flat_map(ObjectStreamGroup::members)
        .copied()
        .collect();
    let container_sources: BTreeSet<ObjectRef> = groups
        .iter()
        .filter_map(|group| match group {
            ObjectStreamGroup::SourceBacked { source, .. } => Some(*source),
            ObjectStreamGroup::Synthetic { .. } => None,
        })
        .collect();
    let mut objects: Vec<PlannedIndirectObject> = old_to_new
        .iter()
        .filter(|(source, _)| {
            !member_sources.contains(source) && !container_sources.contains(source)
        })
        .map(|(&source, &output)| PlannedIndirectObject::Source { source, output })
        .collect();

    for (group_index, group) in groups.iter().enumerate() {
        // cov:ignore-start: ObjectStreamRenumber assigns a container for every supplied group
        let container = renumber.container_number(group_index).ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "plain writer plan: ObjStm group {group_index} was never reached"
            ))
        })?;
        // cov:ignore-end
        let mut members: Vec<PlannedMember> = group
            .members()
            .iter()
            .map(|&source| {
                old_to_new
                    .get(&source)
                    .copied()
                    .map(|output| PlannedMember { source, output })
                    // cov:ignore-start: groups are the same inputs used to build old_to_new
                    .ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "plain writer plan: ObjStm member {} {} R absent from renumber map",
                            source.number, source.generation
                        ))
                    })
                // cov:ignore-end
            })
            .collect::<crate::Result<Vec<_>>>()?;
        members.sort_unstable_by_key(|member| member.output.number);
        let origin = match group {
            ObjectStreamGroup::SourceBacked { source, .. } => {
                PlannedObjectStreamOrigin::SourceBacked(*source)
            }
            ObjectStreamGroup::Synthetic { .. } => PlannedObjectStreamOrigin::Synthetic,
        };
        objects.push(PlannedIndirectObject::ObjectStream {
            origin,
            output: ObjectRef::new(container, 0),
            members,
        });
    }

    objects.sort_unstable_by_key(|object| match object {
        PlannedIndirectObject::Source { output, .. }
        | PlannedIndirectObject::ObjectStream { output, .. } => output.number,
    });

    Ok(PlacementPlan {
        objects,
        old_to_new,
        removed_refs,
    })
}

pub(crate) fn source_has_compressed_entries<R: Read + Seek>(pdf: &Pdf<R>) -> bool {
    pdf.source_xref_entries()
        .values()
        .any(|offset| matches!(offset, XrefEntry::Compressed { .. }))
}

impl NewNumberLookup for PlainWritePlan {
    fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef> {
        PlainWritePlan::new_for_original(self, original)
    }
}

fn require_unique_output(outputs: &mut BTreeSet<u32>, output: ObjectRef) -> crate::Result<()> {
    if outputs.insert(output.number) {
        Ok(())
    } else {
        Err(crate::Error::Unsupported(format!(
            "plain writer plan: output object {} has multiple placements",
            output.number
        )))
    }
}

fn require_unique_source(
    sources: &mut BTreeSet<ObjectRef>,
    source: ObjectRef,
) -> crate::Result<()> {
    if sources.insert(source) {
        Ok(())
    } else {
        Err(crate::Error::Unsupported(format!(
            "plain writer plan: source {} {} R has multiple placements",
            source.number, source.generation
        )))
    }
}

fn require_not_removed(
    removed_refs: &BTreeSet<ObjectRef>,
    source: ObjectRef,
    role: &str,
) -> crate::Result<()> {
    if removed_refs.contains(&source) {
        Err(crate::Error::Unsupported(format!(
            "plain writer plan: removed source {} {} R has {role} placement",
            source.number, source.generation
        )))
    } else {
        Ok(())
    }
}

fn require_matching_mapping(
    old_to_new: &HashMap<ObjectRef, ObjectRef>,
    source: ObjectRef,
    output: ObjectRef,
) -> crate::Result<()> {
    match old_to_new.get(&source) {
        Some(mapped) if *mapped == output => Ok(()),
        Some(mapped) => Err(crate::Error::Unsupported(format!(
            "plain writer plan: source {} {} R maps to {} {} R but is placed at {} {} R",
            source.number,
            source.generation,
            mapped.number,
            mapped.generation,
            output.number,
            output.generation
        ))),
        None => Err(crate::Error::Unsupported(format!(
            "plain writer plan: source {} {} R is absent from old-to-new map",
            source.number, source.generation
        ))),
    }
}

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

    use crate::object_handle::ObjectValue;
    use crate::writer::object_streams::ObjectStreamMode;
    use crate::writer::plain::xref::{append_xref_and_trailer, BodyLayout, IdPlan, TrailerPlan};
    use crate::writer::WriterOptions;
    use crate::{NewlineBeforeEndstream, ObjectHandle, ObjectRef, Pdf, PdfWriter, XrefForm};
    use std::cell::RefCell;
    use std::collections::BTreeMap;
    use std::rc::Rc;

    fn fixture_path(fixture: &str) -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(fixture)
    }

    fn write_options(mode: ObjectStreamMode) -> WriterOptions {
        WriterOptions {
            object_streams: mode,
            static_id: true,
            newline_before_endstream: NewlineBeforeEndstream::Never,
            ..WriterOptions::default()
        }
    }

    fn build(fixture: &str, mode: ObjectStreamMode) -> PlainWritePlan {
        let path = fixture_path(fixture);
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let options = write_options(mode);
        PlainWritePlan::build(&mut pdf, &options).unwrap()
    }

    fn direct_stream_source() -> Vec<u8> {
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let objects: &[(u32, &[u8])] = &[
            (1, b"<< /Type /Catalog /Pages 2 0 R >>"),
            (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
            (
                3,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>",
            ),
            (4, b"<< /Length 3 >>\nstream\nq Q\nendstream"),
        ];
        let mut offsets = BTreeMap::new();
        for (number, body) in objects {
            offsets.insert(*number, bytes.len() as u64);
            bytes.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
            bytes.extend_from_slice(body);
            bytes.extend_from_slice(b"\nendobj\n");
        }
        let xref = bytes.len() as u64;
        let size = 5;
        bytes.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
        for number in 1..size {
            bytes.extend_from_slice(format!("{:010} 00000 n \n", offsets[&number]).as_bytes());
        }
        bytes.extend_from_slice(
            format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n")
                .as_bytes(),
        );
        bytes
    }

    #[test]
    fn plan_handles_direct_streams_without_a_source_cache_identity() {
        struct PassThroughTokenFilter;

        // cov:ignore-start: the direct-stream planning branch intentionally does not pipe data; this filter only flips qpdf's isDataModified bit.
        impl crate::token_filter::TokenFilter for PassThroughTokenFilter {
            fn handle_token(
                &mut self,
                token: &crate::tokenizer::Token,
                output: &mut crate::token_filter::TokenFilterOutput<'_>,
            ) -> crate::pipeline::PipelineResult<()> {
                output.write_token(token)
            }
        }
        // cov:ignore-end

        for modified in [false, true] {
            let mut pdf = Pdf::open_mem_owned(direct_stream_source()).unwrap();
            let page = pdf.get_object_handle(ObjectRef::new(3, 0));
            pdf.resolve(&page).unwrap();
            let direct_stream = ObjectHandle::stream(
                ObjectHandle::dictionary(vec![(b"Length".to_vec(), ObjectHandle::integer(3))]),
                Rc::new(b"q Q".to_vec()),
            );
            page.replace_key(b"Contents", direct_stream).unwrap();
            let contents = page.get_key(b"Contents");
            if modified {
                contents
                    .add_token_filter(Rc::new(RefCell::new(PassThroughTokenFilter)))
                    .unwrap();
            }
            pdf.mark_object_handle_dirty(&page).unwrap();

            let plan =
                PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Disable)).unwrap();
            assert_eq!(plan.root, Some(ObjectRef::new(1, 0)));
        }
    }

    fn source(source: u32, output: u32) -> PlannedIndirectObject {
        PlannedIndirectObject::Source {
            source: ObjectRef::new(source, 0),
            output: ObjectRef::new(output, 0),
        }
    }

    fn plan_for_test(objects: Vec<PlannedIndirectObject>) -> PlainWritePlan {
        let root_source = ObjectRef::new(1, 0);
        let root_output = ObjectRef::new(1, 0);
        PlainWritePlan {
            version: "1.5".to_string(),
            objects,
            root: Some(root_output),
            direct_root: None,
            old_to_new: HashMap::from([(root_source, root_output)]),
            removed_refs: BTreeSet::new(),
            cached_stream_outputs: HashMap::new(),
            trailer: TrailerPlan {
                form: XrefForm::Table,
                canonical_entries: Vec::new(),
                root: Some(root_output),
                direct_root: None,
                id: IdPlan::Materialized { value: None },
                encrypt: None,
                structural_filtered: false,
                qdf: false,
            },
        }
    }

    #[test]
    fn validation_rejects_duplicate_output_numbers() {
        let mut plan = plan_for_test(vec![source(1, 1), source(2, 1)]);
        plan.root = Some(ObjectRef::new(1, 0));
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("output object 1")));
    }

    #[test]
    fn validation_rejects_source_and_source_backed_container_for_same_source() {
        let container_source = ObjectRef::new(2, 0);
        let mut plan = plan_for_test(vec![
            source(1, 1),
            source(2, 3),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::SourceBacked(container_source),
                output: ObjectRef::new(2, 0),
                members: Vec::new(),
            },
        ]);
        plan.old_to_new
            .insert(container_source, ObjectRef::new(3, 0));
        plan.trailer.form = XrefForm::Stream;

        let error = plan.validate().unwrap_err();

        assert!(matches!(error, crate::Error::Unsupported(message)
            if message.contains("source 2 0 R has multiple placements")));
    }

    #[test]
    fn validation_rejects_objstm_output_with_nonzero_generation() {
        let member = PlannedMember {
            source: ObjectRef::new(7, 1),
            output: ObjectRef::new(2, 1),
        };
        let plan = plan_for_test(vec![PlannedIndirectObject::ObjectStream {
            origin: PlannedObjectStreamOrigin::Synthetic,
            output: ObjectRef::new(1, 0),
            members: vec![member],
        }]);
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("output member 2 1 R")));
    }

    #[test]
    fn validation_rejects_objstm_member_colliding_with_plain_output() {
        let member = PlannedMember {
            source: ObjectRef::new(7, 0),
            output: ObjectRef::new(1, 0),
        };
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::Synthetic,
                output: ObjectRef::new(3, 0),
                members: vec![member],
            },
        ]);
        plan.old_to_new
            .insert(ObjectRef::new(7, 0), ObjectRef::new(1, 0));

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("output object 1 has multiple placements")));
    }

    #[test]
    fn validation_accepts_nonzero_source_generation_for_zero_generation_output() {
        let member = PlannedMember {
            source: ObjectRef::new(7, 1),
            output: ObjectRef::new(2, 0),
        };
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::Synthetic,
                output: ObjectRef::new(3, 0),
                members: vec![member],
            },
        ]);
        plan.old_to_new
            .insert(ObjectRef::new(7, 1), ObjectRef::new(2, 0));
        plan.trailer.form = XrefForm::Stream;

        plan.validate().unwrap();
    }

    #[test]
    fn disable_xref_stream_source_keeps_parseable_source_version_and_uses_table() {
        let mut bytes = std::fs::read(fixture_path("three-page-objstm.pdf")).unwrap();
        bytes[7] = b'4';
        let mut pdf = Pdf::open_mem_owned(bytes).unwrap();

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Disable)).unwrap();

        assert_eq!(plan.version, "1.4");
        assert_eq!(plan.trailer.form, XrefForm::Table);
        assert!(plan
            .objects
            .iter()
            .all(|object| matches!(object, PlannedIndirectObject::Source { .. })));
    }

    #[test]
    fn disable_xref_stream_source_does_not_apply_stream_version_repair() {
        let mut bytes = std::fs::read(fixture_path("three-page-objstm.pdf")).unwrap();
        bytes[5] = b'x';
        bytes[7] = b'y';
        let mut pdf = Pdf::open_mem_owned_with_options(
            bytes,
            crate::PdfOpenOptions {
                repair: false,
                ..crate::PdfOpenOptions::default()
            },
        )
        .unwrap();
        assert_eq!(pdf.version(), "x.y");

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Disable)).unwrap();

        assert_eq!(plan.version, "x.y");
        assert_eq!(plan.trailer.form, XrefForm::Table);
        plan.validate().unwrap();
    }

    #[test]
    fn canonical_trailer_entries_follow_qpdf_null_visibility() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("three-page.pdf")).unwrap(),
        ))
        .unwrap();
        let trailer = pdf.trailer();
        trailer.remove_key(b"/Info");
        let null_ref = ObjectRef::new(100, 0);
        let null_handle = pdf.get_object_handle(null_ref);
        null_handle.set_resolved(ObjectValue::Null);
        trailer.replace_key(b"/Null", null_handle).unwrap();
        let mut map = HashMap::new();
        map.insert(null_ref, ObjectRef::new(200, 0));

        let suppressed =
            canonical_trailer_entries_with_visibility(&mut pdf, &map, &BTreeSet::new(), true)
                .unwrap();
        assert!(!suppressed.iter().any(|(key, _)| key == b"/Null"));

        let visible =
            canonical_trailer_entries_with_visibility(&mut pdf, &map, &BTreeSet::new(), false)
                .unwrap();
        assert_eq!(
            visible
                .iter()
                .find(|(key, _)| key == b"/Null")
                .map(|(_, value)| value.as_slice()),
            Some(b"200 0 R".as_slice())
        );
    }

    #[test]
    fn generated_xref_stream_uses_live_trailer_entries() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("three-page.pdf")).unwrap(),
        ))
        .unwrap();
        pdf.trailer()
            .replace_key(
                b"/Added",
                ObjectHandle::dictionary(vec![(b"Value".to_vec(), ObjectHandle::integer(7))]),
            )
            .unwrap();

        let output = {
            let mut writer = PdfWriter::new(&mut pdf);
            writer.set_object_stream_mode(ObjectStreamMode::Generate);
            writer.set_output_memory().unwrap();
            writer.write().unwrap();
            writer.get_buffer().unwrap()
        };
        let text = String::from_utf8_lossy(&output);

        assert!(
            text.contains("/Added << /Value 7 >>"),
            "generated xref stream must serialize the live trailer handle: {text}"
        );
    }

    #[test]
    fn live_source_id0_reads_existing_trailer_id() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("one-page.pdf")).unwrap(),
        ))
        .unwrap();

        assert!(pdf.trailer().try_has_key(b"/ID").unwrap());
        let id0 = live_source_id0(&mut pdf).unwrap();
        assert!(
            id0.is_some(),
            "live trailer /ID[0] must be visible to the planner"
        );
    }

    #[test]
    fn live_source_id0_reads_mutated_trailer_handle_id() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("one-page.pdf")).unwrap(),
        ))
        .unwrap();
        pdf.trailer()
            .replace_key(
                b"/ID",
                ObjectHandle::array(vec![
                    ObjectHandle::string(b"mutated-permanent".to_vec()),
                    ObjectHandle::string(b"mutated-changing".to_vec()),
                ]),
            )
            .unwrap();

        assert_eq!(
            live_source_id0(&mut pdf).unwrap(),
            Some(b"mutated-permanent".to_vec())
        );
    }

    #[test]
    fn live_source_id0_returns_none_for_empty_id_array() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("one-page.pdf")).unwrap(),
        ))
        .unwrap();
        pdf.trailer()
            .replace_key(b"/ID", ObjectHandle::array(Vec::new()))
            .unwrap();

        assert_eq!(live_source_id0(&mut pdf).unwrap(), None);
    }

    #[test]
    fn canonical_deterministic_id_uses_the_live_info_entry() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("no-stream-one-page.pdf")).unwrap(),
        ))
        .unwrap();
        pdf.trailer()
            .replace_key(
                b"/Info",
                ObjectHandle::dictionary(vec![(
                    b"Title".to_vec(),
                    ObjectHandle::string(b"live-info-replacement-768".to_vec()),
                )]),
            )
            .unwrap();
        let mut options = write_options(ObjectStreamMode::Disable);
        options.static_id = false;
        options.deterministic_id = true;

        let plan = PlainWritePlan::build(&mut pdf, &options).unwrap();

        let IdPlan::Deterministic { info_suffix, .. } = plan.trailer.id else {
            panic!("deterministic ID plan expected"); // cov:ignore: deterministic_id=true guarantees this plan variant
        };
        assert_eq!(info_suffix, b" live-info-replacement-768");
    }

    #[test]
    fn canonical_trailer_sorts_decoded_names_before_escaping_them() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("no-stream-one-page.pdf")).unwrap(),
        ))
        .unwrap();
        let trailer = pdf.trailer();
        trailer.remove_key(b"/Info");
        trailer
            .replace_key(b"/ A", ObjectHandle::integer(1))
            .unwrap();
        trailer
            .replace_key(b"/!A", ObjectHandle::integer(2))
            .unwrap();

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Disable)).unwrap();
        let mut bytes = b"BODY".to_vec();
        let mut layout = BodyLayout::default();
        layout.uncompressed.insert(
            plan.root
                .expect("test plan must have an indirect root")
                .number,
            (
                plan.root
                    .expect("test plan must have an indirect root")
                    .generation,
                0,
            ),
        );
        append_xref_and_trailer(&mut bytes, &layout, &plan.trailer).unwrap();
        let text = String::from_utf8_lossy(&bytes);
        let escaped_space = text.find("/#20A").expect("escaped space-name key");
        let exclamation = text.find("/!A").expect("exclamation-name key");

        assert!(
            escaped_space < exclamation,
            "decoded key order must precede PDF name escaping: {text}"
        );
    }

    #[test]
    fn canonical_trailer_entries_reject_an_unmapped_indirect_value() {
        let mut pdf = Pdf::open(std::io::BufReader::new(
            std::fs::File::open(fixture_path("three-page.pdf")).unwrap(),
        ))
        .unwrap();

        let error =
            canonical_trailer_entries(&mut pdf, &HashMap::new(), &BTreeSet::new()).unwrap_err();

        assert!(matches!(error, crate::Error::Unsupported(message)
            if message.contains("trailer /Info reference")
                && message.contains("absent from renumber map")));
    }

    #[test]
    fn validation_rejects_source_missing_from_old_to_new() {
        let plan = plan_for_test(vec![source(1, 1), source(2, 2)]);
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("source 2 0 R is absent from old-to-new map")));
    }

    #[test]
    fn validation_rejects_source_mapping_that_differs_from_placement() {
        let mut plan = plan_for_test(vec![source(1, 1), source(2, 2)]);
        plan.old_to_new
            .insert(ObjectRef::new(2, 0), ObjectRef::new(3, 0));
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("source 2 0 R maps to 3 0 R but is placed at 2 0 R")));
    }

    #[test]
    fn validation_rejects_member_mapping_that_differs_from_placement() {
        let member = PlannedMember {
            source: ObjectRef::new(7, 0),
            output: ObjectRef::new(2, 0),
        };
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::Synthetic,
                output: ObjectRef::new(3, 0),
                members: vec![member],
            },
        ]);
        plan.old_to_new
            .insert(ObjectRef::new(7, 0), ObjectRef::new(4, 0));
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("source 7 0 R maps to 4 0 R but is placed at 2 0 R")));
    }

    #[test]
    fn validation_rejects_extra_old_to_new_entry() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.old_to_new
            .insert(ObjectRef::new(2, 0), ObjectRef::new(2, 0));
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("source 2 0 R has no placement")));
    }

    #[test]
    fn validation_rejects_removed_source_placement() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.removed_refs.insert(ObjectRef::new(1, 0));

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("removed source 1 0 R has source placement")));
    }

    #[test]
    fn validation_rejects_removed_objstm_member_placement() {
        let member = PlannedMember {
            source: ObjectRef::new(7, 0),
            output: ObjectRef::new(2, 0),
        };
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::Synthetic,
                output: ObjectRef::new(3, 0),
                members: vec![member],
            },
        ]);
        plan.old_to_new
            .insert(ObjectRef::new(7, 0), ObjectRef::new(2, 0));
        plan.removed_refs.insert(ObjectRef::new(7, 0));
        plan.trailer.form = XrefForm::Stream;

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("removed source 7 0 R has ObjStm member placement")));
    }

    #[test]
    fn validation_allows_removed_source_backed_container_placeholder() {
        let container_source = ObjectRef::new(2, 0);
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::SourceBacked(container_source),
                output: ObjectRef::new(2, 0),
                members: Vec::new(),
            },
        ]);
        plan.old_to_new
            .insert(container_source, ObjectRef::new(2, 0));
        plan.removed_refs.insert(container_source);
        plan.trailer.form = XrefForm::Stream;

        plan.validate().unwrap();
    }

    #[test]
    fn validation_rejects_removed_source_in_old_to_new_map() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        let removed = ObjectRef::new(2, 0);
        plan.old_to_new.insert(removed, ObjectRef::new(2, 0));
        plan.removed_refs.insert(removed);

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("removed source 2 0 R remains in old-to-new map")));
    }

    #[test]
    fn validation_rejects_duplicate_source_placement() {
        let plan = plan_for_test(vec![source(1, 1), source(1, 2)]);

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("source 1 0 R has multiple placements")));
    }

    #[test]
    fn validation_rejects_duplicate_objstm_member_output() {
        let mut plan = plan_for_test(vec![
            source(1, 1),
            PlannedIndirectObject::ObjectStream {
                origin: PlannedObjectStreamOrigin::Synthetic,
                output: ObjectRef::new(3, 0),
                members: vec![
                    PlannedMember {
                        source: ObjectRef::new(7, 0),
                        output: ObjectRef::new(2, 0),
                    },
                    PlannedMember {
                        source: ObjectRef::new(8, 0),
                        output: ObjectRef::new(2, 0),
                    },
                ],
            },
        ]);
        plan.old_to_new
            .insert(ObjectRef::new(7, 0), ObjectRef::new(2, 0));
        plan.old_to_new
            .insert(ObjectRef::new(8, 0), ObjectRef::new(2, 0));

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("output object 2 has multiple placements")));
    }

    #[test]
    fn validation_rejects_root_absent_from_old_to_new_values() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.root = Some(ObjectRef::new(2, 0));
        plan.trailer.root = plan.root;

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("root 2 0 R is absent from old-to-new map")));
    }

    #[test]
    fn validation_rejects_output_number_holes() {
        let mut plan = plan_for_test(vec![source(1, 1), source(2, 3)]);
        plan.old_to_new
            .insert(ObjectRef::new(2, 0), ObjectRef::new(3, 0));

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("output object 2 has no placement")));
    }

    #[test]
    fn validation_rejects_raw_version_below_1_5_for_xref_stream() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.version = "invalid".to_string();
        plan.trailer.form = XrefForm::Stream;

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("PDF invalid cannot contain object or xref streams")));
    }

    #[test]
    fn validation_rejects_version_below_1_5_for_xref_stream() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.version = "1.4".to_string();
        plan.trailer.form = XrefForm::Stream;

        let err = plan.validate().unwrap_err();

        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("PDF 1.4 cannot contain object or xref streams")));
    }

    #[test]
    fn lookup_helpers_return_mapping_and_skip_source_objects() {
        let plan = plan_for_test(vec![source(1, 1)]);

        assert_eq!(
            plan.new_for_original(ObjectRef::new(1, 0)),
            Some(ObjectRef::new(1, 0))
        );
        assert_eq!(
            <PlainWritePlan as NewNumberLookup>::new_for_original(&plan, ObjectRef::new(1, 0)),
            Some(ObjectRef::new(1, 0))
        );
    }

    #[test]
    fn validation_rejects_trailer_root_that_differs_from_plan_root() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.trailer.root = Some(ObjectRef::new(2, 0));
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message.contains("trailer root 2 0 R differs from plan root 1 0 R")));
    }

    #[test]
    fn validation_rejects_inconsistent_catalog_root_forms() {
        let mut plan = plan_for_test(vec![source(1, 1)]);
        plan.root = None;
        let err = plan.validate().unwrap_err();
        assert!(matches!(err, crate::Error::Unsupported(ref message)
            if message == "plain writer plan: Catalog root form is inconsistent"));
    }

    #[test]
    fn disable_plan_contains_only_source_objects() {
        let plan = build("three-page.pdf", ObjectStreamMode::Disable);
        assert!(plan
            .objects
            .iter()
            .all(|object| matches!(object, PlannedIndirectObject::Source { .. })));
        assert_eq!(plan.trailer.form, XrefForm::Table);
        plan.validate().unwrap();
    }

    #[test]
    fn preserve_without_source_objstm_uses_catalog_first_placement() {
        let plan = build("three-page.pdf", ObjectStreamMode::Preserve);

        assert!(plan
            .objects
            .iter()
            .all(|object| matches!(object, PlannedIndirectObject::Source { .. })));
        assert!(plan.trailer.form == XrefForm::Table);
    }

    #[test]
    fn build_materializes_deterministic_id_plan() {
        let path = fixture_path("three-page.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let mut options = write_options(ObjectStreamMode::Disable);
        options.static_id = false;
        options.deterministic_id = true;

        let plan = PlainWritePlan::build(&mut pdf, &options).unwrap();

        assert!(matches!(plan.trailer.id, IdPlan::Deterministic { .. }));
    }

    #[test]
    fn forced_version_below_1_5_selects_classic_xref() {
        let path = fixture_path("three-page-objstm.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let mut options = write_options(ObjectStreamMode::Disable);
        options.force_version = Some("1.4".to_string());

        let plan = PlainWritePlan::build(&mut pdf, &options).unwrap();

        assert_eq!(plan.version, "1.4");
        assert_eq!(plan.trailer.form, XrefForm::Table);
    }

    #[test]
    fn disable_public_null_replacement_remains_in_the_object_universe() {
        let path = fixture_path("null-visible-matrix.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let deleted = ObjectRef::new(5, 0);
        pdf.replace_object(deleted, ObjectHandle::null())
            .expect("replace the unreferenced object with null");

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Disable)).unwrap();

        assert!(plan.old_to_new.contains_key(&deleted));
        assert!(!plan.removed_refs.contains(&deleted));
    }

    #[test]
    fn generate_public_null_replacement_remains_in_the_object_universe() {
        let path = fixture_path("null-visible-matrix.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let deleted = ObjectRef::new(5, 0);
        pdf.replace_object(deleted, ObjectHandle::null())
            .expect("replace the unreferenced object with null");

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Generate)).unwrap();

        assert!(plan.old_to_new.contains_key(&deleted));
        assert!(!plan.removed_refs.contains(&deleted));
        plan.validate().unwrap();
    }

    #[test]
    fn preserve_source_objstm_members_keep_one_container_and_indices() {
        let plan = build("three-page-objstm.pdf", ObjectStreamMode::Preserve);
        let containers: Vec<_> = plan
            .objects
            .iter()
            .filter_map(|object| match object {
                PlannedIndirectObject::ObjectStream {
                    origin,
                    output,
                    members,
                } => Some((origin.clone(), *output, members.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(containers.len(), 1);
        assert_eq!(
            containers[0].0,
            PlannedObjectStreamOrigin::SourceBacked(ObjectRef::new(1, 0))
        );
        assert_eq!(
            plan.old_to_new.get(&ObjectRef::new(1, 0)),
            Some(&containers[0].1)
        );
        assert!(plan.objects.iter().all(|object| !matches!(
            object,
            PlannedIndirectObject::Source { source, .. }
                if *source == ObjectRef::new(1, 0)
        )));
        assert!(!containers[0].2.is_empty());
        for member in &containers[0].2 {
            assert_eq!(member.output.generation, 0);
        }
        assert_eq!(plan.trailer.form, XrefForm::Stream);
        plan.validate().unwrap();
    }

    #[test]
    fn preserve_without_source_objstm_uses_catalog_first_sources() {
        let plan = build("three-page.pdf", ObjectStreamMode::Preserve);
        assert!(plan
            .objects
            .iter()
            .all(|object| matches!(object, PlannedIndirectObject::Source { .. })));
    }

    #[test]
    fn preserve_stale_generation_is_removed_from_membership() {
        let plan = build(
            "null-visible-stale-generation-objstm.pdf",
            ObjectStreamMode::Preserve,
        );
        let stale = ObjectRef::new(4, 0);
        assert!(plan.removed_refs.contains(&stale));
        assert!(plan.objects.iter().all(|object| match object {
            PlannedIndirectObject::ObjectStream { members, .. } =>
                members.iter().all(|member| member.source != stale),
            PlannedIndirectObject::Source { source, .. } => *source != stale,
        }));
    }

    #[test]
    fn preserve_public_null_replacement_remains_in_the_object_stream() {
        let path = fixture_path("three-page-objstm.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let deleted = ObjectRef::new(4, 0);
        pdf.replace_object(deleted, ObjectHandle::null())
            .expect("replace the object with null");

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Preserve)).unwrap();

        assert!(plan.old_to_new.contains_key(&deleted));
        assert!(!plan.removed_refs.contains(&deleted));
    }

    #[test]
    fn preserve_classic_fallback_keeps_public_null_replacement() {
        let path = fixture_path("null-visible-matrix.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let deleted = ObjectRef::new(5, 0);
        pdf.replace_object(deleted, ObjectHandle::null())
            .expect("replace the unreferenced object with null");

        let plan =
            PlainWritePlan::build(&mut pdf, &write_options(ObjectStreamMode::Preserve)).unwrap();

        assert!(plan.old_to_new.contains_key(&deleted));
        assert!(!plan.removed_refs.contains(&deleted));
    }

    #[test]
    fn generate_plan_even_splits_132_eligible_objects() {
        let plan = build("objstm-gen-nostream-130rev.pdf", ObjectStreamMode::Generate);
        let containers: Vec<(PlannedObjectStreamOrigin, usize)> = plan
            .objects
            .iter()
            .filter_map(|object| match object {
                PlannedIndirectObject::ObjectStream {
                    origin, members, ..
                } => Some((origin.clone(), members.len())),
                _ => None, // cov:ignore: this fixture deliberately packs every planned source
            })
            .collect();
        assert_eq!(
            containers,
            vec![
                (PlannedObjectStreamOrigin::Synthetic, 66),
                (PlannedObjectStreamOrigin::Synthetic, 66),
            ]
        );
        plan.validate().unwrap();
    }
}