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
//! qpdf correspondence: QPDF_pages.cc page-tree repair plus QPDFJob.cc page-selection rebuilding.
//! Page-tree rebuild after extraction / merge / rotate.
//!
//! Given an open [`Pdf`] and an ordered list of selected leaf `/Page`
//! `ObjectRef`s (the output of [`crate::PagePlan`] /
//! [`crate::CombinedPlan`] for a **single** document), this
//! module rebuilds the document's `/Pages` tree so that:
//!
//! - The root `/Pages` node's `/Kids` enumerates exactly the selected pages,
//!   in selection order.
//! - `/Count` equals the selection length.
//! - Inheritable attributes (`/Resources`, `/MediaBox`, `/CropBox`,
//!   `/Rotate`) that were inherited from an ancestor `/Pages` node are pushed
//!   onto each leaf as live handles **before** the leaf is reparented, so the
//!   leaf no longer depends on the old ancestor chain. Direct non-scalar values
//!   are promoted in place through the canonical object registry, preserving
//!   qpdf's shared-handle identity; scalar values and existing indirect values
//!   retain qpdf's copy/identity behavior.
//! - After that push, the retained root no longer carries those four inheritable
//!   keys, matching `QPDF_optimization.cc:159-228`; its page-tree mutation keeps
//!   `/Type`, `/Kids`, and `/Count` as the structural keys.
//! - Every leaf's `/Parent` is repointed at the stable root `/Pages` value.
//!
//! The result is a **flat** qpdf-style page tree: no intermediate `/Pages`
//! nodes are created. An indirect root preserves its `ObjectRef`; a direct
//! root remains embedded in the catalog, matching qpdf's object-handle
//! ownership.
//!
//! # qpdf 11.9.0 observed behaviour (truth source `/usr/bin/qpdf`)
//!
//! Built a 3-page fixture with an intermediate `/Pages` node carrying
//! `/Rotate 90`, `/MediaBox [0 0 200 300]`, `/Resources 9 0 R`; page 2 had
//! its own `/MediaBox [0 0 400 500]`.
//!
//! - `qpdf in.pdf --pages in.pdf 1,3 -- out.pdf`: output has a single
//!   `/Pages` node whose `/Kids` directly lists the two leaves; each leaf
//!   gained explicit `/Rotate 90` and `/MediaBox` (the inherited value), with
//!   direct non-scalar values promoted to indirect objects; the intermediate
//!   node is gone from the reachable output.
//! - `qpdf in.pdf --pages in.pdf 2 -- out.pdf`: page 2 **kept** its own
//!   `/MediaBox [0 0 400 500]` (own attribute wins) while still gaining the
//!   inherited `/Rotate 90` and `/Resources` it lacked.
//! - `qpdf in.pdf --pages in.pdf 1,1 -- out.pdf`: `/Count` = 2 and `/Kids`
//!   holds **two distinct page-dictionary objects**, each a copy of page 1,
//!   while the shared `/Contents` stream object is referenced by both. So a
//!   duplicate selection slot yields a *separate page dictionary* but shared
//!   sub-objects (content streams, resources).
//!
//! This module reproduces that observable result while *mutating in place*
//! rather than writing a fresh renumbered document:
//!
//! - The **first** occurrence of a source page mutates the existing leaf
//!   (materialize inherited attrs + reparent); its `ObjectRef` is unchanged.
//! - **Subsequent** occurrences of the same source page allocate a fresh
//!   object number and shallow-copy the *post-push* page dictionary, then
//!   reparent that clone. Referenced sub-objects (e.g. `/Contents`,
//!   `/Resources` indirect refs) are left shared, exactly as qpdf does.
//!
//! # Scope (single document only)
//!
//! This layer operates on **one** [`Pdf`]. Rebuilding across multiple input
//! documents ([`crate::CombinedPlan`] with >1 input) additionally
//! requires cross-document object copying (renumbering, encryption-boundary
//! handling, name-conflict resolution) and is a separate future layer. The
//! single-input CLI wiring, outline/dest remap, and AcroForm
//! handling all operate over a single document and can build on the
//! [`RebuildResult`] returned here.
//!
//! Obsolete intermediate `/Pages` nodes are intentionally left as orphan
//! objects (unreachable from the page tree) for the unreferenced-resource
//! pruning layer to remove, mirroring the precedent set by
//! [`crate::job::QPDFJob::split_pages`]. Their qpdf-inheritable keys are
//! removed before they become orphaned, so preserved orphan objects still
//! match qpdf's flattening-side cleanup.

use crate::object_handle::ObjectHandleIdentity;
use crate::pages::{
    repair::{prepare_for_optimization_with_max_depth, PageTreeRoot},
    resolve_inherited_handle_with_max_depth, DEFAULT_MAX_PAGE_TREE_DEPTH,
};
use crate::{Error, ObjectHandle, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::io::{Read, Seek};

// ---------------------------------------------------------------------------
// Public result type
// ---------------------------------------------------------------------------

/// Outcome of a [`rebuild_page_tree`] call.
///
/// `new_kids` is the rebuilt `/Pages` `/Kids` array in selection order; its
/// length always equals the selection length (duplicates included).
///
/// `ref_map` maps each *source* page `ObjectRef` to **all** new leaf
/// `ObjectRef`s produced from it, in selection order. Duplicate selections
/// therefore appear as a multi-element `Vec`. Downstream layers use this:
///
/// - **8.10** (outline / named-destination remap): given an old page target,
///   look up `ref_map[old]` and remap to the first element (qpdf-equivalent:
///   destinations resolve to the first occurrence of a duplicated page).
/// - **8.11** (AcroForm): widget `/P` back-pointers follow the same rule.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RebuildResult {
    /// The rebuilt root `/Pages` `/Kids`, in selection order.
    pub new_kids: Vec<ObjectRef>,
    /// Source page ref → every new leaf ref derived from it (selection order).
    pub ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>>,
    /// Every original page-tree leaf that the rebuild dropped: the source page
    /// leaves (qpdf `getAllPages`) that are absent from `ref_map`.
    ///
    /// This is the exact set qpdf nulls during `--pages` (`QPDFJob` enumerates
    /// the original page tree and replaces each unselected `/Page` object with
    /// `null`). Downstream null-out (8.10 outline / named-destination remap)
    /// keys on membership here so a destination is only allowed to null a
    /// genuine removed page — never an arbitrary non-page object it happens to
    /// reference. Membership is captured from the **original** tree before the
    /// rebuild reparents leaves, so it cannot be reconstructed afterwards.
    pub removed_pages: BTreeSet<ObjectRef>,
}

// ---------------------------------------------------------------------------
// Inherited-attribute handle helpers
// ---------------------------------------------------------------------------

/// Promote one direct non-scalar inherited value through the canonical PDF
/// object registry without cloning its live allocation.
///
/// qpdf's `QPDF_optimization.cc:179-190` promotes direct arrays, dictionaries,
/// and streams before attaching them to leaves, while scalar values are copied
/// directly. `makeIndirectObject` updates the shared value in place, so every
/// alias observes the same indirect object number.
fn promote_inherited_value<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    value: ObjectHandle,
) -> Result<ObjectHandle> {
    value.try_dereference()?;
    let non_scalar = value.as_array().is_some()
        || value.as_dictionary().is_some()
        || value.as_stream_dict().is_some();
    if !value.is_direct() || !non_scalar {
        return Ok(value);
    }
    // Promotion changes how every containing indirect dictionary serializes
    // this shared value. Capture and dirty those owners while the value is
    // still direct; after promotion mark the newly allocated object itself,
    // matching the qpdf-native page-repair helper.
    if value.belongs_to_pdf(pdf.unique_id) {
        pdf.mark_object_handle_dirty(&value)?;
    }
    let indirect = pdf.make_indirect_from_object_handle(value)?;
    pdf.mark_object_handle_dirty(&indirect)?;
    Ok(indirect)
}

