flpdf 0.5.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
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
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
//! qpdf correspondence: QPDFAcroFormDocumentHelper.cc adjustAppearanceStream consuming resource_replacer.rs.
//! Port of qpdf's `AcroForm::adjustAppearanceStream`, consuming the shared
//! `ResourceReplacer` / `ResourceFinder` resource-replacement pipeline
//! (`libqpdf/QPDFAcroFormDocumentHelper.cc:628-849`, `libqpdf/ResourceFinder.cc`),
//! called from [`crate::AcroFormDocumentHelper::transform_annotations`] once
//! per copied `/AP` appearance stream whenever an AcroForm placement's
//! [`crate::acroform_document_helper::DrMap`] is non-empty.
//!
//! An appearance stream copied from another document may reference resource
//! names (a font, an `ExtGState`, ...) through its own `/Resources`
//! dictionary that collided with the destination `/AcroForm/DR` during the
//! merge and were renamed there (`DrMap`, populated by the AcroForm resource
//! merge). Left alone, the stream's content would still
//! say e.g. `/F1 18 Tf` while the destination's merged `/DR/Font` no longer
//! has an `F1` entry — only `F1_1`. [`adjust_appearance_stream_handle`] privatizes
//! the stream's `/Resources`, renames the colliding keys there, and rewrites
//! the matching name tokens in the stream's own content so both stay
//! internally consistent.
//!
//! [`crate::resource_replacer`] owns the shared content-stream token scan;
//! this module only applies its best-effort result to decoded appearance
//! stream bytes.

use std::io::{Read, Seek};
use std::rc::Rc;

use crate::acroform_document_helper::DrMap;
use crate::object_handle::{ObjectHandle, ResourceConflicts};
use crate::resource_replacer::replace_resource_names;
use crate::writer::DecodeLevel;
use crate::{Pdf, Result};

fn rewrite_appearance_content(decoded: &[u8], dr_map: &DrMap) -> Vec<u8> {
    match replace_resource_names(decoded, dr_map.renames()) {
        Ok(Some(bytes)) => bytes,
        Ok(None) | Err(_) => decoded.to_vec(),
    }
}

/// Return decoded appearance bytes only when qpdf's filter pipeline was
/// actually installed. `pipeStreamData` writes raw bytes and reports
/// `filtering_attempted = false` for unsupported or decode-level-gated
/// filters; treating those bytes as decoded would make a later re-encode
/// corrupt an image/binary appearance stream.
fn filterable_stream_data(
    stream: &ObjectHandle,
    decode_level: DecodeLevel,
) -> Result<Option<Rc<Vec<u8>>>> {
    let mut bytes = Vec::new();
    let mut pipeline = crate::pipeline::PlString::new("appearance stream data", None, &mut bytes);
    let mut filtering_attempted = false;
    let succeeded = stream.pipe_stream_data(
        &mut pipeline,
        &mut filtering_attempted,
        0,
        decode_level,
        false,
        false,
    )?;
    if !succeeded || !filtering_attempted {
        return Ok(None);
    }
    Ok(Some(Rc::new(bytes)))
}

/// Privatize and rewrite an appearance stream through the canonical
/// `ObjectHandle` graph.
///
/// This is qpdf's `QPDFAcroFormDocumentHelper::adjustAppearanceStream`
/// (`libqpdf/QPDFAcroFormDocumentHelper.cc:615-696`) over the live handle
/// route. The resource dictionary is copied before it is changed, the
/// qpdf-shaped `mergeResources` conflict map is fed back into the local
/// content rename map, and content decoding failures leave the already
/// applied resource mutation in place.
pub(crate) fn adjust_appearance_stream_handle<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    stream: &ObjectHandle,
    dr_map: &DrMap,
) -> Result<()> {
    if dr_map.is_empty() {
        return Ok(());
    }
    stream.try_dereference()?;
    let Some(stream_dict) = stream.as_stream_dict() else {
        return Ok(()); // cov:ignore: caller only supplies appearance streams
    };
    let resources_value = stream_dict.try_get_key(b"/Resources")?;
    if resources_value.try_is_null()? {
        return Ok(()); // cov:ignore: caller gates on an existing /Resources entry
    }
    let resources_terminal = pdf.resolve_handle(&resources_value)?;
    if resources_terminal.as_dictionary().is_none() {
        // qpdf's caller only invokes adjustAppearanceStream when
        // `resources.isDictionary()` (QPDFAcroFormDocumentHelper.cc:1006-1008).
        // A non-dictionary `/Resources` (e.g. an Integer in a malformed or
        // foreign appearance stream) is left untouched, matching qpdf.
        return Ok(());
    }
    let was_indirect = resources_value.is_indirect()
        || resources_value.object_ref().is_some()
        || resources_terminal.object_ref().is_some();
    let private_resources = resources_terminal.shallow_copy()?;
    let private_resources = if was_indirect {
        pdf.make_indirect_from_object_handle(private_resources)?
    } else {
        private_resources
    };
    stream_dict.replace_key(b"/Resources", private_resources.clone())?;

    // qpdf first merges empty category dictionaries solely to force any
    // existing indirect category dictionaries to become private.
    let merge_with = ObjectHandle::dictionary(
        dr_map
            .categories()
            .map(|category| {
                (
                    canonical_resource_name(category),
                    ObjectHandle::dictionary(Vec::new()),
                )
            })
            .collect(),
    );
    private_resources.merge_resources(&merge_with, None)?;

    // The first merge is live and sequential, exactly like qpdf's
    // subdict.getKey/replaceKey loop. Values displaced by a destination name
    // collision are staged into the corresponding merge_with category.
    for category in dr_map.categories() {
        let category_key = canonical_resource_name(category);
        let subdict = private_resources.try_get_key(&category_key)?;
        subdict.try_dereference()?;
        let Some(renames) = dr_map.category(category) else {
            continue; // cov:ignore: categories() iterates the same map
        };
        if subdict.as_dictionary().is_none() {
            continue;
        }
        let staged = merge_with.try_get_key(&category_key)?;
        for (old_name, new_name) in renames {
            let old_key = canonical_resource_name(old_name);
            let new_key = canonical_resource_name(new_name);
            let existing_new = subdict.try_get_key(&new_key)?;
            if !existing_new.try_is_null()? {
                staged.replace_key(&new_key, existing_new)?;
            }
            let existing_old = subdict.try_get_key(&old_key)?;
            if !existing_old.try_is_null()? {
                subdict.replace_key(&new_key, existing_old)?;
                subdict.remove_key(&old_key);
            }
        }
    }

    let mut conflicts = ResourceConflicts::new();
    private_resources.merge_resources(&merge_with, Some(&mut conflicts))?;
    let mut local_dr_map = dr_map.clone();
    extend_dr_map_from_conflicts(&mut local_dr_map, &conflicts);

    for category_key in private_resources.try_get_keys()? {
        let category = private_resources.try_get_key(&category_key)?;
        category.try_dereference()?;
        if category.as_dictionary().is_some() && category.try_get_keys()?.is_empty() {
            private_resources.remove_key(&category_key);
        }
    }

    // qpdf's token-filter installation is best effort. Resource mutations are
    // intentionally not rolled back when the stream cannot be decoded.
    if let Ok(Some(decoded)) = filterable_stream_data(stream, DecodeLevel::Generalized) {
        let rewritten = rewrite_appearance_content(&decoded, &local_dr_map);
        if let Ok(encoded) =
            crate::filters::encode_stream_data_from_handle(&stream_dict, &rewritten)
        {
            stream.replace_stream_data(Rc::new(encoded), None, None);
        } else {
            // qpdf has no LZW/ASCII85/ASCIIHex encoder; its token-filtered
            // stream is emitted under the writer's ordinary Flate route.
            let flate_dict = ObjectHandle::dictionary(vec![(
                b"/Filter".to_vec(),
                ObjectHandle::name(b"FlateDecode".to_vec()),
            )]);
            if let Ok(encoded) =
                crate::filters::encode_stream_data_from_handle(&flate_dict, &rewritten)
            {
                stream.replace_stream_data(
                    Rc::new(encoded),
                    Some(ObjectHandle::name(b"FlateDecode".to_vec())),
                    Some(ObjectHandle::null()),
                );
            }
        }
    }

    pdf.mark_object_handle_dirty(&private_resources)?;
    pdf.mark_object_handle_dirty(&stream_dict)?;
    pdf.mark_object_handle_dirty(stream)?;
    Ok(())
}

fn canonical_resource_name(name: &[u8]) -> Vec<u8> {
    let name = name.strip_prefix(b"/").unwrap_or(name);
    let mut result = Vec::with_capacity(name.len() + 1);
    result.push(b'/');
    result.extend_from_slice(name);
    result
}

fn extend_dr_map_from_conflicts(dr_map: &mut DrMap, conflicts: &ResourceConflicts) {
    for (category, category_conflicts) in conflicts {
        let category = category.strip_prefix(b"/").unwrap_or(category);
        for (old_name, new_name) in category_conflicts {
            dr_map.insert_rename(
                category,
                old_name.strip_prefix(b"/").unwrap_or(old_name).to_vec(),
                new_name.strip_prefix(b"/").unwrap_or(new_name).to_vec(),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PdfOpenOptions;
    use crate::{ObjectHandle, ObjectRef};
    use std::io::Cursor;
    use std::rc::Rc;

    /// Build a `DrMap` with a single category's rename table. `DrMap`'s
    /// `by_name` is private to the AcroForm owner, so tests drive it through
    /// the `#[cfg(test)]`-only `DrMap::for_test` constructor rather than
    /// round-tripping through a full resource merge over a real `Pdf`.
    fn dr_map_with(category: &[u8], old: &[u8], new: &[u8]) -> DrMap {
        DrMap::for_test(category, old, new)
    }

    #[derive(Default)]
    struct HandleDictionary {
        entries: Vec<(String, ObjectHandle)>,
    }

    impl HandleDictionary {
        fn new() -> Self {
            Self::default()
        }

        fn insert(&mut self, key: &str, value: ObjectHandle) {
            self.entries.retain(|(existing, _)| existing != key);
            self.entries.push((key.to_owned(), value));
        }

        fn into_handle(self) -> ObjectHandle {
            ObjectHandle::dictionary(
                self.entries
                    .into_iter()
                    .map(|(key, value)| {
                        let key = key.strip_prefix('/').unwrap_or(&key);
                        (format!("/{key}").into_bytes(), value)
                    })
                    .collect(),
            )
        }
    }

    struct HandleFixture;

    impl HandleFixture {
        fn dictionary(value: HandleDictionary) -> ObjectHandle {
            value.into_handle()
        }

        fn integer(value: i64) -> ObjectHandle {
            ObjectHandle::integer(value)
        }

        fn name(value: Vec<u8>) -> ObjectHandle {
            ObjectHandle::name(value)
        }
    }

    struct HandleDict(std::collections::BTreeMap<Vec<u8>, ObjectHandle>);

    impl HandleDict {
        fn get(&self, key: &str) -> Option<ObjectHandle> {
            let key = format!("/{}", key.strip_prefix('/').unwrap_or(key)).into_bytes();
            self.0.get(&key).cloned()
        }

        fn get_ref(&self, key: &str) -> Option<ObjectRef> {
            self.get(key).and_then(|value| value.object_ref())
        }
    }

    fn handle_dictionary(handle: ObjectHandle) -> Option<HandleDict> {
        handle.as_dictionary().map(HandleDict)
    }

    trait HandleObjectAccess {
        fn get(&self, key: &str) -> Option<ObjectHandle>;
        fn get_ref(&self, key: &str) -> Option<ObjectRef>;
    }

    impl HandleObjectAccess for ObjectHandle {
        fn get(&self, key: &str) -> Option<ObjectHandle> {
            let key = format!("/{}", key.strip_prefix('/').unwrap_or(key)).into_bytes();
            self.try_get_key(&key).ok().filter(|value| !value.is_null())
        }

        fn get_ref(&self, key: &str) -> Option<ObjectRef> {
            self.get(key).and_then(|value| value.object_ref())
        }
    }

    #[test]
    fn resource_replacement_preserves_diagnostic_bytes_and_rewrites_later_name() {
        let dr_map = DrMap::for_test(b"Font", b"F1", b"F1_1");
        let content = b"<0g> /F1 12 Tf";
        assert_eq!(
            rewrite_appearance_content(content, &dr_map),
            b"<0g> /F1_1 12 Tf"
        );
    }

    #[test]
    fn incomplete_inline_image_appearance_keeps_prefix_replacement_and_qpdf_separator() {
        let dr_map = DrMap::for_test(b"Font", b"F1", b"F1_1");
        let content = b"/F1 12 Tf BI ID";
        assert_eq!(
            rewrite_appearance_content(content, &dr_map),
            b"/F1_1 12 Tf BI ID "
        );
    }

    #[test]
    fn fatal_structure_error_keeps_appearance_content_byte_identical() {
        let dr_map = DrMap::for_test(b"Font", b"F1", b"F1_1");
        let content = b"/F1 12 Tf [";
        assert_eq!(rewrite_appearance_content(content, &dr_map), content);
    }

    // ---- adjust_appearance_stream_via_handle --------------------------------

    fn minimal_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref_start = pdf.len() as u64;
        pdf.extend_from_slice(
            format!("xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \n").as_bytes(),
        );
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    fn open_minimal() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open(Cursor::new(minimal_pdf_bytes())).expect("minimal pdf should parse")
    }

    fn dictionary(entries: &[(&str, ObjectHandle)]) -> ObjectHandle {
        let mut result = HandleDictionary::new();
        for (key, value) in entries {
            result.insert(key, value.clone());
        }
        result.into_handle()
    }

    fn indirect<R: Read + Seek>(pdf: &mut Pdf<R>, object_ref: ObjectRef) -> ObjectHandle {
        pdf.get_object_handle(object_ref)
    }

    fn set_dict<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        n: u32,
        entries: &[(&str, ObjectHandle)],
    ) -> ObjectRef {
        let r = ObjectRef::new(n, 0);
        pdf.replace_object(r, dictionary(entries))
            .expect("set canonical dictionary fixture");
        r
    }

    fn set_stream<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        n: u32,
        entries: &[(&str, ObjectHandle)],
        data: &[u8],
    ) -> ObjectRef {
        let r = ObjectRef::new(n, 0);
        pdf.replace_object(
            r,
            ObjectHandle::stream(dictionary(entries), Rc::new(data.to_vec())),
        )
        .expect("set canonical stream fixture");
        r
    }

    fn stream_handle<R: Read + Seek>(pdf: &mut Pdf<R>, stream_ref: ObjectRef) -> ObjectHandle {
        let stream = pdf.get_object_handle(stream_ref);
        pdf.resolve(&stream).expect("resolve stream fixture");
        stream
    }

    fn stream_dict(stream: &ObjectHandle) -> ObjectHandle {
        stream
            .as_stream_dict()
            .expect("appearance fixture must be a stream")
    }

    fn stream_bytes(stream: &ObjectHandle) -> Vec<u8> {
        stream
            .as_stream_data()
            .expect("appearance fixture must have stream data")
            .as_ref()
            .clone()
    }

    fn key(handle: &ObjectHandle, name: &[u8]) -> ObjectHandle {
        handle
            .try_get_key(name)
            .expect("read canonical fixture key")
    }

    fn adjust_appearance_stream_via_handle<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        ap_stream_ref: ObjectRef,
        dr_map: &DrMap,
    ) -> Result<()> {
        let stream = pdf.get_object_handle(ap_stream_ref);
        super::adjust_appearance_stream_handle(pdf, &stream, dr_map)
    }

    #[test]
    fn adjust_appearance_stream_empty_dr_map_is_noop() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let font_handle = indirect(&mut pdf, font_ref);
        let font_dict = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("F1", font_handle);
            d
        });
        let resources_ref = set_dict(&mut pdf, 3, &[("Font", font_dict)]);
        let resources_handle = indirect(&mut pdf, resources_ref);
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", resources_handle)],
            b"/F1 18 Tf",
        );

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &DrMap::new()).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1 18 Tf");
        assert_eq!(
            stream_dict(&stream).get_ref("Resources"),
            Some(resources_ref)
        );
    }

    #[test]
    fn adjust_appearance_stream_no_resources_is_noop() {
        let mut pdf = open_minimal();
        let ap_ref = set_stream(&mut pdf, 4, &[], b"/F1 18 Tf");
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1 18 Tf");
        assert!(stream_dict(&stream).get("Resources").is_none());
    }

    #[test]
    fn adjust_appearance_stream_rewrites_content_and_privatizes_indirect_resources() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let font_handle = indirect(&mut pdf, font_ref);
        let font_dict = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("F1", font_handle);
            d
        });
        let resources_ref = set_dict(&mut pdf, 3, &[("Font", font_dict)]);
        let resources_handle = indirect(&mut pdf, resources_ref);
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", resources_handle)],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf");
        let new_resources_ref = stream_dict(&stream)
            .get_ref("Resources")
            .expect("Resources should stay an indirect reference");
        assert_ne!(
            new_resources_ref, resources_ref,
            "must be a FRESH private object, not the original shared one"
        );

        // The private copy has ONLY the renamed key, pointing at the same
        // font object as before.
        let new_resources = stream_handle(&mut pdf, new_resources_ref);
        let new_font = handle_dictionary(key(&new_resources, b"/Font"))
            .expect("new resources must contain a Font dictionary");
        assert_eq!(new_font.get_ref("F1_1"), Some(font_ref));
        assert!(new_font.get("F1").is_none());

        // The ORIGINAL shared /DR-copy object is untouched.
        let original_resources = stream_handle(&mut pdf, resources_ref);
        let orig_font = handle_dictionary(key(&original_resources, b"/Font"))
            .expect("original resources must contain a Font dictionary");
        assert_eq!(orig_font.get_ref("F1"), Some(font_ref));
    }

    #[test]
    fn canonical_adjust_appearance_stream_rewrites_a_live_handle_without_materializing_it() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let font_handle = indirect(&mut pdf, font_ref);
        let font_dict = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("F1", font_handle);
            d
        });
        let resources_ref = set_dict(&mut pdf, 3, &[("Font", font_dict)]);
        let resources_handle = indirect(&mut pdf, resources_ref);
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", resources_handle)],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        let stream_dict = ap
            .as_stream_dict()
            .expect("expected live stream dictionary");
        let resources = pdf
            .resolve_handle(&stream_dict.try_get_key(b"/Resources").unwrap())
            .unwrap();
        let font = resources
            .try_get_key(b"/Font")
            .unwrap()
            .try_get_key(b"/F1_1")
            .unwrap();
        assert_eq!(font.object_ref(), Some(font_ref));
        assert!(resources.try_get_key(b"/F1").unwrap().is_null());

        let decoded = ap
            .get_stream_data(crate::writer::DecodeLevel::Generalized)
            .unwrap();
        assert_eq!(decoded.as_slice(), b"/F1_1 18 Tf");
        assert_ne!(resources.object_ref(), Some(resources_ref));

        let original = pdf.get_object_handle(resources_ref);
        let original_font = pdf
            .resolve_handle(&original)
            .unwrap()
            .try_get_key(b"/Font")
            .unwrap()
            .try_get_key(b"/F1")
            .unwrap();
        assert_eq!(original_font.object_ref(), Some(font_ref));
    }

    #[test]
    fn canonical_adjust_appearance_stream_empty_dr_map_is_a_noop() {
        let mut pdf = open_minimal();
        let ap_ref = set_stream(&mut pdf, 4, &[], b"/F1 18 Tf");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &DrMap::new()).unwrap();

        assert_eq!(ap.as_stream_data().unwrap().as_slice(), b"/F1 18 Tf");
        assert!(ap
            .as_stream_dict()
            .unwrap()
            .try_get_key(b"/Resources")
            .unwrap()
            .is_null());
    }

    #[test]
    fn canonical_adjust_appearance_stream_keeps_direct_resources_direct() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let resources = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            let mut fonts = HandleDictionary::new();
            fonts.insert("F1", indirect(&mut pdf, font_ref));
            d.insert("Font", HandleFixture::dictionary(fonts));
            d
        });
        let ap_ref = set_stream(&mut pdf, 4, &[("Resources", resources)], b"/F1 18 Tf");
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        let stream_dict = ap
            .as_stream_dict()
            .expect("expected live stream dictionary");
        let resources = stream_dict.try_get_key(b"/Resources").unwrap();
        assert!(resources.as_dictionary().is_some());
        assert!(resources.object_ref().is_none());
        let fonts = resources.try_get_key(b"/Font").unwrap();
        assert!(!fonts.try_get_key(b"/F1_1").unwrap().is_null());
        assert!(fonts.try_get_key(b"/F1").unwrap().is_null());
    }

    #[test]
    fn canonical_adjust_appearance_stream_keeps_non_dictionary_resource_category() {
        let mut pdf = open_minimal();
        let resources = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("Font", HandleFixture::integer(7));
            d
        });
        let ap_ref = set_stream(&mut pdf, 4, &[("Resources", resources)], b"/F1 18 Tf");
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        let resources = ap
            .as_stream_dict()
            .unwrap()
            .try_get_key(b"/Resources")
            .unwrap();
        assert_eq!(
            resources.try_get_key(b"/Font").unwrap().as_integer(),
            Some(7)
        );
    }

    #[test]
    fn canonical_adjust_appearance_stream_keeps_non_dictionary_resources_untouched() {
        // qpdf only calls adjustAppearanceStream when `resources.isDictionary()`
        // (QPDFAcroFormDocumentHelper.cc:1006-1008). A non-dictionary
        // `/Resources` (e.g. from a malformed or foreign appearance stream)
        // must leave both content and `/Resources` byte-for-byte untouched.
        let mut pdf = open_minimal();
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::integer(7))],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        assert_eq!(ap.as_stream_data().unwrap().as_slice(), b"/F1 18 Tf");
        let resources = ap
            .as_stream_dict()
            .unwrap()
            .try_get_key(b"/Resources")
            .unwrap();
        assert_eq!(resources.as_integer(), Some(7));
    }

    #[test]
    fn canonical_adjust_appearance_stream_keeps_resources_when_content_cannot_decode() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let font_handle = indirect(&mut pdf, font_ref);
        let font_dict = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("F1", font_handle);
            d
        });
        let resources_ref = set_dict(&mut pdf, 3, &[("Font", font_dict)]);
        let resources_handle = indirect(&mut pdf, resources_ref);
        let raw = b"not a supported filter payload";
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", resources_handle),
                ("Filter", HandleFixture::name(b"FlateDecode".to_vec())),
            ],
            raw,
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        assert_eq!(ap.as_stream_data().unwrap().as_slice(), raw);
        let stream_dict = ap.as_stream_dict().unwrap();
        let resources = pdf
            .resolve_handle(&stream_dict.try_get_key(b"/Resources").unwrap())
            .unwrap();
        assert!(!resources
            .try_get_key(b"/Font")
            .unwrap()
            .try_get_key(b"/F1_1")
            .unwrap()
            .is_null());
        assert!(resources
            .try_get_key(b"/Font")
            .unwrap()
            .try_get_key(b"/F1")
            .unwrap()
            .is_null());
    }

    #[test]
    fn canonical_adjust_appearance_stream_rewrites_second_order_resource_conflicts() {
        let mut pdf = open_minimal();
        let first_font_ref = ObjectRef::new(5, 0);
        let second_font_ref = ObjectRef::new(6, 0);
        pdf.replace_object(
            first_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        pdf.replace_object(
            second_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let first_font = indirect(&mut pdf, first_font_ref);
        let second_font = indirect(&mut pdf, second_font_ref);
        let font_dict = HandleFixture::dictionary({
            let mut d = HandleDictionary::new();
            d.insert("F1", first_font);
            d.insert("F1_1", second_font);
            d
        });
        let resources_ref = set_dict(&mut pdf, 3, &[("Font", font_dict)]);
        let resources_handle = indirect(&mut pdf, resources_ref);
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", resources_handle)],
            b"/F1 18 Tf /F1_1 12 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        let stream_dict = ap.as_stream_dict().unwrap();
        let resources = pdf
            .resolve_handle(&stream_dict.try_get_key(b"/Resources").unwrap())
            .unwrap();
        let fonts = resources.try_get_key(b"/Font").unwrap();
        assert_eq!(
            fonts.try_get_key(b"/F1_1").unwrap().object_ref(),
            Some(first_font_ref)
        );
        assert_eq!(
            fonts.try_get_key(b"/F1_1_1").unwrap().object_ref(),
            Some(second_font_ref)
        );
        let decoded = ap
            .get_stream_data(crate::writer::DecodeLevel::Generalized)
            .unwrap();
        assert_eq!(decoded.as_slice(), b"/F1_1 18 Tf /F1_1_1 12 Tf");
    }

    #[test]
    fn canonical_adjust_appearance_stream_falls_back_from_lzw_to_flate() {
        let mut pdf = open_minimal();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", HandleFixture::integer(1));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", HandleFixture::dictionary(resources)),
                ("Filter", HandleFixture::name(b"LZWDecode".to_vec())),
            ],
            &pack_lzw_9bit_literal(b"/F1 18 Tf"),
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        let ap = pdf.get_object_handle(ap_ref);
        pdf.resolve(&ap).unwrap();

        super::adjust_appearance_stream_handle(&mut pdf, &ap, &dr_map).unwrap();

        let stream_dict = ap.as_stream_dict().unwrap();
        assert_eq!(
            stream_dict.try_get_key(b"/Filter").unwrap().as_name(),
            Some(b"FlateDecode".to_vec())
        );
        assert!(stream_dict.try_get_key(b"/DecodeParms").unwrap().is_null());
        let decoded = ap
            .get_stream_data(crate::writer::DecodeLevel::Generalized)
            .unwrap();
        assert_eq!(decoded.as_slice(), b"/F1_1 18 Tf");
    }

    #[test]
    fn adjust_appearance_stream_incomplete_inline_image_keeps_resources_and_prefix_consistent() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, font_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 12 Tf BI ID",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 12 Tf BI ID ");
        let font = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .and_then(|resources| resources.get("Font"))
            .and_then(handle_dictionary)
            .expect("appearance stream should retain a Font resource dictionary");
        assert_eq!(font.get_ref("F1_1"), Some(font_ref));
        assert!(font.get("F1").is_none());
    }

    #[test]
    fn adjust_appearance_stream_direct_resources_stays_direct() {
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, font_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(font.get_ref("F1_1"), Some(font_ref));
    }

    #[test]
    fn adjust_appearance_stream_ensures_and_drops_empty_category() {
        // dr_map has a rename recorded under /ExtGState, but this AP
        // stream's own /Resources never had an /ExtGState entry at all: it
        // must be force-inserted (to unshare/exist), found empty (nothing
        // to rename into it), and then dropped — never left behind as a
        // stray empty sub-dictionary in the output.
        let mut pdf = open_minimal();
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(HandleDictionary::new()));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"q Q",
        );
        let dr_map = dr_map_with(b"ExtGState", b"GS1", b"GS1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("expected direct Resources dict");
        assert!(
            resources.get("ExtGState").is_none(),
            "empty /ExtGState sub-dict must be dropped, not left behind"
        );
        // The unrelated, pre-existing (empty) /Font sub-dict is untouched —
        // it wasn't force-inserted by this call, but since it's ALSO
        // empty, qpdf's resource merge counterpart would still
        // drop it via the same "remove empty subdictionaries" step, so it
        // must be dropped here too, matching qpdf iterating every
        // subdictionary of the resulting /Resources, not just the ones
        // `dr_map` touched.
        assert!(resources.get("Font").is_none());
    }

    #[test]
    fn adjust_appearance_stream_rewrites_content_when_category_subdict_is_indirect() {
        // The AP stream's own `/Resources` is direct, but ITS `/Font` entry
        // is itself an indirect reference (`/Font 6 0 R`) — a shape PDF
        // permits and the AcroForm resource merge already resolves on the
        // /DR-merge side. Before the fix, the pre-rename snapshot the
        // membership guard consults still held the un-resolved
        // an unresolved indirect handle, the non-resolving dictionary view cannot see through it, and
        // the guard silently blocked the rewrite even though `/F1` really
        // was present under that indirect sub-dict.
        let mut pdf = open_minimal();
        let font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(font_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let font_dict_ref = ObjectRef::new(6, 0);
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, font_ref));
        pdf.replace_object(font_dict_ref, HandleFixture::dictionary(font_dict))
            .unwrap();
        let mut resources = HandleDictionary::new();
        resources.insert("Font", indirect(&mut pdf, font_dict_ref));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(font.get_ref("F1_1"), Some(font_ref));
        assert!(font.get("F1").is_none());
    }

    #[test]
    fn adjust_appearance_stream_double_conflict_mints_fresh_local_name() {
        // The AP stream's own /Resources/Font already has BOTH `F1` and
        // `F1_1` as two DIFFERENT font objects. Renaming `F1` -> `F1_1`
        // (per dr_map) would silently clobber the pre-existing, unrelated
        // `F1_1` font if the collision were not detected. qpdf handles this
        // by minting a fresh name for the displaced value
        // (`libqpdf/QPDFAcroFormDocumentHelper.cc:791-807`) and extending
        // its local `dr_map` so content that already said `/F1_1` follows
        // it there too. The fresh name is `getUniqueResourceName("F1_1_",
        // ...)`'s first free suffix, `F1_1_1` — NOT `F1_2`, since the
        // minted-name base is the RENAME TARGET (`F1_1`), not the original
        // source name (`F1`).
        let mut pdf = open_minimal();
        let f1_font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(
            f1_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let f1_1_font_ref = ObjectRef::new(6, 0);
        pdf.replace_object(
            f1_1_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, f1_font_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, f1_1_font_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf /F1_1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf /F1_1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert!(font.get("F1").is_none());
        assert_eq!(
            font.get_ref("F1_1"),
            Some(f1_font_ref),
            "the renamed slot now holds F1's original value"
        );
        assert_eq!(
            font.get_ref("F1_1_1"),
            Some(f1_1_font_ref),
            "the displaced original F1_1 value moved to the freshly minted name"
        );
    }

    #[test]
    fn adjust_appearance_stream_reuses_one_name_pool_for_multiple_conflicts() {
        let mut pdf = open_minimal();
        let f1_ref = ObjectRef::new(5, 0);
        let f1_1_ref = ObjectRef::new(6, 0);
        let f2_ref = ObjectRef::new(7, 0);
        let f2_1_ref = ObjectRef::new(8, 0);
        for object_ref in [f1_ref, f1_1_ref, f2_ref, f2_1_ref] {
            pdf.replace_object(
                object_ref,
                HandleFixture::dictionary(HandleDictionary::new()),
            )
            .unwrap();
        }
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, f1_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, f1_1_ref));
        font_dict.insert("F2", indirect(&mut pdf, f2_ref));
        font_dict.insert("F2_1", indirect(&mut pdf, f2_1_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf /F1_1 18 Tf /F2 18 Tf /F2_1 18 Tf",
        );
        let mut dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        dr_map.insert_rename(b"Font", b"F2".to_vec(), b"F2_1".to_vec());

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"/F1_1 18 Tf /F1_1_1 18 Tf /F2_1 18 Tf /F2_1_1 18 Tf"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .unwrap();
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(font.get_ref("F1_1"), Some(f1_ref));
        assert_eq!(font.get_ref("F1_1_1"), Some(f1_1_ref));
        assert_eq!(font.get_ref("F2_1"), Some(f2_ref));
        assert_eq!(font.get_ref("F2_1_1"), Some(f2_1_ref));
    }

    #[test]
    fn adjust_appearance_stream_double_conflict_same_object_is_noop() {
        // /Resources/Font already has BOTH `F1` and `F1_1` pointing at the
        // SAME underlying font object — qpdf's `QPDFObjGen` identity check
        // treats this as already-resolved (the renamed slot would hold the
        // exact same object either way) and mints no fresh name at all.
        let mut pdf = open_minimal();
        let shared_font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(
            shared_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, shared_font_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, shared_font_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf /F1_1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        // `/F1` is renamed to `/F1_1`; the second `/F1_1` token is untouched
        // (no local rename was ever recorded for it), so both tokens end up
        // saying `/F1_1`.
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf /F1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert!(font.get("F1").is_none());
        assert!(
            font.get("F1_1_1").is_none(),
            "no fresh name should be minted for a same-object collision"
        );
        assert_eq!(font.get_ref("F1_1"), Some(shared_font_ref));
    }

    #[test]
    fn adjust_appearance_stream_unsupported_filter_is_non_fatal_noop() {
        // The AP stream's own /Resources/Font has "F2", never "F1" — a rename
        // recorded under dr_map for F1->F1_1 could never have matched this
        // stream's content even if it decoded successfully. Its content uses
        // CCITTFaxDecode: a real ISO 32000 stream filter, but one flpdf
        // intentionally never decodes (crate::filters::passthrough_codec_label
        // — an image/binary passthrough codec, preserved verbatim). Real
        // qpdf's AcroForm::adjustAppearanceStream wraps the equivalent
        // content-parse step in a try/catch that turns exactly this kind of
        // failure into a warning, not a hard error, so it must not propagate
        // here either and kill the whole overlay call chain over one
        // unrelated AP stream. The /Resources dict rename step still runs
        // (matching qpdf, which renames before its own try/catch), but since
        // there was nothing to rename, it is a no-op; the content bytes must
        // be left byte-for-byte exactly as read since flpdf cannot decode
        // them at all.
        let mut pdf = open_minimal();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F2", HandleFixture::integer(1));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", HandleFixture::dictionary(resources)),
                ("Filter", HandleFixture::name(b"CCITTFaxDecode".to_vec())),
            ],
            b"\x00\x01opaque-ccitt-bytes",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        let result = adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map);
        assert!(
            result.is_ok(),
            "an undecodable AP stream content must not fail the whole call"
        );

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"\x00\x01opaque-ccitt-bytes",
            "content bytes must be left exactly as read when they cannot be decoded"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get("F2").and_then(|value| value.as_integer()),
            Some(1),
            "unrelated existing key is untouched"
        );
        assert!(font.get("F1").is_none());
        assert!(font.get("F1_1").is_none());
    }

    #[test]
    fn adjust_appearance_stream_undecodable_filter_keeps_resources_rename_but_leaves_content_stale()
    {
        // Unlike the CCITT test above, this stream's own /Resources/Font
        // DOES have "F1" — a REAL collision, so the /Resources rename
        // (steps 1-4) is not a no-op this time. The content still cannot
        // be decoded (same CCITTFaxDecode passthrough codec), so step 5's
        // content rewrite cannot run at all. This asserts flpdf's ACTUAL
        // (verified) qpdf-matching behavior: qpdf performs the /Resources
        // rename BEFORE its own try/catch'd tokenize step
        // (`libqpdf/QPDFAcroFormDocumentHelper.cc:791-807` runs before
        // `:824-849`), and does NOT roll the rename back when the
        // subsequent tokenize fails — confirmed by fetching qpdf's actual
        // source for roborev PR #490 iter-3 finding 3, which proposed a
        // rollback; a rollback would have been the qpdf DIVERGENCE, so it
        // was declined and this test instead documents the verified,
        // matching (if internally inconsistent-looking) result: the dict
        // says "F1_1", the content still says "F1" — exactly like qpdf.
        let mut pdf = open_minimal();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", HandleFixture::integer(1));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", HandleFixture::dictionary(resources)),
                ("Filter", HandleFixture::name(b"CCITTFaxDecode".to_vec())),
            ],
            b"\x00\x01/F1 opaque-ccitt-bytes",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        let result = adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map);
        assert!(
            result.is_ok(),
            "an undecodable AP stream content must not fail the whole call"
        );

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"\x00\x01/F1 opaque-ccitt-bytes",
            "content bytes must be left exactly as read — qpdf does not roll \
             back a rename it already applied to /Resources just because the \
             later tokenize step failed"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get("F1_1").and_then(|value| value.as_integer()),
            Some(1),
            "the /Resources dict rename (steps 1-4) still applies even though \
             the content (step 5) could not be rewritten"
        );
        assert!(font.get("F1").is_none());
    }

    #[test]
    fn adjust_appearance_stream_leaves_lossy_filtered_content_byte_identical() {
        // DCTDecode is both specialized AND lossy compression
        // (StreamFilter::is_lossy_compression, stream_filter.rs's
        // DctStreamFilter). qpdf's pipeStreamData gates a lossy filter on
        // `decode_level >= qpdf_dl_all` (QPDF_Stream.cc); at the
        // DecodeLevel::Generalized this module uses, the filter pipeline is
        // never installed and raw bytes are piped through with
        // `filtered = false`. Re-encoding those raw JPEG bytes as though
        // they were decoded content would corrupt the image. This is
        // distinct from the CCITTFaxDecode tests above, which exercise
        // is_specialized_compression only; DCTDecode's is_lossy_compression
        // flag is the specific signal filterable_stream_data must also
        // honor (crate::object_handle's pipe_stream_data_inner gates lossy
        // filters at `decode_level < DecodeLevel::All`, a stricter bound
        // than specialized filters' `< DecodeLevel::Specialized`).
        let mut pdf = open_minimal();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", HandleFixture::integer(1));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let jpeg_like_bytes: &[u8] = b"\xff\xd8\xff\xe0not-real-jpeg-but-lossy-passthrough-bytes";
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", HandleFixture::dictionary(resources)),
                ("Filter", HandleFixture::name(b"DCTDecode".to_vec())),
            ],
            jpeg_like_bytes,
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map)
            .expect("a lossy-filtered AP stream must not fail the whole call");

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            jpeg_like_bytes,
            "lossy/specialized-filtered content must stay byte-identical, \
             not be treated as decoded and re-encoded"
        );
        assert_eq!(
            stream_dict(&stream)
                .get("Filter")
                .and_then(|value| value.as_name()),
            Some(b"DCTDecode".to_vec()),
            "the filter must stay untouched since qpdf never installs a \
             decode pipeline for it at this decode level"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get("F1_1").and_then(|value| value.as_integer()),
            Some(1),
            "the /Resources dict rename still applies independently of the \
             (never attempted) content rewrite"
        );
        assert!(font.get("F1").is_none());
    }

    #[test]
    fn adjust_appearance_stream_rename_chain_matches_qpdf_verified_result() {
        // dr_map records a CHAIN within one category: F1->F1_1 AND,
        // independently, F1_1->F1_1_1 (both entries genuinely present in
        // dr_map at once — plausible when the top-level /DR merge assigns
        // F1_1 to a renamed F1 while a DIFFERENT source object separately
        // collides under the destination's own pre-existing F1_1). This
        // stream's own /Resources/Font has both F1 and F1_1 locally.
        //
        // qpdf's rename loop (`libqpdf/QPDFAcroFormDocumentHelper.cc:781-803`,
        // fetched and read for roborev PR #490 iter-3 finding 1) mutates the
        // sub-dictionary IN PLACE: processing F1->F1_1 first (dr_map is
        // sorted, "F1" < "F1_1") moves F1's value into the F1_1 slot,
        // displacing the true original F1_1 value into a `merge_with`
        // side-map. Processing F1_1->F1_1_1 next then reads the ALREADY-
        // overwritten F1_1 slot (now holding F1's value, not the true
        // original) and moves THAT into F1_1_1. The re-merge step
        // (`:805-807`) then re-lands the side-mapped, true original F1_1
        // value back into ITS OWN name, F1_1 — which is free again, since
        // phase 1 vacated it. The two resources end up CROSS-WIRED between
        // the dict and content: this is qpdf's actual, verified output for
        // this input, not a bug flpdf introduced — a "cleaner" pre-snapshot
        // rewrite would be the byte-identical divergence here.
        let mut pdf = open_minimal();
        let f1_font_ref = ObjectRef::new(5, 0);
        pdf.replace_object(
            f1_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let f1_1_font_ref = ObjectRef::new(6, 0);
        pdf.replace_object(
            f1_1_font_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, f1_font_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, f1_1_font_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf /F1_1 18 Tf",
        );
        let mut dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        dr_map.insert_rename(b"Font", b"F1_1".to_vec(), b"F1_1_1".to_vec());

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf /F1_1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert!(font.get("F1").is_none());
        assert_eq!(
            font.get_ref("F1_1"),
            Some(f1_1_font_ref),
            "the true original F1_1 value re-lands under its OWN name via the re-merge"
        );
        assert_eq!(
            font.get_ref("F1_1_1"),
            Some(f1_font_ref),
            "F1's value ends up under F1_1_1, having been reprocessed by the second rename entry"
        );
    }

    #[test]
    fn adjust_appearance_stream_reuses_existing_key_for_same_object_on_new_conflict() {
        // Phase 2's conflict resolution (`libqpdf/QPDFAcroFormDocumentHelper.cc:805-807`'s
        // `resources.mergeResources(merge_with, &dr_map)`, `QPDFObjectHandle::mergeResources`'s
        // `og_to_name` reuse) is exercised here: /Resources/Font has F1 and
        // F2 BOTH pointing at the SAME object, plus F3 at a different
        // object. dr_map renames F3->F2. Phase 1 moves F3's value into F2
        // (displacing F2's original occupant — which is the SAME object as
        // F1 — into `merge_with`). Phase 2 then finds F2 occupied (by F3's
        // moved-in value) and, instead of minting a fresh name for the
        // displaced value, notices it already lives under F1 (by
        // `ObjectRef` identity) and records an EXTRA dr_map redirect
        // (F2->F1) instead — no fresh name minted at all.
        let mut pdf = open_minimal();
        let shared_ref = ObjectRef::new(5, 0);
        pdf.replace_object(
            shared_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let other_ref = ObjectRef::new(6, 0);
        pdf.replace_object(
            other_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, shared_ref));
        font_dict.insert("F2", indirect(&mut pdf, shared_ref));
        font_dict.insert("F3", indirect(&mut pdf, other_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F3 18 Tf /F2 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F3", b"F2");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"/F2 18 Tf /F1 18 Tf",
            "F3 (now under F2) rewrites to /F2; the original /F2 token must \
             follow its displaced value to wherever it actually ended up (F1), \
             not stay pointing at F2 (now a different object) or lose the rename"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(font.get_ref("F1"), Some(shared_ref));
        assert_eq!(font.get_ref("F2"), Some(other_ref));
        assert!(font.get("F3").is_none());
        assert!(
            font.get("F2_1").is_none(),
            "no fresh name should be minted — the displaced value is REUSED \
             under its existing F1 name, not aliased under a new one"
        );
    }

    #[test]
    fn adjust_appearance_stream_reuses_slot_vacated_earlier_in_same_merge() {
        // roborev PR #490 iter-4 finding 1: an earlier version of phase 2's
        // "reuse a key that already names the same object" lookup snapshot
        // `subdict` into `ref_to_key` ONCE, EAGERLY, before the staged loop
        // began. That missed a value that becomes visible to `subdict` only
        // DURING the loop — specifically, a slot phase 1 vacated and phase
        // 2's OWN verbatim-reinstate step (an earlier staged entry, in key
        // order) just refilled with the SAME object a LATER staged entry is
        // about to collide on.
        //
        // Ground truth (fetched from qpdf `main`,
        // `libqpdf/QPDFObjectHandle.cc`, `mergeResources`, since deepwiki's
        // summary of this was internally inconsistent): `og_to_name` is
        // built lazily — ONCE, on the FIRST genuine conflict — via the
        // `initialized_maps` guard around `make_og_to_name(this_val, ...)`.
        // Because that snapshot is taken mid-loop, it legitimately captures
        // any vacated-slot reinstate that ran earlier in the SAME
        // `other_val` loop (those already mutated `this_val` in place via
        // `this_val.replaceKey`). It is then FROZEN — untouched by anything
        // that happens afterward, including a fresh alias minted for a
        // later conflict (this is why the *previous* test above,
        // `..._double_conflict_mints_fresh_local_name`, still mints two
        // separate aliases for two conflicts that are BOTH genuine — that
        // qpdf behavior is unchanged by this fix). This test isolates the
        // one case the eager snapshot missed: reuse sourced from an
        // in-loop verbatim reinstate.
        //
        // Chain (three rename entries under Font, sorted by old_key so
        // phase 1 processes them F1, F1_1, F2 in that order):
        //   F1 -> F1_1: displaces F1_1's ORIGINAL value (shared_ref) into
        //               merge_with["F1_1"]; F1's value (temp_ref) moves in.
        //   F1_1 -> F3: displaces nothing (F3 was empty); F1_1's CURRENT
        //               value (temp_ref) moves to F3, vacating F1_1.
        //   F2 -> F4:   displaces F4's ORIGINAL value (shared_ref, the SAME
        //               object as above) into merge_with["F4"]; F2's value
        //               (other_ref) moves in.
        // After phase 1: subdict = {F3: temp_ref, F4: other_ref}; no key
        // names shared_ref any more. merge_with = {F1_1: shared_ref,
        // F4: shared_ref} — both entries name the SAME object.
        //
        // Phase 2 processes merge_with in key order: "F1_1" < "F4".
        //   F1_1: vacated (subdict has no F1_1) -> reinstated verbatim,
        //         subdict["F1_1"] = shared_ref. THIS is the in-loop
        //         mutation the eager snapshot could not see.
        //   F4:   occupied (by other_ref) -> genuine conflict, the FIRST
        //         one this loop hits. The lazily-built snapshot now
        //         includes the just-reinstated F1_1 -> shared_ref, so F4's
        //         displaced value (shared_ref) reuses F1_1 instead of
        //         minting a fresh alias (e.g. the wrong "F4_1").
        let mut pdf = open_minimal();
        let shared_ref = ObjectRef::new(5, 0);
        pdf.replace_object(
            shared_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let temp_ref = ObjectRef::new(6, 0);
        pdf.replace_object(temp_ref, HandleFixture::dictionary(HandleDictionary::new()))
            .unwrap();
        let other_ref = ObjectRef::new(7, 0);
        pdf.replace_object(
            other_ref,
            HandleFixture::dictionary(HandleDictionary::new()),
        )
        .unwrap();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", indirect(&mut pdf, temp_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, shared_ref));
        font_dict.insert("F2", indirect(&mut pdf, other_ref));
        font_dict.insert("F4", indirect(&mut pdf, shared_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F4 12 Tf",
        );
        let mut dr_map = dr_map_with(b"Font", b"F1", b"F1_1");
        dr_map.insert_rename(b"Font", b"F1_1".to_vec(), b"F3".to_vec());
        dr_map.insert_rename(b"Font", b"F2".to_vec(), b"F4".to_vec());

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"/F1_1 12 Tf",
            "the /F4 token must follow shared_ref to wherever it actually \
             ended up (F1_1, reused from the in-loop reinstate), not a \
             freshly minted alias"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get_ref("F1_1"),
            Some(shared_ref),
            "the vacated slot's own verbatim reinstate"
        );
        assert_eq!(
            font.get_ref("F4"),
            Some(other_ref),
            "F4's occupant is untouched — the reuse branch never mutates \
             subdict, unlike the fresh-mint branch"
        );
        assert!(
            font.get("F4_1").is_none(),
            "no fresh alias minted for F4 — it reuses F1_1 by ObjectRef \
             identity instead"
        );
    }

    #[test]
    fn adjust_appearance_stream_freezes_name_pool_with_identity_snapshot() {
        let mut pdf = open_minimal();
        let shared_ref = ObjectRef::new(5, 0);
        let temp_a_ref = ObjectRef::new(6, 0);
        let temp_b_ref = ObjectRef::new(7, 0);
        let temp_c_ref = ObjectRef::new(8, 0);
        let b_original_ref = ObjectRef::new(9, 0);
        let c_original_ref = ObjectRef::new(10, 0);
        for object_ref in [
            shared_ref,
            temp_a_ref,
            temp_b_ref,
            temp_c_ref,
            c_original_ref,
        ] {
            pdf.replace_object(
                object_ref,
                HandleFixture::dictionary(HandleDictionary::new()),
            )
            .unwrap();
        }
        let mut b_original = HandleDictionary::new();
        b_original.insert("C_1", HandleFixture::name(b"Inserted".to_vec()));
        pdf.replace_object(b_original_ref, HandleFixture::dictionary(b_original))
            .unwrap();

        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F0", indirect(&mut pdf, shared_ref));
        font_dict.insert("A", indirect(&mut pdf, shared_ref));
        font_dict.insert("A0", indirect(&mut pdf, temp_a_ref));
        font_dict.insert("A1", indirect(&mut pdf, temp_b_ref));
        font_dict.insert("A2", indirect(&mut pdf, temp_c_ref));
        font_dict.insert("B", indirect(&mut pdf, b_original_ref));
        font_dict.insert("C", indirect(&mut pdf, c_original_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/C 12 Tf",
        );
        let mut dr_map = dr_map_with(b"Font", b"A0", b"A");
        dr_map.insert_rename(b"Font", b"A1".to_vec(), b"B".to_vec());
        dr_map.insert_rename(b"Font", b"A2".to_vec(), b"C".to_vec());
        dr_map.insert_rename(b"Font", b"B".to_vec(), b"D".to_vec());

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"/C_1 12 Tf",
            "the later fresh conflict must use the pool captured by the first conflict"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(font.get_ref("C_1"), Some(c_original_ref));
        assert!(font.get("C_2").is_none());
    }

    #[test]
    fn adjust_appearance_stream_tolerates_malformed_nested_resource_like_qpdf() {
        // Keep object 8 lazy and malformed, reachable only two levels below
        // the Font category (Font/F0 -> object 5 -> /Broken -> object 8).
        // qpdf's actual conflict-resolution scan (getResourceNames,
        // QPDFObjectHandle.cc:1156-1170) dereferences a category value only
        // one level deep, to check `val.isDictionary()`, and then reads that
        // value's own KEYS without dereferencing ITS values — so object 5 is
        // touched (and is fine) but object 8 is never reached at all. The
        // canonical handle route must match that resolution depth, not go
        // deeper and surface a parse failure qpdf itself would never
        // encounter here.
        let bodies: &[&[u8]] = &[
            b"1 0 obj\n<< /Type /Catalog >>\nendobj\n",
            b"2 0 obj\nnull\nendobj\n",
            b"3 0 obj\nnull\nendobj\n",
            b"4 0 obj\nnull\nendobj\n",
            b"5 0 obj\nnull\nendobj\n",
            b"6 0 obj\nnull\nendobj\n",
            b"7 0 obj\nnull\nendobj\n",
            b"8 0 obj\n<<",
        ];
        let mut bytes = b"%PDF-1.7\n".to_vec();
        let mut offsets = Vec::new();
        for body in bodies {
            offsets.push(bytes.len() as u64);
            bytes.extend_from_slice(body);
        }
        let xref_start = bytes.len();
        bytes.extend_from_slice(b"xref\n0 9\n0000000000 65535 f \n");
        for offset in offsets {
            bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        bytes.extend_from_slice(
            format!("trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        let mut pdf = Pdf::open_with_options(
            Cursor::new(bytes),
            PdfOpenOptions {
                repair: false,
                ..PdfOpenOptions::default()
            },
        )
        .expect("malformed object must stay lazy");
        let broken_ref = indirect(&mut pdf, ObjectRef::new(8, 0));
        let broken_resource_ref = set_dict(&mut pdf, 5, &[("Broken", broken_ref)]);
        let f1_ref = set_dict(&mut pdf, 6, &[]);
        let f1_1_ref = set_dict(&mut pdf, 7, &[]);
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F0", indirect(&mut pdf, broken_resource_ref));
        font_dict.insert("F1", indirect(&mut pdf, f1_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, f1_1_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf",
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map)
            .expect("a malformed object two levels below the touched category must not fail");

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(
            stream_bytes(&stream),
            b"/F1_1 18 Tf",
            "the rename must actually apply to the stream content"
        );
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get_ref("F1_1"),
            Some(f1_ref),
            "F1's value must move into the F1_1 slot"
        );
        assert!(font.get("F1").is_none(), "F1 must be removed after rename");
        assert_eq!(
            font.get_ref("F0"),
            Some(broken_resource_ref),
            "F0 is untouched by the rename and its malformed grandchild is never dereferenced"
        );
    }

    #[test]
    fn adjust_appearance_stream_unrelated_nested_resource_does_not_interfere_with_rename() {
        // An unrelated category entry (F0) that itself points at a
        // dictionary with its own further reference (object 9 -> "Nested"
        // -> object 8) is not part of the F1->F1_1 rename and is never
        // dereferenced past its own immediate value — matching qpdf's
        // getResourceNames, which reads only the immediate category value's
        // own keys, not the values behind them (QPDFObjectHandle.cc:1156-1170).
        let mut pdf = open_minimal();
        let nested_value_ref = set_dict(&mut pdf, 8, &[]);
        let nested_value = indirect(&mut pdf, nested_value_ref);
        let nested_resource_ref = set_dict(&mut pdf, 9, &[("Nested", nested_value)]);
        let f1_ref = set_dict(&mut pdf, 6, &[]);
        let f1_1_ref = set_dict(&mut pdf, 7, &[]);
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F0", indirect(&mut pdf, nested_resource_ref));
        font_dict.insert("F1", indirect(&mut pdf, f1_ref));
        font_dict.insert("F1_1", indirect(&mut pdf, f1_1_ref));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[("Resources", HandleFixture::dictionary(resources))],
            b"/F1 18 Tf",
        );

        adjust_appearance_stream_via_handle(
            &mut pdf,
            ap_ref,
            &dr_map_with(b"Font", b"F1", b"F1_1"),
        )
        .unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);
        assert_eq!(stream_bytes(&stream), b"/F1_1 18 Tf");
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get_ref("F0"),
            Some(nested_resource_ref),
            "the unrelated F0 entry is untouched by the F1->F1_1 rename"
        );
    }

    /// Pack literal bytes as a minimal `/LZWDecode` stream: each byte is its
    /// own literal code (codes 0-255 are always literal single-byte table
    /// entries per PDF §7.4.4), followed by EOD (257). Every code stays 9
    /// bits wide because so few codes are emitted the table never reaches
    /// the first width-bump threshold (511 entries under the default
    /// EarlyChange). flpdf has no LZW encoder (decision flpdf-9hc.7.2), so a
    /// test needing LZW-encoded *input* must synthesize it directly —
    /// mirrors `filters::tests::pack_lzw_9bit`, which cannot be reused here
    /// since it is private to that module.
    fn pack_lzw_9bit_literal(bytes: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut buf: u32 = 0;
        let mut bits: u32 = 0;
        let mut codes: Vec<u16> = bytes.iter().map(|&b| u16::from(b)).collect();
        codes.push(257); // EOD
        for code in codes {
            buf = (buf << 9) | u32::from(code);
            bits += 9;
            while bits >= 8 {
                bits -= 8;
                out.push((buf >> bits) as u8);
            }
        }
        if bits > 0 {
            out.push((buf << (8 - bits)) as u8);
        }
        out
    }

    #[test]
    fn adjust_appearance_stream_lzw_reencode_failure_falls_back_to_flate() {
        // `/LZWDecode` is the one filter flpdf can decode but not re-encode
        // (crate::filters::apply_single_filter_encode, decision
        // flpdf-9hc.7.2). Unlike the CCITT test above, this stream's own
        // /Resources/Font DOES have "F1", so dr_map's F1->F1_1 rename is a
        // REAL rename, not a no-op. Before this fix, the /Resources rename
        // still applied but the content-rewrite step silently discarded the
        // token-replaced bytes on re-encode failure, leaving the content on
        // the stale "/F1" name while /Resources only had "F1_1" — an
        // inconsistent stream. This asserts the two stay consistent.
        let mut pdf = open_minimal();
        let mut font_dict = HandleDictionary::new();
        font_dict.insert("F1", HandleFixture::integer(1));
        let mut resources = HandleDictionary::new();
        resources.insert("Font", HandleFixture::dictionary(font_dict));

        let lzw_bytes = pack_lzw_9bit_literal(b"/F1 18 Tf");
        let ap_ref = set_stream(
            &mut pdf,
            4,
            &[
                ("Resources", HandleFixture::dictionary(resources)),
                ("Filter", HandleFixture::name(b"LZWDecode".to_vec())),
            ],
            &lzw_bytes,
        );
        let dr_map = dr_map_with(b"Font", b"F1", b"F1_1");

        adjust_appearance_stream_via_handle(&mut pdf, ap_ref, &dr_map).unwrap();

        let stream = stream_handle(&mut pdf, ap_ref);

        // Dict-level rename (steps 1-4) applied, as always.
        let resources = stream_dict(&stream)
            .get("Resources")
            .and_then(handle_dictionary)
            .expect("Resources should stay a direct (embedded) dictionary");
        let font = resources.get("Font").and_then(handle_dictionary).unwrap();
        assert_eq!(
            font.get("F1_1").and_then(|value| value.as_integer()),
            Some(1)
        );
        assert!(font.get("F1").is_none());

        // The content must agree: re-encoded as FlateDecode (flpdf cannot
        // re-encode LZW), with the resource token renamed to match.
        assert_eq!(
            stream_dict(&stream)
                .get("Filter")
                .and_then(|value| value.as_name()),
            Some(b"FlateDecode".to_vec()),
            "un-re-encodable /LZWDecode must fall back to /FlateDecode"
        );
        assert!(
            stream_dict(&stream).get("DecodeParms").is_none(),
            "stale LZW /DecodeParms must not survive the filter swap"
        );
        let decoded_content = stream
            .get_stream_data(crate::writer::DecodeLevel::Generalized)
            .unwrap();
        assert_eq!(
            decoded_content.as_slice(),
            b"/F1_1 18 Tf",
            "content must reference the RENAMED name, consistent with /Resources"
        );
        let expected_length = i64::try_from(stream_bytes(&stream).len()).unwrap();
        assert_eq!(
            stream_dict(&stream)
                .get("Length")
                .and_then(|value| value.as_integer()),
            Some(expected_length),
            "/Length must match the newly re-encoded bytes"
        );
    }
}