/// Replace a missing/null leaf key with the live inherited handle.
fn install_inherited_value<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page: &ObjectHandle,
    key: &[u8],
    value: Option<&ObjectHandle>,
) -> Result<()> {
    if page.try_has_key(key)? {
        return Ok(());
    }
    let Some(value) = value else {
        return Ok(());
    };
    page.replace_key(key, value.clone())?;
    pdf.mark_object_handle_dirty(page)
}

/// Resolve and prepare an inherited value only when the page has no visible
/// own value. A leaf-owned non-scalar must not be promoted merely because the
/// canonical walk returns that same leaf handle.
fn resolve_inherited_for_page<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
    page: &ObjectHandle,
    key: &[u8],
    max_depth: usize,
) -> Result<Option<ObjectHandle>> {
    let value = resolve_inherited_handle_with_max_depth(pdf, page_ref, key, max_depth)?;
    if page.try_has_key(key)? {
        return Ok(None);
    }
    value
        .map(|value| promote_inherited_value(pdf, value))
        .transpose()
}

/// Collect the canonical `/Pages` handles that qpdf's inherited-attribute
/// push visits before flattening the tree. The handles are captured before
/// leaf reparenting so the now-orphaned intermediate nodes can receive the
/// same inheritable-key cleanup as the retained root.
#[allow(
    clippy::mutable_key_type,
    reason = "ObjectHandleIdentity intentionally keys the canonical live allocation"
)]
fn collect_page_tree_nodes(
    node: ObjectHandle,
    nodes: &mut Vec<ObjectHandle>,
    seen: &mut HashSet<ObjectHandleIdentity>,
    depth: usize,
    max_depth: usize,
) -> Result<()> {
    if depth >= max_depth {
        let location = node
            .object_ref()
            .map_or_else(|| "direct /Pages node".to_owned(), |r| r.to_string());
        return Err(Error::Unsupported(format!(
            "page tree depth exceeds maximum of {max_depth} at {location}"
        )));
    }
    if !seen.insert(node.identity_key()) {
        return Ok(());
    }

    node.try_dereference()?;
    if !node.try_is_dictionary_of_type(b"Pages", b"")? {
        return Ok(());
    }
    nodes.push(node.clone());

    let kids = node.try_get_key(b"/Kids")?;
    let Some(kid_count) = kids.try_array_len()? else {
        return Ok(());
    };
    for index in 0..kid_count {
        let Some(kid) = kids.try_array_item(index)? else {
            continue; // cov:ignore: canonical array handles return Some for every in-range item
        };
        if kid.try_has_key(b"/Kids")? {
            collect_page_tree_nodes(kid, nodes, seen, depth + 1, max_depth)?;
        }
    }
    Ok(())
}

/// Materialize direct non-scalar inheritable values on every `/Pages` node
/// before the page-selection rebuild discards any branch.
///
/// qpdf's `pushInheritedAttributesToPageInternal` walks the complete tree
/// before flattening (`QPDF_optimization.cc:159-239`). Its direct-array,
/// dictionary, and stream promotion therefore also runs for a branch whose
/// pages will not be selected; the later page-selection operation can discard
/// that branch while `--preserve-unreferenced` still serializes the promoted
/// object.
fn promote_page_tree_inheritable_values<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    nodes: &[ObjectHandle],
) -> Result<()> {
    let inheritable_keys = [
        b"/CropBox".as_slice(),
        b"/MediaBox".as_slice(),
        b"/Resources".as_slice(),
        b"/Rotate".as_slice(),
    ];

    for node in nodes {
        for key in inheritable_keys {
            if !node.try_has_key(key)? {
                continue;
            }
            let value = node.try_get_key(key)?;
            promote_inherited_value(pdf, value)?;
        }
    }
    Ok(())
}

fn page_tree_root_handle<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_root: PageTreeRoot,
) -> Result<ObjectHandle> {
    match page_root {
        PageTreeRoot::Indirect(root_ref) => Ok(pdf.get_object_handle(root_ref)),
        PageTreeRoot::Direct { catalog } => pdf.get_object_handle(catalog).try_get_key(b"/Pages"),
        PageTreeRoot::DirectCatalog => pdf.root_handle()?.try_get_key(b"/Pages"),
    }
}

/// Warn about discarded unknown keys and remove qpdf's four inheritable keys
/// from every original `/Pages` node.
///
/// The selected leaves have already received their effective values when this
/// runs. Keeping this cleanup on live handles matters when the writer is asked
/// to preserve otherwise-unreferenced objects: the old intermediate nodes are
/// then still serialized, but no longer retain stale inherited attributes.
///
/// `QPDF::flattenPagesTree` asks `pushInheritedAttributesToPage` to warn while
/// walking an intermediate `/Pages` node. The retained root is excluded by its
/// missing `/Parent`; structural keys are also excluded because they are part
/// of the page-tree representation rather than inheritable page attributes.
/// qpdf prefixes each warning with the current `Pages object` description; the
/// parenthesized prefix below lets the resolver add the input filename in the
/// same position.
fn remove_inheritable_keys_from_page_tree<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    nodes: &[ObjectHandle],
) -> Result<()> {
    let inheritable_keys = [
        b"/CropBox".as_slice(),
        b"/MediaBox".as_slice(),
        b"/Resources".as_slice(),
        b"/Rotate".as_slice(),
    ];
    let structural_keys = [
        b"/Type".as_slice(),
        b"/Parent".as_slice(),
        b"/Kids".as_slice(),
        b"/Count".as_slice(),
    ];

    for node in nodes {
        let pages_object = node.object_ref().map_or_else(
            || "Pages object".to_owned(),
            |object_ref| {
                format!(
                    "Pages object: object {} {}",
                    object_ref.number, object_ref.generation
                )
            },
        );

        if node.try_has_key(b"/Parent")? {
            for key in node.try_get_keys()? {
                if !inheritable_keys.contains(&key.as_slice())
                    && !structural_keys.contains(&key.as_slice())
                {
                    pdf.push_warning(format!(
                        "({pages_object}): Unknown key {} in /Pages object is being discarded as a result of flattening the /Pages tree",
                        String::from_utf8_lossy(&key)
                    ))?;
                }
            }
        }

        for key in inheritable_keys {
            node.remove_key(key);
        }
        pdf.mark_object_handle_dirty(node)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Main entry point
// ---------------------------------------------------------------------------

/// Rebuild the document's `/Pages` tree from `selected` leaf page refs.
///
/// `selected` is the ordered list of source `/Page` `ObjectRef`s (from
/// [`crate::PagePlan::pages`] / a single-input
/// [`crate::CombinedPlan`]). Duplicate refs are permitted and
/// produce duplicate output pages, matching qpdf.
///
/// On success the in-memory document is mutated so that its root `/Pages`
/// value lists exactly the selected pages, each with inheritable attributes
/// pushed and `/Parent` repointed at that root. An indirect root keeps
/// its object reference; a direct catalog root remains direct. Serialize the
/// result with [`crate::PdfWriter`].
///
/// The `selected` refs it consumes are produced by
/// [`PagePlan`](crate::PagePlan) (single document) or a single-input
/// [`CombinedPlan`](crate::CombinedPlan). For an end-to-end
/// extraction walkthrough see the runnable `examples/extract_pages.rs`.
///
/// # Errors
///
/// - [`Error::Missing`] when `/Root` or the catalog `/Pages` value is absent.
/// - [`Error::Unsupported`] when the catalog / a selected ref is not a
///   dictionary, the page-tree depth limit is exceeded, or canonical indirect
///   allocation fails while duplicating a selection.
/// - Any error propagated from the canonical `ObjectHandle` resolver or
///   mutation surface.
pub fn rebuild_page_tree<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    selected: &[ObjectRef],
) -> Result<RebuildResult> {
    rebuild_page_tree_with_max_depth(pdf, selected, DEFAULT_MAX_PAGE_TREE_DEPTH)
}

/// Like [`rebuild_page_tree`] but with a caller-supplied inheritance-walk
/// recursion limit.
///
/// # Errors
///
/// - [`Error::Missing`] when `/Root` or the catalog `/Pages` value is absent.
/// - [`Error::Unsupported`] when the catalog, a selected ref, or the `/Pages`
///   root is not a dictionary, a selected object is not a `/Page` dictionary,
///   the page-tree depth limit (`max_depth`) is exceeded, or canonical indirect
///   allocation fails while duplicating a selection.
/// - Any error propagated from the canonical `ObjectHandle` resolver or
///   mutation surface while resolving the catalog, leaves, or inherited
///   attributes.
#[allow(
    clippy::mutable_key_type,
    reason = "ObjectHandleIdentity intentionally keys the canonical live allocation"
)]
pub fn rebuild_page_tree_with_max_depth<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    selected: &[ObjectRef],
    max_depth: usize,
) -> Result<RebuildResult> {
    // qpdf obtains the effective /Pages handle through getAllPages before
    // flattening it. That handle can be either an indirect root or a direct
    // dictionary embedded in the catalog. Keep the ownership boundary through
    // this rebuild instead of requiring catalog.get_ref("Pages").
    let root_candidate = pdf.trailer_key_handle(b"Root");
    if root_candidate.is_null() {
        return Err(Error::Missing("/Root"));
    }
    pdf.root_handle()?;
    let prepared =
        prepare_for_optimization_with_max_depth(pdf, max_depth)?.ok_or(Error::Missing("/Pages"))?;
    let page_root = prepared.root;
    // qpdf's page mutation APIs update `m->all_pages` in place. This rebuild
    // replaces the page tree wholesale, so invalidate the cached prepared
    // snapshot before any replacement can fail partway.
    pdf.invalidate_page_list_cache();
    let root = page_tree_root_handle(pdf, page_root)?;
    let mut page_tree_nodes = Vec::new();
    collect_page_tree_nodes(
        root.clone(),
        &mut page_tree_nodes,
        &mut HashSet::new(),
        0,
        max_depth,
    )?; // cov:ignore: LLVM attributes this multiline canonical traversal terminator separately

    // qpdf promotes direct non-scalar values on every original /Pages node
    // before page selection discards an unselected branch. Keep these objects
    // in the canonical registry so preserve-unreferenced can serialize them.
    promote_page_tree_inheritable_values(pdf, &page_tree_nodes)?;

    // Capture qpdf's repaired leaf order before changing /Kids or /Parent.
    // Any original leaf absent from ref_map is a removed page.
    let original_pages = prepared.pages;

    let mut new_kids: Vec<ObjectRef> = Vec::with_capacity(selected.len());
    let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
    let mut pending_leaves: Vec<ObjectHandle> = Vec::with_capacity(selected.len());
    // Tracks whether a given source ref has already consumed its in-place slot.
    let mut materialized: BTreeSet<ObjectRef> = BTreeSet::new();

    for &src in selected {
        let page = pdf.get_object_handle(src);
        page.try_dereference()?;
        if !page.try_is_dictionary_of_type(b"Page", b"")? {
            return Err(Error::Unsupported(format!(
                "selected object {src} is not a /Page dictionary"
            )));
        }

        let target = if materialized.insert(src) {
            // Resolve every inheritable attribute through the original live
            // parent chain before the final /Parent replacement. Resolve in
            // qpdf's key order so direct non-scalar promotions have the same
            // deterministic allocation order as QPDF_optimization.cc.
            let inherited_cropbox =
                resolve_inherited_for_page(pdf, src, &page, b"/CropBox", max_depth)?; // cov:ignore: LLVM maps this covered multiline call terminator to the call setup
            let inherited_mediabox =
                resolve_inherited_for_page(pdf, src, &page, b"/MediaBox", max_depth)?; // cov:ignore: LLVM maps this covered multiline call terminator to the call setup
            let inherited_resources =
                resolve_inherited_for_page(pdf, src, &page, b"/Resources", max_depth)?; // cov:ignore: LLVM maps this covered multiline call terminator to the call setup
            let inherited_rotate =
                resolve_inherited_handle_with_max_depth(pdf, src, b"/Rotate", max_depth)?;

            // qpdf's inherited attribute push leaves an absent key absent;
            // explicit null is treated as absent only when a real ancestor
            // value is available. Inherited handles retain their identity.
            install_inherited_value(pdf, &page, b"/CropBox", inherited_cropbox.as_ref())?;
            install_inherited_value(pdf, &page, b"/MediaBox", inherited_mediabox.as_ref())?;
            install_inherited_value(pdf, &page, b"/Resources", inherited_resources.as_ref())?;
            install_inherited_value(pdf, &page, b"/Rotate", inherited_rotate.as_ref())?;
            page.clone()
        } else {
            // Duplicate occurrence: shallow-copy the post-materialization
            // live page and allocate only the page dictionary. Indirect child
            // handles (`/Contents`, `/Resources`, ...) remain shared.
            let copy = page.shallow_copy()?;
            let promoted = pdf.make_indirect_from_object_handle(copy)?;
            pdf.mark_object_handle_dirty(&promoted)?;
            promoted
        };
        let target_ref = target
            .object_ref()
            .expect("prepared pages and duplicate promotion are indirect");

        new_kids.push(target_ref);
        ref_map.entry(src).or_default().push(target_ref);
        pending_leaves.push(target);
    }

    // Rewrite the root /Pages handle in place: flat /Kids in selection order,
    // /Count equal to the selection length, and no stale /Parent. A direct
    // root remains the live dictionary embedded in the catalog.
    // cov:ignore-start: prepare_for_optimization guarantees that the retained /Pages root is a dictionary
    if root.try_as_dictionary()?.is_none() {
        return Err(Error::Unsupported(match page_root {
            PageTreeRoot::Indirect(root_ref) => {
                format!("document /Pages root {root_ref} is not a dictionary")
            }
            PageTreeRoot::Direct { .. } => {
                "document catalog /Pages root is not a dictionary".into()
            }
            PageTreeRoot::DirectCatalog => {
                "document catalog /Pages root is not a dictionary".into()
            }
        }));
    } // cov:ignore-end
    root.replace_key(b"/Type", ObjectHandle::name(b"Pages".to_vec()))?;
    let kid_handles: Vec<_> = new_kids
        .iter()
        .map(|object_ref| pdf.get_object_handle(*object_ref))
        .collect();
    root.replace_key(b"/Kids", ObjectHandle::array(kid_handles))?;
    let count = i64::try_from(new_kids.len()).unwrap_or(i64::MAX);
    root.replace_key(b"/Count", ObjectHandle::integer(count))?;
    // qpdf's QPDF_optimization.cc:159-228 removes each inheritable key from
    // every /Pages node after pushing its effective value to the leaves. The
    // retained rebuilt root and the now-orphaned intermediate nodes are all
    // subject to that same cleanup.
    remove_inheritable_keys_from_page_tree(pdf, &page_tree_nodes)?;
    root.remove_key(b"/Parent");
    pdf.mark_object_handle_dirty(&root)?;

    // Reparent every retained page through the same live root handle. This is
    // qpdf's `flattenPagesTree` `replaceKey("/Parent", pages)` operation, and
    // direct roots therefore retain one shared direct-dictionary identity.
    for leaf in pending_leaves {
        leaf.replace_key(b"/Parent", root.clone())?;
        pdf.mark_object_handle_dirty(&leaf)?;
    }

    // A removed page is an original leaf that no selection kept (absent from
    // `ref_map`). New refs minted for duplicate selections are fresh object
    // numbers, never original leaves, so they are correctly excluded.
    let removed_pages: BTreeSet<ObjectRef> = original_pages
        .into_iter()
        .filter(|p| !ref_map.contains_key(p))
        .collect();

    Ok(RebuildResult {
        new_kids,
        ref_map,
        removed_pages,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::job::check_bytes_for_test;
    use crate::pages::page_refs;
    use crate::pipeline::test_support::NthWriteFailure;
    use crate::pipeline::PipelineHandle;
    use crate::writer::write_qpdf_to_memory;
    use crate::Pdf;
    use std::io::Cursor;
    use std::process::Command;
    use std::rc::Rc;

    /// Build a PDF with a root `/Pages` (2 0 R) → intermediate `/Pages`
    /// (3 0 R, carrying `/Rotate 90`, `/MediaBox [0 0 200 300]`,
    /// `/Resources 9 0 R`) → three leaves:
    ///   4 0 R  Page (no own attrs, /Contents 7 0 R)
    ///   5 0 R  Page (own /MediaBox [0 0 400 500], /Contents 8 0 R)
    ///   6 0 R  Page (no own attrs, no contents)
    /// plus 7,8 content streams and 9 the shared Resources dict.
    fn build_nested_pdf() -> Vec<u8> {
        let parts: Vec<(u32, String)> = vec![
            (1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
            (2, "<< /Type /Pages /Kids [3 0 R] /Count 3 >>".into()),
            (
                3,
                "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R 6 0 R] /Count 3 \
                 /Rotate 90 /MediaBox [0 0 200 300] /Resources 9 0 R >>"
                    .into(),
            ),
            (4, "<< /Type /Page /Parent 3 0 R /Contents 7 0 R >>".into()),
            (
                5,
                "<< /Type /Page /Parent 3 0 R /Contents 8 0 R /MediaBox [0 0 400 500] >>".into(),
            ),
            (6, "<< /Type /Page /Parent 3 0 R >>".into()),
        ];
        let c1 = b"BT /F1 12 Tf 10 10 Td (Page1) Tj ET";
        let c2 = b"BT /F1 12 Tf 10 10 Td (Page2) Tj ET";

        let mut out: Vec<u8> = b"%PDF-1.5\n".to_vec();
        let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
        for (n, s) in &parts {
            offs.insert(*n, out.len() as u64);
            out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
        }
        offs.insert(7, out.len() as u64);
        out.extend_from_slice(format!("7 0 obj\n<< /Length {} >>\nstream\n", c1.len()).as_bytes());
        out.extend_from_slice(c1);
        out.extend_from_slice(b"\nendstream\nendobj\n");
        offs.insert(8, out.len() as u64);
        out.extend_from_slice(format!("8 0 obj\n<< /Length {} >>\nstream\n", c2.len()).as_bytes());
        out.extend_from_slice(c2);
        out.extend_from_slice(b"\nendstream\nendobj\n");
        offs.insert(9, out.len() as u64);
        out.extend_from_slice(
            b"9 0 obj\n<< /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >>\nendobj\n",
        );

        let xref_start = out.len() as u64;
        let total = 10u32;
        out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
        for i in 1..total {
            out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
        }
        out.extend_from_slice(
            format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        out
    }

    /// Build a two-branch page tree where the selected page is under branch B
    /// and branch A carries a direct non-scalar inherited value. qpdf promotes
    /// branch A's direct `/MediaBox` before page selection discards that branch,
    /// so preserve-unreferenced output retains the promoted orphan object.
    fn build_deselected_branch_pdf() -> Vec<u8> {
        let parts: Vec<(u32, String)> = vec![
            (1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
            (2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".into()),
            (
                3,
                "<< /Type /Pages /Parent 2 0 R /Kids [5 0 R] /Count 1 \
                 /MediaBox [0 0 200 300] >>"
                    .into(),
            ),
            (
                4,
                "<< /Type /Pages /Parent 2 0 R /Kids [6 0 R] /Count 1 /Rotate 180 >>".into(),
            ),
            (5, "<< /Type /Page /Parent 3 0 R /Contents 7 0 R >>".into()),
            (
                6,
                "<< /Type /Page /Parent 4 0 R /Contents 8 0 R /MediaBox [0 0 612 792] >>".into(),
            ),
        ];
        let c1 = b"BT /F1 12 Tf 10 10 Td (Page1) Tj ET";
        let c2 = b"BT /F1 12 Tf 10 10 Td (Page2) Tj ET";

        let mut out: Vec<u8> = b"%PDF-1.5\n".to_vec();
        let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
        for (n, s) in &parts {
            offs.insert(*n, out.len() as u64);
            out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
        }
        offs.insert(7, out.len() as u64);
        out.extend_from_slice(format!("7 0 obj\n<< /Length {} >>\nstream\n", c1.len()).as_bytes());
        out.extend_from_slice(c1);
        out.extend_from_slice(b"\nendstream\nendobj\n");
        offs.insert(8, out.len() as u64);
        out.extend_from_slice(format!("8 0 obj\n<< /Length {} >>\nstream\n", c2.len()).as_bytes());
        out.extend_from_slice(c2);
        out.extend_from_slice(b"\nendstream\nendobj\n");

        let xref_start = out.len() as u64;
        let total = 9u32;
        out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
        for i in 1..total {
            out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
        }
        out.extend_from_slice(
            format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        out
    }

    /// A root `/Pages` node whose only `/Kids` entry is a direct `/Page`
    /// dictionary. qpdf's page enumeration promotes that live handle to the
    /// first available indirect object before a later rebuild allocates a
    /// duplicate selection slot.
    fn build_direct_leaf_pdf() -> Vec<u8> {
        let mut out = b"%PDF-1.4\n".to_vec();
        let off1 = out.len() as u64;
        out.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = out.len() as u64;
        out.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [<< /Type /Page /MediaBox [0 0 612 792] >>] /Count 1 >>\nendobj\n",
        );

        let xref_start = out.len() as u64;
        out.extend_from_slice(b"xref\n0 3\n0000000000 65535 f \n");
        out.extend_from_slice(format!("{off1:010} 00000 n \n").as_bytes());
        out.extend_from_slice(format!("{off2:010} 00000 n \n").as_bytes());
        out.extend_from_slice(
            format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        out
    }

    fn open(bytes: Vec<u8>) -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open(Cursor::new(bytes)).expect("PDF should parse")
    }

    fn resolved_handle(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef) -> ObjectHandle {
        let handle = pdf.get_object_handle(object_ref);
        pdf.resolve(&handle).expect("resolve object");
        handle
    }

    fn resolved_key(
        pdf: &mut Pdf<Cursor<Vec<u8>>>,
        object: &ObjectHandle,
        key: &[u8],
    ) -> ObjectHandle {
        let value = object.get_key(key);
        pdf.resolve(&value).expect("resolve dictionary child");
        value
    }

    fn integer_array(pdf: &mut Pdf<Cursor<Vec<u8>>>, value: ObjectHandle) -> Vec<i64> {
        resolved_handle_value(pdf, value)
            .as_array()
            .expect("array")
            .into_iter()
            .map(|item| {
                resolved_handle_value(pdf, item)
                    .as_integer()
                    .expect("integer array item")
            })
            .collect()
    }

    fn resolved_handle_value(pdf: &mut Pdf<Cursor<Vec<u8>>>, value: ObjectHandle) -> ObjectHandle {
        pdf.resolve(&value).expect("resolve handle");
        value
    }

    fn integer_array_key(
        pdf: &mut Pdf<Cursor<Vec<u8>>>,
        object: &ObjectHandle,
        key: &[u8],
    ) -> Vec<i64> {
        let value = resolved_key(pdf, object, key);
        integer_array(pdf, value)
    }

    fn handle_of(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef) -> ObjectHandle {
        resolved_handle(pdf, object_ref)
    }

    fn set_handle(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef, value: ObjectHandle) {
        pdf.replace_object(object_ref, value)
            .expect("set canonical object handle");
    }

    #[test]
    fn rebuild_marks_qpdf_get_all_pages_observation() {
        let mut pdf = open(build_nested_pdf());
        assert!(!pdf.ever_called_get_all_pages());

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)]).unwrap();

        assert!(
            pdf.ever_called_get_all_pages(),
            "qpdf rebuild preparation enumerates pages through getAllPages"
        );
    }

    #[test]
    fn rebuild_invalidates_the_cached_page_list() {
        let mut pdf = open(build_nested_pdf());
        let before = crate::PageDocumentHelper::new(&mut pdf)
            .get_all_pages()
            .expect("initial page list");
        assert_eq!(
            before,
            vec![
                ObjectRef::new(4, 0),
                ObjectRef::new(5, 0),
                ObjectRef::new(6, 0)
            ]
        );

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(5, 0)]).expect("page rebuild");

        let after = crate::PageDocumentHelper::new(&mut pdf)
            .get_all_pages()
            .expect("page list after rebuild");
        assert_eq!(after, vec![ObjectRef::new(5, 0)]);
    }

    #[allow(
        clippy::mutable_key_type,
        reason = "the test exercises the canonical live-allocation identity set"
    )]
    #[test]
    fn collect_page_tree_nodes_handles_duplicate_and_malformed_handles() {
        let pages = ObjectHandle::dictionary(vec![
            (b"/Type".to_vec(), ObjectHandle::name(b"Pages".to_vec())),
            (b"/Kids".to_vec(), ObjectHandle::integer(7)),
        ]);
        let mut nodes = Vec::new();
        let mut seen = HashSet::new();

        collect_page_tree_nodes(pages.clone(), &mut nodes, &mut seen, 0, 8)
            .expect("a malformed /Kids value is treated as an empty array");
        assert_eq!(nodes.len(), 1);
        collect_page_tree_nodes(pages, &mut nodes, &mut seen, 0, 8)
            .expect("a repeated canonical handle is skipped");
        assert_eq!(nodes.len(), 1);

        let leaf = ObjectHandle::dictionary(vec![(
            b"/Type".to_vec(),
            ObjectHandle::name(b"Page".to_vec()),
        )]);
        collect_page_tree_nodes(leaf, &mut nodes, &mut seen, 0, 8)
            .expect("a non-/Pages dictionary is ignored");
        assert_eq!(nodes.len(), 1);

        let direct_pages = ObjectHandle::dictionary(vec![(
            b"/Type".to_vec(),
            ObjectHandle::name(b"Pages".to_vec()),
        )]);
        let error = collect_page_tree_nodes(direct_pages, &mut nodes, &mut seen, 0, 0)
            .expect_err("the depth bound must apply before dereferencing the node");
        assert!(
            matches!(error, Error::Unsupported(message) if message.contains("direct /Pages node"))
        );
    }

    #[test]
    fn empty_selection_rebuilds_an_empty_page_tree() {
        let mut pdf = open(build_nested_pdf());
        let result = rebuild_page_tree(&mut pdf, &[]).expect("qpdf accepts zero selected pages");

        assert!(result.new_kids.is_empty());
        assert_eq!(
            result.removed_pages,
            BTreeSet::from([
                ObjectRef::new(4, 0),
                ObjectRef::new(5, 0),
                ObjectRef::new(6, 0),
            ])
        );

        let pages = resolved_handle(&mut pdf, ObjectRef::new(2, 0));
        assert_eq!(pages.get_key(b"/Count").as_integer(), Some(0));
        assert_eq!(
            pages
                .get_key(b"/Kids")
                .as_array()
                .expect("empty /Kids array")
                .len(),
            0
        );
    }

    #[test]
    fn selecting_a_pages_node_is_rejected() {
        // 2 0 R is the root /Pages node, not a leaf /Page. Passing it must
        // error rather than build a self-referential page tree.
        let mut pdf = open(build_nested_pdf());
        let err = rebuild_page_tree(&mut pdf, &[ObjectRef::new(2, 0)]).unwrap_err();
        assert!(
            matches!(err, Error::Unsupported(_)),
            "expected Unsupported for /Pages node, got {err:?}"
        );
    }

    #[test]
    fn count_and_kids_match_selection_order() {
        // Select pages 3,1 (objects 6 then 4) — descending / out of order.
        let mut pdf = open(build_nested_pdf());
        let sel = [ObjectRef::new(6, 0), ObjectRef::new(4, 0)];
        let res = rebuild_page_tree(&mut pdf, &sel).unwrap();

        assert_eq!(
            res.new_kids,
            vec![ObjectRef::new(6, 0), ObjectRef::new(4, 0)]
        );

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        assert_eq!(
            resolved_key(&mut pdf, &root, b"/Count").as_integer(),
            Some(2)
        );
        let kids = resolved_key(&mut pdf, &root, b"/Kids")
            .as_array()
            .expect("root /Kids array");
        assert_eq!(
            kids.into_iter()
                .map(|kid| kid.object_ref().expect("/Kids indirect page"))
                .collect::<Vec<_>>(),
            vec![ObjectRef::new(6, 0), ObjectRef::new(4, 0)]
        );
    }

    #[test]
    fn direct_catalog_root_stays_direct_after_rebuild_and_round_trips() {
        let mut pdf = open(build_nested_pdf());
        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        let direct_root = root
            .shallow_copy()
            .expect("/Pages dictionary should be shallow-copyable");
        let catalog = handle_of(&mut pdf, ObjectRef::new(1, 0));
        assert!(
            catalog.as_dictionary().is_some(),
            "catalog must be a dictionary"
        );
        catalog
            .replace_key(b"/Pages", direct_root)
            .expect("catalog /Pages replacement");
        pdf.mark_object_handle_dirty(&catalog)
            .expect("catalog mutation must be dirty");

        let result =
            rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0), ObjectRef::new(4, 0)]).unwrap();
        assert_eq!(result.new_kids.len(), 2);

        let catalog = handle_of(&mut pdf, ObjectRef::new(1, 0));
        let root = resolved_key(&mut pdf, &catalog, b"/Pages");
        assert!(root.is_direct(), "catalog /Pages must remain direct");
        assert_eq!(
            resolved_key(&mut pdf, &root, b"/Count").as_integer(),
            Some(2)
        );
        for page_ref in result.new_kids {
            let page = handle_of(&mut pdf, page_ref);
            let parent = resolved_key(&mut pdf, &page, b"/Parent");
            assert!(
                parent.is_same_object_as(&root),
                "page /Parent must retain the direct root identity"
            );
        }

        let out = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();
        let mut reopened = Pdf::open(Cursor::new(out)).expect("direct-root output must parse");
        assert_eq!(
            crate::PageDocumentHelper::new(&mut reopened)
                .get_all_pages()
                .unwrap()
                .len(),
            2
        );
    }

    #[test]
    fn rebuild_does_not_synthesize_absent_rotate() {
        let mut pdf = open(build_direct_leaf_pdf());
        let prepared = crate::pages::repair::prepare_for_optimization(&mut pdf)
            .expect("page preparation must succeed")
            .expect("fixture has a page tree");
        assert_eq!(prepared.pages, vec![ObjectRef::new(3, 0)]);

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(3, 0)])
            .expect("flat page rebuild must succeed");

        let page = handle_of(&mut pdf, ObjectRef::new(3, 0));
        assert!(
            !page.has_key(b"/Rotate"),
            "qpdf leaves an absent inherited /Rotate absent"
        );
    }

    #[test]
    fn rebuild_preserves_inherited_indirect_handle_identity() {
        let mut pdf = open(build_nested_pdf());
        let page = pdf.get_object_handle(ObjectRef::new(4, 0));
        let resources = pdf.get_object_handle(ObjectRef::new(9, 0));

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)])
            .expect("flat page rebuild must succeed");

        let page_resources = page
            .try_get_key(b"/Resources")
            .expect("page /Resources lookup must succeed");
        assert!(
            page_resources.is_same_object_as(&resources),
            "inherited /Resources must retain its live indirect handle"
        );
    }

    #[test]
    fn rebuild_promotes_a_catalog_alias_with_the_inherited_value_in_place() {
        let mut pdf = Pdf::empty().expect("empty PDF");
        let catalog = pdf.root_handle().expect("empty PDF catalog");
        let pages = resolved_handle(&mut pdf, ObjectRef::new(2, 0));
        let shared =
            ObjectHandle::dictionary(vec![(b"/Marker".to_vec(), ObjectHandle::integer(7))]);
        let page = pdf
            .make_indirect_from_object_handle(ObjectHandle::dictionary(vec![
                (b"/Type".to_vec(), ObjectHandle::name(b"Page".to_vec())),
                (b"/Parent".to_vec(), pages.clone()),
            ]))
            .expect("page object allocation");
        pdf.mark_object_handle_dirty(&page)
            .expect("page allocation must be dirty");
        let page_ref = page.object_ref().expect("page object reference");

        catalog
            .replace_key(b"/Foo", shared.clone())
            .expect("Catalog alias insertion");
        pages
            .replace_key(b"/Resources", shared.clone())
            .expect("Pages alias insertion");
        pages
            .replace_key(b"/Kids", ObjectHandle::array(vec![page]))
            .expect("Pages kids insertion");
        pages
            .replace_key(b"/Count", ObjectHandle::integer(1))
            .expect("Pages count insertion");
        pdf.mark_object_handle_dirty(&catalog)
            .expect("Catalog mutation must be dirty");
        pdf.mark_object_handle_dirty(&pages)
            .expect("Pages mutation must be dirty");

        rebuild_page_tree(&mut pdf, &[page_ref]).expect("page-selection rebuild");

        let foo = catalog.try_get_key(b"/Foo").expect("Catalog alias lookup");
        let page_resources = pdf
            .get_object_handle(page_ref)
            .try_get_key(b"/Resources")
            .expect("page inherited resources lookup");
        assert!(
            shared.is_indirect(),
            "qpdf promotion must update the aliased direct allocation in place"
        );
        assert!(
            foo.is_indirect(),
            "Catalog alias must become an indirect reference"
        );
        assert!(
            page_resources.is_indirect(),
            "inherited /Resources must become an indirect reference"
        );
        assert_eq!(
            foo.object_ref(),
            page_resources.object_ref(),
            "Catalog /Foo and page /Resources must use the same object number"
        );
        assert!(
            foo.is_same_object_as(&page_resources),
            "Catalog /Foo and page /Resources must retain the same live object identity"
        );
    }

    #[test]
    fn rebuild_mutates_retained_page_handles_in_place() {
        let mut pdf = open(build_nested_pdf());
        let root = pdf.get_object_handle(ObjectRef::new(2, 0));
        let page = pdf.get_object_handle(ObjectRef::new(4, 0));

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)])
            .expect("flat page rebuild must succeed");

        assert_eq!(
            root.try_get_key(b"/Count")
                .expect("live root /Count lookup must succeed")
                .as_integer(),
            Some(1)
        );
        let kids = root
            .try_get_key(b"/Kids")
            .expect("live root /Kids lookup must succeed");
        assert_eq!(
            kids.try_array_item(0)
                .expect("live root /Kids item lookup must succeed")
                .expect("the rebuilt root must have one child")
                .object_ref(),
            Some(ObjectRef::new(4, 0))
        );
        assert!(
            page.try_get_key(b"/Parent")
                .expect("live page /Parent lookup must succeed")
                .is_same_object_as(&root),
            "reparenting must be visible through the retained page handle"
        );
    }

    #[test]
    fn rebuilt_root_drops_qpdf_inheritable_attributes_after_materializing_pages() {
        let mut pdf = open(build_nested_pdf());
        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        root.replace_key(
            b"/MediaBox",
            ObjectHandle::array(vec![
                ObjectHandle::integer(0),
                ObjectHandle::integer(0),
                ObjectHandle::integer(612),
                ObjectHandle::integer(792),
            ]),
        )
        .unwrap();
        root.replace_key(
            b"/CropBox",
            ObjectHandle::array(vec![
                ObjectHandle::integer(10),
                ObjectHandle::integer(20),
                ObjectHandle::integer(500),
                ObjectHandle::integer(700),
            ]),
        )
        .unwrap();
        root.replace_key(b"/Resources", ObjectHandle::dictionary(Vec::new()))
            .unwrap();
        root.replace_key(b"/Rotate", ObjectHandle::integer(180))
            .unwrap();
        pdf.mark_object_handle_dirty(&root).unwrap();

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(6, 0)])
            .expect("flat page rebuild must succeed");

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        for key in [
            b"/MediaBox".as_slice(),
            b"/CropBox".as_slice(),
            b"/Resources".as_slice(),
            b"/Rotate".as_slice(),
        ] {
            assert!(
                !root.has_key(key),
                "rebuilt /Pages root must not retain inheritable {key:?}"
            );
        }

        let intermediate = handle_of(&mut pdf, ObjectRef::new(3, 0));
        for key in [
            b"/MediaBox".as_slice(),
            b"/CropBox".as_slice(),
            b"/Resources".as_slice(),
            b"/Rotate".as_slice(),
        ] {
            assert!(
                !intermediate.has_key(key),
                "orphaned intermediate /Pages must not retain inheritable {key:?}"
            );
        }

        let page = handle_of(&mut pdf, ObjectRef::new(6, 0));
        assert_eq!(
            resolved_key(&mut pdf, &page, b"/CropBox").object_ref(),
            Some(ObjectRef::new(10, 0)),
            "the selected page must retain the root-inherited /CropBox handle"
        );
    }

    #[test]
    fn promotes_direct_inheritable_values_on_deselected_branches() {
        let mut pdf = open(build_deselected_branch_pdf());

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(6, 0)])
            .expect("page-tree rebuild must succeed");

        let promoted = pdf
            .get_all_objects()
            .expect("canonical object enumeration must succeed")
            .into_iter()
            .filter_map(|handle| handle.as_array())
            .any(|items| {
                items.len() == 4
                    && items
                        .iter()
                        .map(ObjectHandle::as_integer)
                        .collect::<Vec<_>>()
                        == vec![Some(0), Some(0), Some(200), Some(300)]
            });
        assert!(
            promoted,
            "qpdf promotes the deselected branch's direct /MediaBox before cleanup"
        );
    }

    #[test]
    fn rebuild_warns_for_unknown_keys_only_on_flattened_pages_nodes() {
        let mut pdf = open(build_nested_pdf());

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        root.replace_key(b"/UserUnit", ObjectHandle::integer(1))
            .unwrap();
        pdf.mark_object_handle_dirty(&root).unwrap();

        let intermediate = handle_of(&mut pdf, ObjectRef::new(3, 0));
        intermediate
            .replace_key(b"/UserUnit", ObjectHandle::integer(2))
            .unwrap();
        pdf.mark_object_handle_dirty(&intermediate).unwrap();

        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)])
            .expect("page-tree rebuild must preserve qpdf warning behavior");

        let diagnostics = pdf.repair_diagnostics();
        let warnings: Vec<_> = diagnostics
            .entries()
            .iter()
            .map(|entry| entry.message.as_str())
            .filter(|message| message.contains("Unknown key /UserUnit"))
            .collect();
        assert_eq!(
            warnings,
            ["(Pages object: object 3 0): Unknown key /UserUnit in /Pages object is being discarded as a result of flattening the /Pages tree"],
            "only the flattened intermediate /Pages node should warn"
        );

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        assert_eq!(
            resolved_key(&mut pdf, &root, b"/UserUnit").as_integer(),
            Some(1)
        );
    }

    #[test]
    fn rebuild_propagates_unknown_pages_warning_sink_failure() {
        let mut pdf = open(build_nested_pdf());

        let intermediate = handle_of(&mut pdf, ObjectRef::new(3, 0));
        intermediate
            .replace_key(b"/UserUnit", ObjectHandle::integer(2))
            .unwrap();
        pdf.mark_object_handle_dirty(&intermediate).unwrap();

        let logger = crate::QPDFLogger::create();
        logger.set_warn(Some(PipelineHandle::new(NthWriteFailure::new(1))));
        pdf.set_logger(logger);

        assert!(matches!(
            rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)]),
            Err(Error::System(ref message)) if message == "sink write failure 1"
        ));
        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .any(|diagnostic| diagnostic.message.contains("Unknown key /UserUnit")));
    }

    #[test]
    fn inherited_attrs_materialized_on_leaf() {
        // Page 1 (obj 4) inherits everything from intermediate node 3.
        let mut pdf = open(build_nested_pdf());
        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)]).unwrap();

        let leaf = handle_of(&mut pdf, ObjectRef::new(4, 0));
        assert_eq!(
            resolved_key(&mut pdf, &leaf, b"/Rotate").as_integer(),
            Some(90)
        );
        let media_box = resolved_key(&mut pdf, &leaf, b"/MediaBox");
        assert!(
            media_box.is_indirect(),
            "expected promoted inherited /MediaBox reference"
        );
        assert_eq!(integer_array(&mut pdf, media_box), vec![0, 0, 200, 300]);
        // /Resources inherited via indirect ref 9 0 R retains that live
        // indirect handle, rather than materializing a dictionary clone.
        assert_eq!(
            resolved_key(&mut pdf, &leaf, b"/Resources").object_ref(),
            Some(ObjectRef::new(9, 0))
        );
        // Reparented to root.
        assert_eq!(
            resolved_key(&mut pdf, &leaf, b"/Parent").object_ref(),
            Some(ObjectRef::new(2, 0))
        );
    }

    #[test]
    fn own_attribute_wins_over_inherited() {
        // Page 2 (obj 5) has its own /MediaBox; it must be preserved while the
        // inherited /Rotate is still materialized.
        let mut pdf = open(build_nested_pdf());
        rebuild_page_tree(&mut pdf, &[ObjectRef::new(5, 0)]).unwrap();

        let leaf = handle_of(&mut pdf, ObjectRef::new(5, 0));
        assert_eq!(
            integer_array_key(&mut pdf, &leaf, b"/MediaBox"),
            vec![0, 0, 400, 500],
            "own /MediaBox must win over inherited [0 0 200 300]"
        );
        assert_eq!(
            resolved_key(&mut pdf, &leaf, b"/Rotate").as_integer(),
            Some(90)
        );
    }

    #[test]
    fn duplicate_selection_yields_distinct_page_dicts_sharing_contents() {
        // Select page 1 twice (obj 4, 4). qpdf: /Count 2, two distinct page
        // dicts, shared /Contents stream object.
        let mut pdf = open(build_nested_pdf());
        let res =
            rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0), ObjectRef::new(4, 0)]).unwrap();

        assert_eq!(res.new_kids.len(), 2);
        assert_eq!(res.new_kids[0], ObjectRef::new(4, 0)); // first keeps original
        let clone_ref = res.new_kids[1];
        assert_ne!(clone_ref, ObjectRef::new(4, 0), "second slot is a clone");

        // ref_map records both new refs under the source.
        assert_eq!(
            res.ref_map.get(&ObjectRef::new(4, 0)),
            Some(&vec![ObjectRef::new(4, 0), clone_ref])
        );

        let original = handle_of(&mut pdf, ObjectRef::new(4, 0));
        let clone = handle_of(&mut pdf, clone_ref);
        // Distinct objects but identical materialized content; /Contents
        // stream object is shared (same indirect ref), not duplicated.
        assert_eq!(
            resolved_key(&mut pdf, &original, b"/Contents").object_ref(),
            resolved_key(&mut pdf, &clone, b"/Contents").object_ref()
        );
        assert_eq!(
            resolved_key(&mut pdf, &original, b"/Contents").object_ref(),
            Some(ObjectRef::new(7, 0))
        );
        assert_eq!(
            resolved_key(&mut pdf, &clone, b"/Rotate").as_integer(),
            Some(90)
        );

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        assert_eq!(
            resolved_key(&mut pdf, &root, b"/Count").as_integer(),
            Some(2)
        );
    }

    #[test]
    fn duplicate_selection_allocates_after_canonical_direct_promotion() {
        let mut pdf = open(build_direct_leaf_pdf());

        // This is the page-preparation sequence: page enumeration
        // first promotes the direct leaf, then rebuild receives its canonical
        // reference twice. The allocator must see that promoted reference.
        let prepared = crate::pages::repair::prepare_for_optimization(&mut pdf)
            .expect("page preparation must succeed")
            .expect("fixture has a page tree");
        assert_eq!(prepared.pages, vec![ObjectRef::new(3, 0)]);

        let result = rebuild_page_tree(&mut pdf, &[ObjectRef::new(3, 0), ObjectRef::new(3, 0)])
            .expect("duplicate rebuild must succeed");
        assert_eq!(
            result.new_kids,
            vec![ObjectRef::new(3, 0), ObjectRef::new(4, 0)]
        );

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        let kids = resolved_key(&mut pdf, &root, b"/Kids")
            .as_array()
            .expect("rebuilt /Kids array");
        assert_eq!(
            kids.into_iter()
                .map(|kid| kid.object_ref().expect("/Kids page reference"))
                .collect::<Vec<_>>(),
            vec![ObjectRef::new(3, 0), ObjectRef::new(4, 0)]
        );
    }

    #[test]
    fn subset_round_trips_to_valid_pdf() {
        // Extract pages 1 and 3; write, reopen, and verify structure + check.
        let mut pdf = open(build_nested_pdf());
        rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0), ObjectRef::new(6, 0)]).unwrap();

        let out = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();

        let mut pdf2 = Pdf::open(Cursor::new(out.clone())).expect("rebuilt PDF should parse");
        let refs = page_refs(&mut pdf2).expect("page tree should walk");
        assert_eq!(refs.len(), 2, "/Pages should enumerate exactly 2 leaves");

        // Each leaf must carry the materialized inherited attrs after reopen.
        for page_ref in refs {
            let leaf = handle_of(&mut pdf2, page_ref);
            assert_eq!(
                resolved_key(&mut pdf2, &leaf, b"/Rotate").as_integer(),
                Some(90)
            );
            assert!(leaf.has_key(b"/MediaBox"));
        }

        // Belt-and-suspenders: the crate's own validity check is clean.
        check_bytes_for_test(out).expect("canonical qpdf check should run");
    }

    #[test]
    fn duplicate_round_trips_with_correct_page_count() {
        let mut pdf = open(build_nested_pdf());
        rebuild_page_tree(
            &mut pdf,
            &[
                ObjectRef::new(4, 0),
                ObjectRef::new(4, 0),
                ObjectRef::new(5, 0),
            ],
        )
        .unwrap();

        let out = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();

        let mut pdf2 = Pdf::open(Cursor::new(out)).expect("should parse");
        let refs = page_refs(&mut pdf2).expect("walk");
        assert_eq!(refs.len(), 3, "duplicate selection → 3 enumerated pages");
    }

    #[test]
    fn rebuild_honors_repair_depth_limit() {
        let mut pdf = open(build_nested_pdf());

        let root = handle_of(&mut pdf, ObjectRef::new(2, 0));
        let first_ref = pdf.get_object_handle(ObjectRef::new(10, 0));
        root.replace_key(b"/Kids", ObjectHandle::array(vec![first_ref]))
            .unwrap();
        root.replace_key(b"/Count", ObjectHandle::integer(1))
            .unwrap();
        pdf.mark_object_handle_dirty(&root).unwrap();

        let first = ObjectHandle::dictionary(vec![
            (b"/Type".to_vec(), ObjectHandle::name(b"Pages".to_vec())),
            (
                b"/Parent".to_vec(),
                pdf.get_object_handle(ObjectRef::new(2, 0)),
            ),
            (
                b"/Kids".to_vec(),
                ObjectHandle::array(vec![pdf.get_object_handle(ObjectRef::new(11, 0))]),
            ),
            (b"/Count".to_vec(), ObjectHandle::integer(1)),
        ]);
        set_handle(&mut pdf, ObjectRef::new(10, 0), first);

        // The missing /Type is deliberately below the supplied bound. The old
        // default-bound preparation silently repairs it before rebuilding.
        let second = ObjectHandle::dictionary(vec![
            (
                b"/Parent".to_vec(),
                pdf.get_object_handle(ObjectRef::new(10, 0)),
            ),
            (
                b"/Kids".to_vec(),
                ObjectHandle::array(vec![pdf.get_object_handle(ObjectRef::new(4, 0))]),
            ),
            (b"/Count".to_vec(), ObjectHandle::integer(1)),
        ]);
        set_handle(&mut pdf, ObjectRef::new(11, 0), second);

        let leaf = handle_of(&mut pdf, ObjectRef::new(4, 0));
        leaf.replace_key(b"/Parent", pdf.get_object_handle(ObjectRef::new(10, 0)))
            .unwrap();
        leaf.replace_key(b"/Rotate", ObjectHandle::integer(0))
            .unwrap();
        leaf.replace_key(b"/Resources", ObjectHandle::dictionary(Vec::new()))
            .unwrap();
        leaf.replace_key(
            b"/CropBox",
            ObjectHandle::array(vec![
                ObjectHandle::integer(0),
                ObjectHandle::integer(0),
                ObjectHandle::integer(200),
                ObjectHandle::integer(300),
            ]),
        )
        .unwrap();
        pdf.mark_object_handle_dirty(&leaf).unwrap();

        let before_root = handle_of(&mut pdf, ObjectRef::new(2, 0)).unparse_resolved();
        let before_second = handle_of(&mut pdf, ObjectRef::new(11, 0)).unparse_resolved();
        let error = rebuild_page_tree_with_max_depth(&mut pdf, &[ObjectRef::new(4, 0)], 2)
            .expect_err("repair must use the caller-supplied depth limit");
        assert!(matches!(error, Error::Unsupported(_)), "got {error:?}");
        assert_eq!(
            handle_of(&mut pdf, ObjectRef::new(2, 0)).unparse_resolved(),
            before_root
        );
        assert_eq!(
            handle_of(&mut pdf, ObjectRef::new(11, 0)).unparse_resolved(),
            before_second
        );
    }

    #[test]
    fn rebuild_cases_are_pinned_to_qpdf_11_9_page_probe() {
        let version = match Command::new("qpdf").arg("--version").output() {
            Ok(output) if output.status.success() => {
                String::from_utf8_lossy(&output.stdout).into_owned()
            }
            // cov:ignore-start: qpdf is an optional runtime oracle for this test.
            Ok(_) | Err(_) => {
                eprintln!("qpdf 11.9.0 unavailable; skipping page rebuild oracle probe");
                return;
            } // cov:ignore-end
        };
        // cov:ignore-start: the probe is only authoritative for the pinned qpdf release.
        if !version.starts_with("qpdf version 11.9.") {
            eprintln!("qpdf 11.9.0 unavailable; skipping page rebuild oracle probe");
            return;
        }
        // cov:ignore-end

        let directory = tempfile::tempdir().expect("create qpdf page probe directory");
        let input = directory.path().join("input.pdf");
        let output = directory.path().join("output.pdf");
        std::fs::write(&input, build_nested_pdf()).expect("write qpdf page probe input");

        let flattened = Command::new("qpdf")
            .arg(&input)
            .arg("--pages")
            .arg(&input)
            .arg("1,1")
            .arg("--")
            .arg(&output)
            .output()
            .expect("run qpdf duplicate page probe");
        assert!(
            flattened.status.success(),
            "qpdf duplicate page probe failed: {}",
            String::from_utf8_lossy(&flattened.stderr) // cov:ignore: assertion failure arm
        );

        let pages = Command::new("qpdf")
            .arg("--show-pages")
            .arg(&output)
            .output()
            .expect("run qpdf page listing probe");
        assert!(
            pages.status.success(),
            "qpdf page listing probe failed: {}",
            String::from_utf8_lossy(&pages.stderr) // cov:ignore: assertion failure arm
        );
        let pages = String::from_utf8_lossy(&pages.stdout);
        assert_eq!(
            pages.matches("page ").count(),
            2,
            "qpdf duplicate selection must produce two page entries: {pages}"
        );

        let page = Command::new("qpdf")
            .arg("--show-object=4")
            .arg(&output)
            .output()
            .expect("show qpdf first page probe");
        assert!(
            page.status.success(),
            "qpdf first-page probe failed: {}",
            String::from_utf8_lossy(&page.stderr) // cov:ignore: assertion failure arm
        );
        let page = String::from_utf8_lossy(&page.stdout);
        assert!(page.contains("/Rotate 90"), "qpdf first page: {page}");
        assert!(page.contains("/MediaBox"), "qpdf first page: {page}");
        assert!(page.contains("/Resources"), "qpdf first page: {page}");

        let mut direct_leaf = open(build_direct_leaf_pdf());
        rebuild_page_tree(&mut direct_leaf, &[ObjectRef::new(3, 0)])
            .expect("direct leaf rebuild must succeed");
        let direct_page = handle_of(&mut direct_leaf, ObjectRef::new(3, 0));
        assert!(
            !direct_page.has_key(b"/Rotate"),
            "qpdf's direct-leaf probe has no inherited /Rotate to push"
        );
    }

    #[test]
    fn promote_inherited_value_promotes_direct_streams() {
        let mut pdf = Pdf::empty().expect("empty PDF");
        let stream = ObjectHandle::stream(
            ObjectHandle::dictionary(Vec::new()),
            Rc::new(b"stream".to_vec()),
        );
        let promoted = promote_inherited_value(&mut pdf, stream)
            .expect("direct stream promotion must succeed");

        assert!(promoted.is_indirect());
        assert!(promoted.as_stream_dict().is_some());
    }

    #[test]
    fn promote_inherited_value_preserves_a_same_identity_alias_in_place() {
        let mut pdf = Pdf::empty().expect("empty PDF");
        let value = ObjectHandle::dictionary(vec![(b"Marker".to_vec(), ObjectHandle::integer(7))]);
        let alias = value.clone();

        let promoted =
            promote_inherited_value(&mut pdf, value).expect("first promotion must succeed");

        assert!(promoted.is_indirect());
        assert!(alias.is_indirect());
        assert!(promoted.is_same_object_as(&alias));
    }
}