flpdf 0.6.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
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
//! [`PageLabelDocumentHelper`] reads and reconstructs (ISO 32000-1 §12.4.2)
//! the catalog `/PageLabels` number tree. The qpdf-shaped read methods retain
//! live [`ObjectHandle`] values for raw `/S`, `/P`, and `/St` semantics;
//! [`LabelRange`] is the typed view used by reconstruction and inspection APIs.
//!
//! qpdf correspondence: `QPDFPageLabelDocumentHelper.cc` canonical page-label access and reconstruction.
//!
//!

use crate::nntree::DEFAULT_MAX_TREE_DEPTH;
use crate::{Error, ObjectHandle, Pdf, Result};
use std::collections::BTreeSet;
use std::io::{Read, Seek};

/// Page-label numbering style (ISO 32000-1 §12.4.2 `/S`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelStyle {
    /// `/D` — decimal arabic.
    Decimal,
    /// `/R` — uppercase roman.
    RomanUpper,
    /// `/r` — lowercase roman.
    RomanLower,
    /// `/A` — uppercase letters (A, B, …, Z, AA, …).
    AlphaUpper,
    /// `/a` — lowercase letters.
    AlphaLower,
    /// No `/S` — labels have no numeric portion (prefix only).
    None,
}

impl LabelStyle {
    /// Map a `/S` name's bytes to a style; unrecognised/absent → [`LabelStyle::None`].
    pub fn from_name(name: &[u8]) -> Self {
        match name {
            b"D" => LabelStyle::Decimal,
            b"R" => LabelStyle::RomanUpper,
            b"r" => LabelStyle::RomanLower,
            b"A" => LabelStyle::AlphaUpper,
            b"a" => LabelStyle::AlphaLower,
            _ => LabelStyle::None,
        }
    }

    /// The `/S` name string, or `None` for [`LabelStyle::None`].
    pub fn to_name(self) -> Option<&'static str> {
        match self {
            LabelStyle::Decimal => Some("D"),
            LabelStyle::RomanUpper => Some("R"),
            LabelStyle::RomanLower => Some("r"),
            LabelStyle::AlphaUpper => Some("A"),
            LabelStyle::AlphaLower => Some("a"),
            LabelStyle::None => None,
        }
    }
}

/// One `/PageLabels` range: numbering style, prefix, and starting value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LabelRange {
    /// Numbering style (`/S`).
    pub style: LabelStyle,
    /// Label prefix (`/P`), decoded; empty when absent.
    pub prefix: String,
    /// First value in the range (`/St`); defaults to 1.
    pub start: i64,
}

/// A qpdf-shaped reconstructed label before it crosses a document boundary.
/// `source_id` lets page-job consumers copy the raw dictionary through the
/// persistent foreign-object map instead of collapsing it into `LabelRange`.
pub(crate) struct RawPageLabelEntry {
    pub(crate) index: i64,
    pub(crate) source_id: u64,
    /// True when qpdf keeps the source QPDF as the page-selection owner.
    /// Foreign source labels remain raw so the destination writer can report
    /// qpdf's ownership error instead of silently copying them.
    pub(crate) source_is_primary: bool,
    pub(crate) label: ObjectHandle,
}

impl LabelRange {
    /// Decode a live qpdf-shaped label dictionary without materializing it as
    /// an independent value snapshot. Unknown `/S` names remain unknown to the
    /// handle, while this typed compatibility view retains the historical
    /// `LabelStyle::None` mapping.
    fn from_handle(handle: &ObjectHandle) -> Result<Option<Self>> {
        let handle = handle.clone();
        handle.try_dereference()?;
        if !handle.try_is_dictionary()? {
            return Ok(None);
        }
        let style = handle
            .try_get_key(b"/S")?
            .try_as_name()?
            .map(|name| LabelStyle::from_name(&name))
            .unwrap_or(LabelStyle::None);
        // `QPDFPageLabelDocumentHelper::getLabelForPage` copies `/P` verbatim
        // without inspecting its type (`QPDFPageLabelDocumentHelper.cc:38,48`),
        // so a non-string prefix must not raise qpdf's string typeWarning here.
        // `try_get_string_value` would; this stays on the silent accessor and
        // falls back to an empty prefix like the pre-cutover code did.
        let prefix_handle = handle.try_get_key(b"/P")?;
        prefix_handle.try_dereference()?;
        let prefix_bytes = prefix_handle.as_string().unwrap_or_default();
        let prefix = crate::json_inspect::decode_pdf_text_string(&prefix_bytes)
            .unwrap_or_else(|| String::from_utf8_lossy(&prefix_bytes).into_owned());
        let start = handle.try_get_key(b"/St")?.try_as_integer()?.unwrap_or(1);
        Ok(Some(Self {
            style,
            prefix,
            start,
        }))
    }
}

/// Compare reconstructed raw label dictionaries using qpdf's unparse
/// comparison for `/S` and `/P` plus checked `/St` arithmetic
/// (`QPDFPageLabelDocumentHelper.cc:57-79`).
fn raw_page_labels_are_redundant(
    previous_index: i64,
    previous: &ObjectHandle,
    index: i64,
    current: &ObjectHandle,
) -> Result<bool> {
    let previous_st = previous.try_get_key(b"/St")?.try_as_integer()?;
    let current_st = current.try_get_key(b"/St")?.try_as_integer()?;
    let expected_start = index
        .checked_sub(previous_index)
        .and_then(|gap| previous_st.and_then(|start| start.checked_add(gap)));
    Ok(match (expected_start, current_st) {
        (Some(expected_start), Some(current_st)) => {
            current_st == expected_start
                && previous.try_get_key(b"/S")?.unparse() == current.try_get_key(b"/S")?.unparse()
                && previous.try_get_key(b"/P")?.unparse() == current.try_get_key(b"/P")?.unparse()
        }
        _ => false,
    })
}

/// Fold raw label dictionaries that already belong to the destination
/// document.
pub(crate) fn merge_adjacent_raw_labels(
    ranges: Vec<(i64, ObjectHandle)>,
) -> Result<Vec<(i64, ObjectHandle)>> {
    let mut out = Vec::with_capacity(ranges.len());
    for range in ranges {
        if let Some((previous_index, previous)) = out.last() {
            if raw_page_labels_are_redundant(*previous_index, previous, range.0, &range.1)? {
                continue;
            }
        }
        out.push(range);
    }
    Ok(out)
}

pub(crate) fn merge_adjacent_raw_page_labels(
    ranges: Vec<RawPageLabelEntry>,
) -> Result<Vec<RawPageLabelEntry>> {
    let mut out: Vec<RawPageLabelEntry> = Vec::with_capacity(ranges.len());
    for range in ranges {
        if let Some(previous) = out.last() {
            let redundant = raw_page_labels_are_redundant(
                previous.index,
                &previous.label,
                range.index,
                &range.label,
            )?; // cov:ignore: raw label accessor failures are covered by handle tests
            if redundant {
                continue;
            }
        }
        out.push(range);
    }
    Ok(out)
}

/// Copy raw label dictionaries into the destination document through its
/// qpdf-shaped persistent foreign-object map.
///
/// Provenance registration is deliberately *not* done here — see
/// [`record_primary_label_provenance`], which the page-selection callers run
/// once after this loop.
pub(crate) fn copy_raw_page_label_entries<R: Read + Seek>(
    target: &mut Pdf<R>,
    ranges: &[RawPageLabelEntry],
) -> Result<Vec<(i64, ObjectHandle)>> {
    ranges
        .iter()
        .map(|range| {
            let label = if range.source_is_primary {
                target.copy_foreign_value(range.source_id, &range.label)?
            } else {
                // qpdf builds a new direct label dictionary: direct scalar
                // values are independent, while indirect /S or /P handles
                // remain foreign and are rejected by the destination writer.
                range.label.shallow_copy()?
            };
            Ok((range.index, label))
        })
        .collect()
}

/// Register the primary source's foreign-object map for QDF provenance, once
/// per distinct primary source.
///
/// qpdf's `--pages .` form keeps the primary `QPDF` itself as the destination
/// (`libqpdf/QPDFJob.cc:2511-2593`), so `QPDFWriter` emits the source ObjGen
/// in `%% Original object ID` (`libqpdf/QPDFWriter.cc:1786`). Only callers on
/// that primary-owner path may register it; a caller that models
/// `emptyPDF()` plus foreign `addPage` must not, because there qpdf writes the
/// destination ObjGen instead.
///
/// Runs after the whole copy loop rather than inside it: each call walks the
/// entire persistent foreign-object map, so per-range registration would be
/// quadratic in `label_count x copied_object_count`.
pub(crate) fn record_primary_label_provenance<R: Read + Seek>(
    target: &mut Pdf<R>,
    ranges: &[RawPageLabelEntry],
) {
    let mut recorded = BTreeSet::new();
    for range in ranges.iter().filter(|range| range.source_is_primary) {
        if recorded.insert(range.source_id) {
            target.record_primary_writer_object_refs(range.source_id);
        }
    }
}

/// High-level helper for a document's `/PageLabels` number tree.
///
/// Construct with [`PageLabelDocumentHelper::new`] or [`Pdf::page_labels`]. The
/// helper caches nothing; methods re-read the live document.
pub struct PageLabelDocumentHelper<'a, R: Read + Seek + 'static> {
    pdf: &'a mut Pdf<R>,
}

impl<'a, R: Read + Seek> PageLabelDocumentHelper<'a, R> {
    /// Create a new helper borrowing `pdf` mutably.
    pub fn new(pdf: &'a mut Pdf<R>) -> Self {
        Self { pdf }
    }

    /// Return the live catalog `/PageLabels` value from the canonical handle
    /// graph. Values that resolve to null are absent, matching qpdf's
    /// `QPDF_Dictionary::hasKey` visibility rule.
    fn pagelabels_root_handle(&mut self) -> Result<Option<ObjectHandle>> {
        let catalog = self.pdf.root_handle()?;
        // qpdf's QPDF_Dictionary::hasKey hides values that are null, including
        // an indirect reference that resolves to null (QPDF_Dictionary.cc:98-101).
        if !catalog.try_has_key(b"/PageLabels")? {
            return Ok(None);
        }
        Ok(Some(catalog.try_get_key(b"/PageLabels")?))
    }

    fn pagelabels_tree(&mut self) -> Result<Option<crate::nntree::NumberTree>> {
        let Some(root) = self.pagelabels_root_handle()? else {
            return Ok(None);
        };
        let mut tree = crate::nntree::NumberTree::new(root, true);
        tree.set_max_depth(DEFAULT_MAX_TREE_DEPTH);
        Ok(Some(tree))
    }

    /// Whether the document carries a `/PageLabels` tree with at least the root.
    ///
    /// # Errors
    ///
    /// - Any error from canonical ObjectHandle resolution.
    pub fn has_page_labels(&mut self) -> Result<bool> {
        Ok(self.pagelabels_root_handle()?.is_some())
    }

    /// Build qpdf's direct label dictionary for a numbering style, starting
    /// value, and optional prefix (`pageLabelDict`).
    pub fn page_label_dict(style: LabelStyle, start_num: i64, prefix: &str) -> ObjectHandle {
        Self::page_label_dict_bytes(style, start_num, prefix.as_bytes())
    }

    /// Build qpdf's direct label dictionary from the original byte prefix.
    /// qpdf's `newUnicodeString(std::string_view)` receives the option/Config
    /// bytes without a UTF-8 projection, so the Job transformation path uses
    /// this byte-preserving form for `/P`.
    pub fn page_label_dict_bytes(style: LabelStyle, start_num: i64, prefix: &[u8]) -> ObjectHandle {
        let result = ObjectHandle::dictionary(Vec::new());
        if let Some(name) = style.to_name() {
            result
                .replace_key(b"/S", ObjectHandle::name(name.as_bytes().to_vec()))
                .expect("new direct page-label dictionary is unowned");
        }
        if !prefix.is_empty() {
            let bytes = crate::pdf_string::new_unicode_string(prefix);
            result
                .replace_key(b"/P", ObjectHandle::string(bytes))
                .expect("new direct page-label dictionary is unowned");
        }
        if start_num != 1 {
            result
                .replace_key(b"/St", ObjectHandle::integer(start_num))
                .expect("new direct page-label dictionary is unowned");
        }
        result
    }

    fn reconstructed_label_handle(
        range: &LabelRange,
        prefix_present: bool,
    ) -> Result<ObjectHandle> {
        let result = Self::page_label_dict(range.style, range.start, &range.prefix);
        if prefix_present && range.prefix.is_empty() {
            result.replace_key(b"/P", ObjectHandle::string(Vec::new()))?;
        }
        result.replace_key(b"/St", ObjectHandle::integer(range.start))?;
        Ok(result)
    }

    /// All label ranges as `(first_page_index, LabelRange)`, ascending by index.
    /// Empty when `/PageLabels` is absent.
    ///
    /// # Errors
    ///
    /// - [`crate::Error::Unsupported`] when the number-tree depth limit is
    ///   exceeded.
    /// - Any error from canonical ObjectHandle resolution.
    pub fn ranges(&mut self) -> Result<Vec<(i64, LabelRange)>> {
        let Some(mut tree) = self.pagelabels_tree()? else {
            return Ok(vec![]);
        };
        let raw_entries = tree.as_map(self.pdf)?;
        let mut entries = Vec::with_capacity(raw_entries.len());
        for (index, value) in raw_entries {
            if let Some(range) = LabelRange::from_handle(&value)? {
                entries.push((index, range));
            }
        }
        Ok(entries)
    }

    /// The effective label for a 0-based page index (qpdf `getLabelForPage`):
    /// the range whose first index is the largest `<= page_idx`, with `start`
    /// offset to that page. `None` when no range applies (no `/PageLabels`, or
    /// the page precedes the first range).
    ///
    /// # Errors
    ///
    /// - [`crate::Error::Unsupported`] when the number-tree depth limit is
    ///   exceeded.
    /// - Any error from canonical ObjectHandle resolution.
    pub fn label_for_page(&mut self, page_idx: i64) -> Result<Option<LabelRange>> {
        let Some(label) = self.get_label_for_page(page_idx)? else {
            return Ok(None);
        };
        LabelRange::from_handle(&label)
    }

    /// Return qpdf's raw reconstructed label dictionary for a 0-based page
    /// index. The returned direct dictionary always contains `/St`; `/S` and
    /// `/P` retain the source handles' exact presence, absence, and values.
    ///
    /// This is qpdf `getLabelForPage`: an unknown `/S` name and an explicit
    /// empty `/P ()` are preserved rather than normalized into [`LabelRange`].
    ///
    /// # Errors
    ///
    /// Returns errors from canonical object resolution, number-tree traversal,
    /// or checked `/St` offset arithmetic.
    pub fn get_label_for_page(&mut self, page_idx: i64) -> Result<Option<ObjectHandle>> {
        let Some(mut tree) = self.pagelabels_tree()? else {
            return Ok(None);
        };
        self.get_label_for_page_from_tree(&mut tree, page_idx)
    }

    /// Append qpdf's reconstructed label entries for an inclusive source page
    /// range to `labels`.
    ///
    /// Each tuple is `(new_page_index, raw_label_dictionary)`. The first entry
    /// is fabricated with `/St = new_start_idx + 1` when no effective source
    /// label exists. Existing trailing entries are checked using qpdf's raw
    /// `/S`/`/P`/`/St` redundancy rule before the first entry is appended.
    ///
    /// This is qpdf `getLabelsForPageRange`; callers may invoke it repeatedly
    /// for multiple input documents and preserve the accumulated vector.
    ///
    /// # Errors
    ///
    /// Returns errors from canonical object resolution, number-tree traversal,
    /// or checked index arithmetic.
    pub fn get_labels_for_page_range(
        &mut self,
        start_idx: i64,
        end_idx: i64,
        new_start_idx: i64,
        labels: &mut Vec<(i64, ObjectHandle)>,
    ) -> Result<()> {
        let idx_offset = new_start_idx
            .checked_sub(start_idx)
            .ok_or_else(|| Error::Unsupported("page label index offset overflow".to_string()))?;
        let mut tree = self.pagelabels_tree()?;
        let first_label = match tree.as_mut() {
            Some(tree) => self
                .get_label_for_page_from_tree(tree, start_idx)?
                .unwrap_or_else(|| ObjectHandle::dictionary(Vec::new())),
            None => ObjectHandle::dictionary(Vec::new()),
        };
        if !first_label.try_has_key(b"/St")? {
            let default_start = new_start_idx.checked_add(1).ok_or_else(|| {
                Error::Unsupported("page label fabricated start overflow".to_string())
            })?;
            first_label.replace_key(b"/St", ObjectHandle::integer(default_start))?;
        }

        let skip_first = if let Some((last_index, last_label)) = labels.last() {
            if last_label.try_is_dictionary()? && first_label.try_is_dictionary()? {
                let last_s = last_label.try_get_key(b"/S")?;
                let first_s = first_label.try_get_key(b"/S")?;
                let last_p = last_label.try_get_key(b"/P")?;
                let first_p = first_label.try_get_key(b"/P")?;
                let last_st = last_label.try_get_key(b"/St")?.try_as_integer()?;
                let first_st = first_label.try_get_key(b"/St")?.try_as_integer()?;
                let idx_delta = new_start_idx.checked_sub(*last_index);
                let st_delta = first_st
                    .and_then(|first_st| last_st.and_then(|last_st| first_st.checked_sub(last_st)));
                idx_delta.zip(st_delta).is_some_and(|(idx, st)| {
                    idx == st
                        && last_s.unparse() == first_s.unparse()
                        && last_p.unparse() == first_p.unparse()
                })
            } else {
                false
            }
        } else {
            false
        };
        if !skip_first {
            labels.push((new_start_idx, first_label));
        }

        if let Some(tree) = tree.as_mut() {
            let mut source_idx = start_idx;
            while source_idx < end_idx {
                source_idx = source_idx.checked_add(1).ok_or_else(|| {
                    // cov:ignore-start: source_idx < end_idx and end_idx is an i64, so incrementing cannot overflow.
                    Error::Unsupported("page label source index overflow".to_string())
                })?; // cov:ignore-end
                if !tree.has_index(self.pdf, source_idx)? {
                    continue;
                }
                let Some(label) = self.get_label_for_page_from_tree(tree, source_idx)? else {
                    continue;
                };
                let output_idx = source_idx.checked_add(idx_offset).ok_or_else(|| {
                    Error::Unsupported("page label output index overflow".to_string())
                })?;
                labels.push((output_idx, label));
            }
        }
        Ok(())
    }

    fn get_label_for_page_from_tree(
        &mut self,
        tree: &mut crate::nntree::NumberTree,
        page_idx: i64,
    ) -> Result<Option<ObjectHandle>> {
        let Some((label, offset)) = tree.find_object_at_or_below(self.pdf, page_idx)? else {
            return Ok(None);
        };
        label.try_dereference()?;
        if !label.try_is_dictionary()? {
            return Ok(None);
        }

        let start = label
            .try_get_key(b"/St")?
            .try_as_integer()?
            .unwrap_or(1)
            .checked_add(offset)
            .ok_or_else(|| Error::Unsupported("page label /St offset overflow".to_string()))?;
        let result = ObjectHandle::dictionary(Vec::new());
        result.replace_key(b"/S", label.try_get_key(b"/S")?)?;
        result.replace_key(b"/P", label.try_get_key(b"/P")?)?;
        result.replace_key(b"/St", ObjectHandle::integer(start))?;
        Ok(Some(result))
    }

    /// qpdf `getLabelsForPageRange` compatibility view: collect the label entries needed to
    /// reproduce the labels of pages `start_idx..=end_idx` if they were
    /// renumbered to begin at `new_start_idx`. Returns `(new_index, LabelRange)`
    /// pairs (the first entry plus every explicit entry in the source range),
    /// renumbered by `new_start_idx - start_idx`. Read-only; intended for
    /// page-extraction/subsetting call sites that reconstruct a document's
    /// `/PageLabels` for a new page range (pair with
    /// [`PageLabelDocumentHelper::write_reconstructed_labels`]).
    ///
    /// `start_idx` must be `<= end_idx`. An inverted span (`start_idx >
    /// end_idx`) is a caller bug: this returns only the first-page label
    /// with no explicit-range entries, matching an empty-span read; it does
    /// not panic. `start_idx == end_idx` denotes a single-page span.
    ///
    /// `new_start_idx` is expected to be a valid page-index-shaped value
    /// (typically `0..page_count`). Arithmetic that cannot be represented as
    /// an `i64` returns [`crate::Error::Unsupported`].
    ///
    /// Unlike qpdf's accumulating signature, this is a single self-contained
    /// call: the leading entry is always emitted (the result vector starts
    /// empty, so there is no prior entry to be redundant against). A later
    /// accumulating consumer can dedupe across calls.
    ///
    /// Traverses the `/PageLabels` tree once for this call and keeps raw
    /// dictionary handles until the typed compatibility view is built.
    ///
    /// # Errors
    ///
    /// - [`crate::Error::Unsupported`] when the number-tree depth limit is
    ///   exceeded.
    /// - Any error from canonical ObjectHandle resolution.
    #[cfg(test)]
    pub fn labels_for_page_range(
        &mut self,
        start_idx: i64,
        end_idx: i64,
        new_start_idx: i64,
    ) -> Result<Vec<(i64, LabelRange)>> {
        // debug_assert catches an inverted span (a caller bug per the doc
        // contract) in dev/tests. Release keeps the graceful empty-span
        // behavior documented above.
        debug_assert!(
            start_idx <= end_idx,
            "labels_for_page_range: inverted span (start={start_idx}, end={end_idx})",
        );
        let mut raw_labels = Vec::new();
        self.get_labels_for_page_range(start_idx, end_idx, new_start_idx, &mut raw_labels)?;
        raw_labels
            .into_iter()
            .map(|(index, label)| {
                LabelRange::from_handle(&label)?
                    .map(|label| (index, label))
                    .ok_or_else(|| {
                        // cov:ignore-start: get_labels_for_page_range only stores direct dictionary handles in raw_labels.
                        Error::Unsupported("page label range is not a dictionary".to_string())
                    }) // cov:ignore-end
            })
            .collect()
    }

    /// Batch typed compatibility view for inspection callers. Page-job
    /// reconstruction uses the raw canonical route internally so `/S` and `/P`
    /// handles retain qpdf's exact presence and value semantics.
    ///
    /// # Errors
    ///
    /// - [`crate::Error::Unsupported`] when the number-tree depth limit is
    ///   exceeded while reading the existing tree.
    /// - Any error from canonical ObjectHandle resolution.
    pub fn labels_for_selection(
        &mut self,
        src_indices: &[i64],
        out_start_idx: i64,
    ) -> Result<Vec<(i64, LabelRange)>> {
        self.labels_for_selection_raw(src_indices, out_start_idx)?
            .into_iter()
            .map(|(index, label)| {
                LabelRange::from_handle(&label)?
                    .map(|label| (index, label))
                    .ok_or_else(|| {
                        // cov:ignore-start: labels_for_selection_raw always emits dictionaries.
                        Error::Unsupported("page label selection is not a dictionary".to_string())
                    }) // cov:ignore-end
            })
            .collect()
    }

    /// Batch variant of [`Self::labels_for_selection`] that also returns
    /// whether each effective label dictionary carries an explicit `/P` key.
    ///
    /// The raw label lookup and the typed [`LabelRange`] projection happen in
    /// one pass. Callers that need to preserve the distinction between an
    /// absent prefix and an explicit empty `/P ()` should use this method so
    /// they do not traverse the number tree again for each selected page.
    /// This follows qpdf's `getLabelForPage` raw-dictionary construction
    /// (`QPDFPageLabelDocumentHelper.cc:23-51`), which retains `/P` key
    /// presence while projecting the effective `/St` value.
    #[cfg(test)]
    pub fn labels_for_selection_with_prefix_presence(
        &mut self,
        src_indices: &[i64],
        out_start_idx: i64,
    ) -> Result<Vec<(i64, LabelRange, bool)>> {
        let mut tree = self.pagelabels_tree()?;
        let mut out = Vec::with_capacity(src_indices.len());
        for (i, &src_idx) in src_indices.iter().enumerate() {
            let out_idx = out_start_idx
                .checked_add(i64::try_from(i).map_err(|_| {
                    // cov:ignore-start: supported 64-bit targets cannot allocate a slice with more than i64::MAX elements.
                    Error::Unsupported("page label selection index overflow".to_string())
                })?) // cov:ignore-end
                .ok_or_else(|| {
                    Error::Unsupported("page label output index overflow".to_string())
                })?;
            let label = match tree.as_mut() {
                Some(tree) => self.get_label_for_page_from_tree(tree, src_idx)?,
                None => None,
            };
            let (label, prefix_present) = match label {
                Some(label) => {
                    let prefix_present = label.try_has_key(b"/P")?;
                    let label = LabelRange::from_handle(&label)?.ok_or_else(|| {
                        // cov:ignore-start: get_label_for_page_from_tree returns Some only for a dictionary handle.
                        Error::Unsupported("page label range is not a dictionary".to_string())
                    })?; // cov:ignore-end
                    (label, prefix_present)
                }
                None => (
                    LabelRange {
                        style: LabelStyle::None,
                        prefix: String::new(),
                        start: out_idx.checked_add(1).ok_or_else(|| {
                            Error::Unsupported("page label fabricated start overflow".to_string())
                        })?,
                    },
                    false,
                ),
            };
            out.push((out_idx, label, prefix_present));
        }
        Ok(out)
    }

    /// Batch raw variant of [`Self::labels_for_selection`]. The returned
    /// dictionaries retain arbitrary `/S` and `/P` values so page-job
    /// reconstruction can copy them exactly like qpdf.
    pub(crate) fn labels_for_selection_raw(
        &mut self,
        src_indices: &[i64],
        out_start_idx: i64,
    ) -> Result<Vec<(i64, ObjectHandle)>> {
        let mut tree = self.pagelabels_tree()?;
        let mut out = Vec::with_capacity(src_indices.len());
        for (i, &src_idx) in src_indices.iter().enumerate() {
            let i = i64::try_from(i).map_err(|_| {
                // cov:ignore-start: supported targets cannot allocate more than i64::MAX items.
                Error::Unsupported("page label selection index overflow".to_string())
                // cov:ignore-end
            })?; // cov:ignore: the same allocation bound is unrepresentable on supported targets
            let out_idx = out_start_idx.checked_add(i).ok_or_else(|| {
                Error::Unsupported("page label output index overflow".to_string())
            })?;
            let label = match tree.as_mut() {
                Some(tree) => self.get_label_for_page_from_tree(tree, src_idx)?,
                None => None,
            }
            .unwrap_or_else(|| ObjectHandle::dictionary(Vec::new()));
            if !label.try_has_key(b"/St")? {
                label.replace_key(
                    b"/St",
                    ObjectHandle::integer(out_idx.checked_add(1).ok_or_else(|| {
                        Error::Unsupported("page label fabricated start overflow".to_string())
                    })?),
                )?; // cov:ignore: the catalog was validated as a dictionary and this local replacement has no qpdf failure branch
            }
            out.push((out_idx, label));
        }
        Ok(out)
    }

    /// Return whether the effective label dictionary for `page_idx` carries
    /// an explicit `/P` key, including an explicitly empty string. qpdf keeps
    /// that distinction when `getLabelsForPageRange` copies raw label
    /// dictionaries; the JSON representation renders an empty Unicode prefix
    /// as `u:` while an absent prefix is omitted.
    #[cfg(test)]
    pub fn label_prefix_is_present(&mut self, page_idx: i64) -> Result<bool> {
        let Some(mut tree) = self.pagelabels_tree()? else {
            return Ok(false);
        };
        let Some(label) = self.get_label_for_page_from_tree(&mut tree, page_idx)? else {
            return Ok(false);
        };
        label.try_has_key(b"/P")
    }

    /// Install `entries` as the catalog's `/PageLabels`: a direct
    /// (non-indirect) `<< /Nums [...] >>` dictionary — never a balanced
    /// number tree — with each entry's label dictionary built in the same
    /// shape qpdf's `getLabelForPage` reconstruction uses (`/S` iff the style
    /// is not [`LabelStyle::None`], `/P` iff the prefix is non-empty, `/St`
    /// always present).
    ///
    /// This is the shape qpdf produces when reconstructing labels for a page
    /// subset or split (`QPDFJob::handlePageSpecs`, `QPDFJob::doSplitPages`):
    /// it always unconditionally replaces the catalog's `/PageLabels` with a
    /// freshly built flat array — never merging with, or preserving the
    /// shape of, any prior value. Pair with [`Self::label_for_page`] or a
    /// caller-provided typed compatibility view, which produce the `entries`
    /// this expects.
    ///
    /// The catalog is resolved through qpdf's `QPDF::getRoot`-shaped
    /// dictionary gate, so a missing, dangling, or non-dictionary `/Root` is
    /// an error rather than a silent no-op.
    ///
    /// # Errors
    ///
    /// Any error from canonical ObjectHandle resolution, including qpdf's
    /// `unable to find /Root dictionary` error.
    pub fn write_reconstructed_labels(&mut self, entries: &[(i64, LabelRange)]) -> Result<()> {
        let catalog = self.pdf.root_handle()?;
        let mut nums = Vec::with_capacity(entries.len() * 2);
        for (idx, range) in entries {
            nums.push(ObjectHandle::integer(*idx));
            nums.push(Self::reconstructed_label_handle(range, false)?);
        }
        let page_labels =
            ObjectHandle::dictionary(vec![(b"/Nums".to_vec(), ObjectHandle::array(nums))]);
        catalog.replace_key(b"/PageLabels", page_labels)?;
        Ok(())
    }

    /// Install reconstructed labels while retaining whether the source had an
    /// explicit empty `/P` prefix. This is the raw-handle distinction qpdf's
    /// `getLabelsForPageRange` preserves and the compact [`LabelRange`] value
    /// intentionally does not expose in its public three-field shape.
    #[cfg(test)]
    pub fn write_reconstructed_labels_with_prefix_presence(
        &mut self,
        entries: &[(i64, LabelRange, bool)],
    ) -> Result<()> {
        let catalog = self.pdf.root_handle()?;
        let mut nums = Vec::with_capacity(entries.len() * 2);
        for (idx, range, prefix_present) in entries {
            nums.push(ObjectHandle::integer(*idx));
            nums.push(Self::reconstructed_label_handle(range, *prefix_present)?);
        }
        let page_labels =
            ObjectHandle::dictionary(vec![(b"/Nums".to_vec(), ObjectHandle::array(nums))]);
        catalog.replace_key(b"/PageLabels", page_labels)?;
        Ok(())
    }

    /// Install already destination-owned raw label dictionaries. This is the
    /// qpdf reconstruction boundary; unlike the typed writer, it does not
    /// manufacture a string `/P` for a non-string source value.
    pub(crate) fn write_reconstructed_labels_raw(
        &mut self,
        entries: &[(i64, ObjectHandle)],
    ) -> Result<()> {
        let catalog = self.pdf.root_handle()?;
        let mut nums = Vec::with_capacity(entries.len() * 2);
        for (index, label) in entries {
            nums.push(ObjectHandle::integer(*index));
            nums.push(label.clone());
        }
        let page_labels =
            ObjectHandle::dictionary(vec![(b"/Nums".to_vec(), ObjectHandle::array(nums))]);
        catalog.replace_key(b"/PageLabels", page_labels)?;
        Ok(())
    }
}

/// Extension constructor mirroring [`Pdf::acroform`].
impl<R: Read + Seek> Pdf<R> {
    /// Return a high-level page-label helper for this document.
    pub fn page_labels(&mut self) -> PageLabelDocumentHelper<'_, R> {
        PageLabelDocumentHelper::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::json::Json;
    use crate::ObjectRef;
    use std::io::Cursor;

    #[test]
    fn label_range_propagates_an_unresolved_handle_error() {
        let handle = ObjectHandle::new_indirect_unresolved(ObjectRef::new(99, 0), -1);
        let error = LabelRange::from_handle(&handle).unwrap_err();
        assert!(matches!(
            error,
            Error::Internal(ref message) if message == "object 99 0 belongs to a dropped PDF"
        ));
    }

    /// `QPDFPageLabelDocumentHelper::getLabelForPage` reads `/P` with a plain
    /// `label.getKey("/P")` and copies it into the result untouched
    /// (`QPDFPageLabelDocumentHelper.cc:38,48`), so a non-string prefix raises
    /// no diagnostic. Probed with qpdf 11.9.0 on `/P 42`, `/P /Foo` and
    /// `/P [1 2]`: `--pages . 1-2 --` exits 0 with empty stderr for all three.
    /// Reading through `try_get_string_value` instead would emit qpdf's
    /// "operation for string attempted on object of type integer" warning and
    /// turn the run into exit 3.
    #[test]
    fn non_string_prefix_decodes_to_empty_without_a_type_warning() {
        for prefix in [
            ObjectHandle::integer(42),
            ObjectHandle::name(b"Foo".to_vec()),
            ObjectHandle::array(vec![ObjectHandle::integer(1)]),
        ] {
            let label = ObjectHandle::dictionary(vec![
                (b"/S".to_vec(), ObjectHandle::name(b"D".to_vec())),
                (b"/P".to_vec(), prefix),
            ]);
            let range = LabelRange::from_handle(&label)
                .expect("a non-string prefix must not raise a type warning")
                .expect("the label is a dictionary");
            assert_eq!(range.prefix, "");
        }
    }

    /// A minimal one-page PDF with no `/PageLabels` key at all (as opposed to
    /// [`pdf_with_pagelabels`], whose catalog always carries `/PageLabels`,
    /// even when `/Nums` is empty).
    fn bare_one_page_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"%PDF-1.7\n");
        let off1 = bytes.len() as u64;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = bytes.len() as u64;
        bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = bytes.len() as u64;
        bytes.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref = bytes.len() as u64;
        bytes.extend_from_slice(
            format!(
                "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        Pdf::open(Cursor::new(bytes)).expect("open")
    }

    /// A minimal one-page PDF whose trailer contains the Catalog directly in
    /// `/Root`, matching qpdf's accepted direct-root form.
    fn direct_root_one_page_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"%PDF-1.4\n");
        let off1 = bytes.len() as u64;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Pages /Count 1 /Kids [2 0 R] >>\nendobj\n");
        let off2 = bytes.len() as u64;
        bytes.extend_from_slice(
            b"2 0 obj\n<< /Type /Page /Parent 1 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref = bytes.len() as u64;
        bytes.extend_from_slice(
            format!(
                "xref\n0 3\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \ntrailer\n<< /Size 3 /Root << /Type /Catalog /Pages 1 0 R >> >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        Pdf::open(Cursor::new(bytes)).expect("open direct-root fixture")
    }

    fn install_page_labels(pdf: &mut Pdf<Cursor<Vec<u8>>>, value: ObjectHandle) {
        let catalog_ref = pdf.root_ref().expect("one-page fixture has a catalog root");
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_is_scalar().expect("resolve catalog");
        catalog
            .replace_key(b"/PageLabels", value)
            .expect("install catalog page labels");
    }

    fn pdf_with_pagelabels(nums: Vec<ObjectHandle>) -> Pdf<Cursor<Vec<u8>>> {
        // Minimal one-page PDF; then attach an indirect /PageLabels leaf via
        // the canonical handle allocation and catalog mutation boundary.
        let mut pdf = bare_one_page_pdf();
        let leaf = ObjectHandle::dictionary(vec![(b"/Nums".to_vec(), ObjectHandle::array(nums))]);
        let leaf = pdf
            .make_indirect_from_object_handle(leaf)
            .expect("promote page-label leaf");
        install_page_labels(&mut pdf, leaf);
        pdf
    }

    fn pdf_with_catalog_pagelabels(value: ObjectHandle) -> Pdf<Cursor<Vec<u8>>> {
        let mut pdf = bare_one_page_pdf();
        install_page_labels(&mut pdf, value);
        pdf
    }

    fn label_dict(style: &str, st: Option<i64>, prefix: Option<&str>) -> ObjectHandle {
        let mut entries = vec![(
            b"/S".to_vec(),
            ObjectHandle::name(style.as_bytes().to_vec()),
        )];
        if let Some(s) = st {
            entries.push((b"/St".to_vec(), ObjectHandle::integer(s)));
        }
        if let Some(p) = prefix {
            entries.push((b"/P".to_vec(), ObjectHandle::string(p.as_bytes().to_vec())));
        }
        ObjectHandle::dictionary(entries)
    }

    #[test]
    fn ranges_reads_a_valid_indirect_tree() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), None),
        ]);
        let ranges = pdf.page_labels().ranges().expect("read ranges");

        assert_eq!(ranges.len(), 1);
    }

    #[test]
    fn label_for_page_offsets_start() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(10), None),
        ]);
        let mut h = pdf.page_labels();
        let lab = h.label_for_page(2).unwrap().expect("range applies");
        assert_eq!(lab.start, 12, "/St 10 + offset 2");
        assert_eq!(lab.style, LabelStyle::Decimal);
    }

    #[test]
    fn get_label_for_page_preserves_qpdf_raw_dictionary_keys() {
        let unknown_with_empty_prefix = ObjectHandle::dictionary(vec![
            (b"/S".to_vec(), ObjectHandle::name(b"Z".to_vec())),
            (b"/P".to_vec(), ObjectHandle::string(Vec::new())),
            (b"/St".to_vec(), ObjectHandle::integer(3)),
        ]);
        let decimal_without_prefix =
            ObjectHandle::dictionary(vec![(b"/S".to_vec(), ObjectHandle::name(b"D".to_vec()))]);

        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            unknown_with_empty_prefix,
            ObjectHandle::integer(2),
            decimal_without_prefix,
        ]);
        let mut h = pdf.page_labels();

        let unknown = h
            .get_label_for_page(1)
            .unwrap()
            .expect("unknown style range applies");
        assert_eq!(
            unknown.try_get_key(b"/S").unwrap().try_as_name().unwrap(),
            Some(b"Z".to_vec())
        );
        assert!(unknown.try_has_key(b"/P").unwrap(), "empty /P is present");
        assert_eq!(
            unknown.try_get_key(b"/P").unwrap().as_string(),
            Some(vec![])
        );
        assert_eq!(unknown.try_get_key(b"/St").unwrap().as_integer(), Some(4));

        let decimal = h
            .get_label_for_page(2)
            .unwrap()
            .expect("decimal range applies");
        assert_eq!(
            decimal.try_get_key(b"/S").unwrap().try_as_name().unwrap(),
            Some(b"D".to_vec())
        );
        assert!(
            !decimal.try_has_key(b"/P").unwrap(),
            "absent /P stays absent"
        );
        assert_eq!(decimal.try_get_key(b"/St").unwrap().as_integer(), Some(1));
    }

    #[test]
    fn get_label_for_page_preserves_indirect_member_identity() {
        let mut pdf = bare_one_page_pdf();
        let label = pdf
            .make_indirect_from_object_handle(label_dict("D", None, Some("prefix")))
            .expect("promote label dictionary");
        let leaf = ObjectHandle::dictionary(vec![(
            b"/Nums".to_vec(),
            ObjectHandle::array(vec![ObjectHandle::integer(0), label.clone()]),
        )]);
        let leaf = pdf
            .make_indirect_from_object_handle(leaf)
            .expect("promote page-label leaf");
        install_page_labels(&mut pdf, leaf);

        let source = label.clone();
        source.try_is_scalar().unwrap();
        let source_style = source.try_get_key(b"/S").unwrap();
        let source_prefix = source.try_get_key(b"/P").unwrap();

        let mut helper = pdf.page_labels();
        let result = helper
            .get_label_for_page(0)
            .unwrap()
            .expect("label dictionary");

        assert!(result
            .try_get_key(b"/S")
            .unwrap()
            .is_same_object_as(&source_style));
        assert!(result
            .try_get_key(b"/P")
            .unwrap()
            .is_same_object_as(&source_prefix));
    }

    #[test]
    fn page_label_dict_matches_qpdf_factory_shape() {
        let label = PageLabelDocumentHelper::<Cursor<Vec<u8>>>::page_label_dict(
            LabelStyle::AlphaUpper,
            3,
            "§",
        );
        assert_eq!(
            label.try_get_key(b"/S").unwrap().try_as_name().unwrap(),
            Some(b"A".to_vec())
        );
        assert_eq!(
            label.try_get_key(b"/P").unwrap().as_string(),
            Some(vec![0xa7])
        );
        assert_eq!(label.try_get_key(b"/St").unwrap().as_integer(), Some(3));

        let ascii_prefix = PageLabelDocumentHelper::<Cursor<Vec<u8>>>::page_label_dict(
            LabelStyle::Decimal,
            1,
            "A-",
        );
        assert_eq!(
            ascii_prefix.try_get_key(b"/P").unwrap().as_string(),
            Some(b"A-".to_vec())
        );

        let default =
            PageLabelDocumentHelper::<Cursor<Vec<u8>>>::page_label_dict(LabelStyle::None, 1, "");
        assert!(!default.try_has_key(b"/S").unwrap());
        assert!(!default.try_has_key(b"/P").unwrap());
        assert!(!default.try_has_key(b"/St").unwrap());
    }

    #[test]
    fn get_labels_for_page_range_accumulates_effective_raw_entries() {
        let empty_prefix = ObjectHandle::dictionary(vec![
            (b"/S".to_vec(), ObjectHandle::name(b"D".to_vec())),
            (b"/P".to_vec(), ObjectHandle::string(Vec::new())),
        ]);
        let decimal = ObjectHandle::dictionary(vec![
            (b"/S".to_vec(), ObjectHandle::name(b"D".to_vec())),
            (b"/St".to_vec(), ObjectHandle::integer(10)),
        ]);

        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("r", None, None),
            ObjectHandle::integer(2),
            empty_prefix,
            ObjectHandle::integer(4),
            decimal,
        ]);
        let mut h = pdf.page_labels();
        let mut labels = Vec::new();
        h.get_labels_for_page_range(1, 4, 0, &mut labels).unwrap();

        assert_eq!(labels.len(), 3);
        assert_eq!(labels[0].0, 0);
        assert_eq!(
            labels[0]
                .1
                .try_get_key(b"/S")
                .unwrap()
                .try_as_name()
                .unwrap(),
            Some(b"r".to_vec())
        );
        assert_eq!(
            labels[0].1.try_get_key(b"/St").unwrap().as_integer(),
            Some(2)
        );
        assert_eq!(labels[1].0, 1);
        assert!(labels[1].1.try_has_key(b"/P").unwrap());
        assert_eq!(
            labels[1].1.try_get_key(b"/St").unwrap().as_integer(),
            Some(1)
        );
        assert_eq!(labels[2].0, 3);
        assert_eq!(
            labels[2].1.try_get_key(b"/St").unwrap().as_integer(),
            Some(10)
        );
    }

    #[test]
    fn get_labels_for_page_range_skips_redundant_accumulated_leading_entry() {
        let mut pdf =
            pdf_with_pagelabels(vec![ObjectHandle::integer(0), label_dict("D", None, None)]);
        let mut h = pdf.page_labels();
        let prior =
            PageLabelDocumentHelper::<Cursor<Vec<u8>>>::page_label_dict(LabelStyle::Decimal, 1, "");
        prior.replace_key(b"/St", ObjectHandle::integer(1)).unwrap();
        let mut labels = vec![(0, prior)];

        h.get_labels_for_page_range(1, 1, 1, &mut labels).unwrap();

        assert_eq!(labels.len(), 1, "the leading continuation is redundant");
    }

    #[test]
    fn get_labels_for_page_range_handles_missing_tree_and_non_dictionary_prior() {
        let mut pdf = bare_one_page_pdf();
        let mut h = pdf.page_labels();
        let mut labels = vec![(0, ObjectHandle::integer(0))];

        h.get_labels_for_page_range(0, 0, 0, &mut labels).unwrap();

        assert_eq!(labels.len(), 2);
        assert_eq!(labels[1].0, 0);
        assert_eq!(
            labels[1].1.try_get_key(b"/St").unwrap().as_integer(),
            Some(1)
        );
    }

    #[test]
    fn get_labels_for_page_range_rejects_fabricated_start_overflow() {
        let mut pdf = bare_one_page_pdf();
        let error = pdf
            .page_labels()
            .get_labels_for_page_range(i64::MAX, i64::MAX, i64::MAX, &mut Vec::new())
            .expect_err("fabricated /St must use checked arithmetic");
        assert!(error.to_string().contains("fabricated start overflow"));
    }

    #[test]
    fn get_labels_for_page_range_skips_non_dictionary_explicit_entries() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", None, None),
            ObjectHandle::integer(1),
            ObjectHandle::integer(99),
        ]);
        let mut h = pdf.page_labels();
        let mut labels = Vec::new();

        h.get_labels_for_page_range(0, 2, 0, &mut labels).unwrap();

        assert_eq!(
            labels.len(),
            1,
            "a non-dictionary explicit value is skipped"
        );
        assert_eq!(labels[0].0, 0);
    }

    #[test]
    fn get_labels_for_page_range_rejects_output_index_overflow() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), None),
            ObjectHandle::integer(1),
            label_dict("R", Some(1), None),
        ]);
        let error = pdf
            .page_labels()
            .get_labels_for_page_range(0, 2, i64::MAX, &mut Vec::new())
            .expect_err("reconstructed output index must use checked arithmetic");
        assert!(error.to_string().contains("output index overflow"));
    }

    #[test]
    fn labels_for_selection_reconstructs_effective_and_default_ranges() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(5),
            label_dict("R", Some(2), Some("P-")),
        ]);
        let mut h = pdf.page_labels();

        let labels = h.labels_for_selection(&[0, 5, 6], 10).unwrap();

        assert_eq!(labels[0], (10, none_range(11)));
        assert_eq!(
            labels[1],
            (
                11,
                LabelRange {
                    style: LabelStyle::RomanUpper,
                    prefix: "P-".into(),
                    start: 2,
                }
            )
        );
        assert_eq!(
            labels[2],
            (
                12,
                LabelRange {
                    style: LabelStyle::RomanUpper,
                    prefix: "P-".into(),
                    start: 3,
                }
            )
        );
    }

    #[test]
    fn labels_for_selection_with_prefix_presence_preserves_raw_prefix_presence() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), Some("")),
            ObjectHandle::integer(1),
            label_dict("D", Some(1), None),
        ]);
        let labels = pdf
            .page_labels()
            .labels_for_selection_with_prefix_presence(&[0, 1], 0)
            .expect("selection labels with prefix presence");

        assert_eq!(
            labels,
            vec![
                (
                    0,
                    LabelRange {
                        style: LabelStyle::Decimal,
                        prefix: String::new(),
                        start: 1,
                    },
                    true,
                ),
                (
                    1,
                    LabelRange {
                        style: LabelStyle::Decimal,
                        prefix: String::new(),
                        start: 1,
                    },
                    false,
                ),
            ]
        );
    }

    #[test]
    fn labels_for_selection_handles_missing_tree() {
        let mut pdf = bare_one_page_pdf();
        let labels = pdf.page_labels().labels_for_selection(&[0], 0).unwrap();
        assert_eq!(labels, vec![(0, none_range(1))]);
        let raw = pdf.page_labels().labels_for_selection_raw(&[0], 0).unwrap();
        assert_eq!(raw[0].1.try_get_key(b"/St").unwrap().as_integer(), Some(1));
    }

    #[test]
    fn labels_for_selection_rejects_output_index_overflow() {
        let mut pdf =
            pdf_with_pagelabels(vec![ObjectHandle::integer(0), label_dict("D", None, None)]);
        let error = pdf
            .page_labels()
            .labels_for_selection(&[0, 1], i64::MAX)
            .expect_err("selection output index must use checked arithmetic");
        assert!(error.to_string().contains("output index overflow"));

        let error = pdf
            .page_labels()
            .labels_for_selection_raw(&[0, 1], i64::MAX)
            .expect_err("raw selection output index must use checked arithmetic");
        assert!(error
            .to_string()
            .contains("page label output index overflow"));
    }

    #[test]
    fn labels_for_selection_rejects_fabricated_start_overflow() {
        let mut pdf = bare_one_page_pdf();
        let error = pdf
            .page_labels()
            .labels_for_selection(&[0], i64::MAX)
            .expect_err("fabricated selection /St must use checked arithmetic");
        assert!(error.to_string().contains("fabricated start overflow"));

        let error = pdf
            .page_labels()
            .labels_for_selection_raw(&[0], i64::MAX)
            .expect_err("raw fabricated selection /St must use checked arithmetic");
        assert!(error.to_string().contains("fabricated start overflow"));
    }

    #[test]
    fn raw_label_merges_compare_qpdf_values_and_keep_nonredundant_entries() {
        let label = |prefix: ObjectHandle, start| {
            ObjectHandle::dictionary(vec![
                (b"/S".to_vec(), ObjectHandle::name(b"D".to_vec())),
                (b"/P".to_vec(), prefix),
                (b"/St".to_vec(), ObjectHandle::integer(start)),
            ])
        };
        let ranges = vec![
            (0, label(ObjectHandle::integer(42), 1)),
            (1, label(ObjectHandle::integer(42), 2)),
            (2, label(ObjectHandle::name(b"Foo".to_vec()), 3)),
        ];
        let merged = merge_adjacent_raw_labels(ranges).expect("raw merge");
        assert_eq!(merged.len(), 2);

        let kept = merge_adjacent_raw_labels(vec![
            (0, label(ObjectHandle::integer(42), 1)),
            (1, ObjectHandle::dictionary(Vec::new())),
        ])
        .expect("raw merge must keep a label without /St");
        assert_eq!(kept.len(), 2);

        let ranges = vec![
            RawPageLabelEntry {
                index: 0,
                source_id: 1,
                source_is_primary: true,
                label: label(ObjectHandle::integer(42), 1),
            },
            RawPageLabelEntry {
                index: 1,
                source_id: 1,
                source_is_primary: true,
                label: label(ObjectHandle::integer(42), 2),
            },
        ];
        assert_eq!(
            merge_adjacent_raw_page_labels(ranges)
                .expect("raw foreign merge")
                .len(),
            1
        );
    }

    #[test]
    fn get_label_for_page_rejects_checked_start_overflow() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(i64::MAX), None),
        ]);
        let error = pdf
            .page_labels()
            .get_label_for_page(1)
            .expect_err("/St offset must use checked arithmetic");
        assert!(error.to_string().contains("offset overflow"));
    }

    #[test]
    fn get_label_for_page_reports_qpdf_short_number_tree_error() {
        let mut pdf = pdf_with_pagelabels(vec![ObjectHandle::integer(0)]);
        let error = pdf
            .page_labels()
            .get_label_for_page(0)
            .expect_err("qpdf rejects a short /Nums pair during find");
        assert!(error.to_string().contains("items array is too short"));
        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .any(|warning| warning
                .message_string()
                .contains("update ivalue: items array is too short")));
    }

    #[test]
    fn get_label_for_page_ignores_non_dictionary_values() {
        let mut pdf =
            pdf_with_pagelabels(vec![ObjectHandle::integer(0), ObjectHandle::integer(99)]);
        assert!(pdf.page_labels().get_label_for_page(0).unwrap().is_none());
    }

    #[test]
    fn no_pagelabels_defaults_to_decimal() {
        let mut pdf = pdf_with_pagelabels(vec![]); // empty /Nums -> ranges empty
        let mut h = pdf.page_labels();
        assert!(h.ranges().unwrap().is_empty());
        assert!(h.label_for_page(0).unwrap().is_none());
    }

    #[test]
    fn direct_null_page_labels_key_is_absent() {
        let mut pdf = pdf_with_catalog_pagelabels(ObjectHandle::null());
        let mut helper = pdf.page_labels();

        assert!(!helper.has_page_labels().unwrap());
        assert!(helper.get_label_for_page(0).unwrap().is_none());
        assert!(helper.ranges().unwrap().is_empty());
    }

    #[test]
    fn indirect_null_page_labels_key_is_absent() {
        let mut pdf = bare_one_page_pdf();
        let null_handle = pdf
            .make_indirect_from_object_handle(ObjectHandle::null())
            .expect("promote null page-label value");
        install_page_labels(&mut pdf, null_handle);
        let mut helper = pdf.page_labels();

        assert!(!helper.has_page_labels().unwrap());
        assert!(helper.get_label_for_page(0).unwrap().is_none());
        assert!(helper.ranges().unwrap().is_empty());
    }

    #[test]
    fn page_before_first_range_has_no_effective_label() {
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(3),
            label_dict("R", Some(1), None),
        ]);
        let mut h = pdf.page_labels();
        assert!(h.get_label_for_page(0).unwrap().is_none());
        assert!(h.get_label_for_page(3).unwrap().is_some());
    }

    #[test]
    fn labels_for_page_range_renumbers_and_copies_explicit() {
        // ranges at 0 (roman) and 5 (decimal). Extract pages 3..=6 to new_start 0.
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("r", Some(1), None),
            ObjectHandle::integer(5),
            label_dict("D", Some(1), None),
        ]);
        let mut h = pdf.page_labels();
        let out = h.labels_for_page_range(3, 6, 0).unwrap();
        // First page (idx 3) is in the roman range with offset 3 -> start 4.
        assert_eq!(out[0].0, 0);
        assert_eq!(out[0].1.style, LabelStyle::RomanLower);
        assert_eq!(out[0].1.start, 4);
        // Page 5 has an explicit entry -> copied, renumbered to new index 2.
        assert!(out
            .iter()
            .any(|(idx, r)| *idx == 2 && r.style == LabelStyle::Decimal));
    }

    #[test]
    fn ranges_resolves_indirect_inner_st() {
        // Put an indirect /St value in a live label dictionary.
        let mut pdf = bare_one_page_pdf();
        let st = pdf
            .make_indirect_from_object_handle(ObjectHandle::integer(7))
            .expect("promote /St value");
        let label = label_dict("D", None, None);
        label.replace_key(b"/St", st).unwrap();
        let leaf = ObjectHandle::dictionary(vec![(
            b"/Nums".to_vec(),
            ObjectHandle::array(vec![ObjectHandle::integer(0), label]),
        )]);
        let leaf = pdf
            .make_indirect_from_object_handle(leaf)
            .expect("promote page-label leaf");
        install_page_labels(&mut pdf, leaf);
        let mut h = pdf.page_labels();
        let ranges = h.ranges().unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges[0].1.start, 7, "indirect /St must be resolved");
    }

    #[test]
    fn label_style_name_round_trip_all_variants() {
        for (bytes, style, name) in [
            (b"D".as_ref(), LabelStyle::Decimal, Some("D")),
            (b"R".as_ref(), LabelStyle::RomanUpper, Some("R")),
            (b"r".as_ref(), LabelStyle::RomanLower, Some("r")),
            (b"A".as_ref(), LabelStyle::AlphaUpper, Some("A")),
            (b"a".as_ref(), LabelStyle::AlphaLower, Some("a")),
        ] {
            assert_eq!(LabelStyle::from_name(bytes), style);
            assert_eq!(style.to_name(), name);
        }
        // Unrecognised /S name -> None (from_name `_` arm); None has no name.
        assert_eq!(LabelStyle::from_name(b"Z"), LabelStyle::None);
        assert_eq!(LabelStyle::None.to_name(), None);
    }

    #[test]
    fn ranges_handles_indirect_and_non_dict_values() {
        // entry 0: indirect ref to a label dict; entry 5: a non-dict value (skipped).
        let mut pdf = bare_one_page_pdf();
        let lab = pdf
            .make_indirect_from_object_handle(label_dict("D", None, None))
            .expect("promote indirect label dictionary");
        let leaf = ObjectHandle::dictionary(vec![(
            b"/Nums".to_vec(),
            ObjectHandle::array(vec![
                ObjectHandle::integer(0),
                lab, // indirect entry value -> resolve
                ObjectHandle::integer(5),
                ObjectHandle::integer(99), // non-dict entry value -> skipped
            ]),
        )]);
        let leaf = pdf
            .make_indirect_from_object_handle(leaf)
            .expect("promote page-label leaf");
        install_page_labels(&mut pdf, leaf);
        let mut h = pdf.page_labels();
        let ranges = h.ranges().unwrap();
        assert_eq!(ranges.len(), 1, "non-dict value skipped");
        assert_eq!(ranges[0].0, 0);
        assert_eq!(ranges[0].1.style, LabelStyle::Decimal);
    }

    #[test]
    fn ranges_non_name_style_resolves_to_none() {
        // A label dict whose /S is not a Name maps to LabelStyle::None via
        // the canonical handle-to-typed compatibility view.
        let mut pdf = bare_one_page_pdf();
        let lab = ObjectHandle::dictionary(vec![
            (b"/S".to_vec(), ObjectHandle::integer(0)), // non-Name /S
        ]);
        let leaf = ObjectHandle::dictionary(vec![(
            b"/Nums".to_vec(),
            ObjectHandle::array(vec![ObjectHandle::integer(0), lab]),
        )]);
        let leaf = pdf
            .make_indirect_from_object_handle(leaf)
            .expect("promote page-label leaf");
        install_page_labels(&mut pdf, leaf);
        let mut h = pdf.page_labels();
        let ranges = h.ranges().unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges[0].1.style, LabelStyle::None);
    }

    #[test]
    fn labels_for_page_range_fabricates_default_when_first_unlabeled() {
        // Only an explicit range at index 5; extract starting before it (idx 0).
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(5),
            label_dict("D", Some(1), None),
        ]);
        let mut h = pdf.page_labels();
        let out = h.labels_for_page_range(0, 6, 0).unwrap();
        // First entry fabricated: no /S (LabelStyle::None), start = new_start(0) + 1 = 1.
        // Matches qpdf 11.9.0's own fabricated dict (`getLabelForPage` returning
        // null): `<< /St 1 >>`, no `/S /D`.
        assert_eq!(out[0].0, 0);
        assert_eq!(out[0].1.style, LabelStyle::None);
        assert_eq!(out[0].1.start, 1);
        // The explicit range at 5 is copied (renumbered to 5).
        assert!(out.iter().any(|(idx, _)| *idx == 5));
    }

    #[test]
    fn labels_for_page_range_single_page_span_does_not_panic() {
        // start_idx == end_idx (a single-page span, the common case for
        // --split-pages=1 or a chunk's last page) must not panic: the
        // internal `explicit.range((start_idx+1)..=end_idx)` bound would
        // otherwise be inverted, which `BTreeSet::range` panics on.
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), None),
        ]);
        let mut h = pdf.page_labels();
        let out = h.labels_for_page_range(4, 4, 0).unwrap();
        assert_eq!(out, vec![(0, dec(5))], "St 1 + offset 4 = 5");
    }

    #[test]
    fn helper_rejects_non_dict_catalog() {
        let mut pdf = pdf_with_pagelabels(vec![]);
        let catalog_ref = pdf.root_ref().unwrap();
        pdf.replace_object(catalog_ref, ObjectHandle::integer(0))
            .unwrap(); // catalog no longer a dict
        let mut h = pdf.page_labels();
        let error = h
            .has_page_labels()
            .expect_err("qpdf getRoot rejects a non-dictionary Catalog");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    #[test]
    fn helper_rejects_missing_root() {
        // QPDFPageLabelDocumentHelper calls QPDF::getRoot, so a trailer
        // without /Root is a document-level error, not a missing-label case.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"%PDF-1.7\n");
        let off1 = bytes.len() as u64;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref = bytes.len() as u64;
        bytes.extend_from_slice(
            format!(
                "xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \ntrailer\n<< /Size 2 >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("rootless trailer still opens");
        assert!(pdf.root_ref().is_none(), "rootless trailer => no root_ref");
        let mut h = pdf.page_labels();
        let error = h
            .has_page_labels()
            .expect_err("qpdf getRoot rejects a missing Catalog");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    /// Shorthand for a plain decimal range starting at `start`, no prefix.
    fn dec(start: i64) -> LabelRange {
        LabelRange {
            style: LabelStyle::Decimal,
            prefix: String::new(),
            start,
        }
    }

    /// Shorthand for a style-less range (no `/S`), no prefix, starting at
    /// `start` — the shape of qpdf's fabricated "unlabeled page" default.
    fn none_range(start: i64) -> LabelRange {
        LabelRange {
            style: LabelStyle::None,
            prefix: String::new(),
            start,
        }
    }

    #[test]
    fn write_reconstructed_labels_installs_direct_nums_dict() {
        // Installed as a direct dict — not an indirect number tree — and
        // every entry's /St is explicit (qpdf --split-pages/--pages parity).
        let mut pdf = bare_one_page_pdf();
        {
            let mut h = pdf.page_labels();
            h.write_reconstructed_labels(&[
                (0, none_range(1)),
                (
                    3,
                    LabelRange {
                        style: LabelStyle::Decimal,
                        prefix: String::new(),
                        start: 1,
                    },
                ),
            ])
            .unwrap();
        }
        let catalog_ref = pdf.root_ref().unwrap();
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_is_scalar().unwrap();
        let page_labels = catalog.try_get_key(b"/PageLabels").unwrap();
        assert!(page_labels.as_dictionary().is_some());
        assert!(!page_labels.is_indirect(), "/PageLabels must be direct");
        let nums = page_labels.try_get_key(b"/Nums").unwrap();
        let nums = nums.as_array().expect("/Nums must be a direct array");
        assert_eq!(nums.len(), 4, "2 entries * (index, dict)");
        assert_eq!(nums[0].as_integer(), Some(0));
        assert_eq!(nums[1].try_get_key(b"/St").unwrap().as_integer(), Some(1));
        assert!(!nums[1].try_has_key(b"/S").unwrap());
        assert_eq!(nums[2].as_integer(), Some(3));
        assert_eq!(
            nums[3].try_get_key(b"/S").unwrap().try_as_name().unwrap(),
            Some(b"D".to_vec())
        );
        assert_eq!(nums[3].try_get_key(b"/St").unwrap().as_integer(), Some(1));

        // The high-level reader round-trips the installed entries too.
        let mut h = pdf.page_labels();
        let ranges = h.ranges().unwrap();
        assert_eq!(ranges.len(), 2);
        assert_eq!(ranges[0].0, 0);
        assert_eq!(ranges[1].0, 3);
    }

    #[test]
    fn direct_catalog_root_supports_page_label_reconstruction_and_readback() {
        let mut pdf = direct_root_one_page_pdf();
        pdf.page_labels()
            .write_reconstructed_labels(&[(0, dec(1))])
            .expect("direct Catalog must accept reconstructed labels");

        let mut helper = pdf.page_labels();
        assert!(helper
            .has_page_labels()
            .expect("read direct Catalog labels"));
        assert_eq!(
            helper.ranges().expect("read reconstructed labels"),
            vec![(0, dec(1))]
        );
    }

    #[test]
    fn direct_catalog_root_supports_raw_page_label_reconstruction() {
        let mut pdf = direct_root_one_page_pdf();
        pdf.page_labels()
            .write_reconstructed_labels_raw(&[(0, label_dict("A", Some(1), None))])
            .expect("direct Catalog must accept raw reconstructed labels");

        let root = pdf.root_handle().expect("direct Catalog root");
        let page_labels = root.try_get_key(b"/PageLabels").expect("PageLabels key");
        assert_eq!(
            page_labels
                .try_get_key(b"/Nums")
                .expect("Nums key")
                .try_array_len()
                .expect("Nums array"),
            Some(2)
        );
    }

    #[test]
    fn write_reconstructed_labels_preserves_catalog_source_metadata() {
        let mut pdf = bare_one_page_pdf();
        let catalog_ref = pdf.root_ref().expect("catalog ref");
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_dereference().expect("resolve catalog");
        let source_description = catalog.description();
        let source_end_offsets = catalog.end_offsets();
        assert!(
            source_end_offsets.0 >= 0 && source_end_offsets.1 >= 0,
            "fixture must establish catalog source extents"
        );

        pdf.page_labels()
            .write_reconstructed_labels(&[(0, none_range(1))])
            .expect("canonical label write");

        assert_eq!(
            catalog.description(),
            source_description,
            "replaceKey must preserve the catalog object description"
        );
        assert_eq!(
            catalog.end_offsets(),
            source_end_offsets,
            "replaceKey must preserve the catalog source extents"
        );
        assert!(
            catalog
                .try_get_key(b"/PageLabels")
                .expect("PageLabels key")
                .try_as_dictionary()
                .expect("PageLabels dictionary")
                .is_some(),
            "the live catalog handle must observe the replacement"
        );
    }

    #[test]
    fn label_prefix_presence_distinguishes_empty_and_absent_prefixes() {
        let mut explicit_empty = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), Some("")),
        ]);
        let mut helper = explicit_empty.page_labels();
        assert!(helper.label_prefix_is_present(0).unwrap());

        let mut empty_tree = pdf_with_pagelabels(vec![]);
        assert!(!empty_tree.page_labels().label_prefix_is_present(0).unwrap());

        let mut absent = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("D", Some(1), None),
        ]);
        assert!(!absent.page_labels().label_prefix_is_present(0).unwrap());

        let mut no_tree = bare_one_page_pdf();
        assert!(!no_tree.page_labels().label_prefix_is_present(0).unwrap());
    }

    #[test]
    fn reconstructed_labels_can_retain_an_explicit_empty_prefix() {
        let mut pdf = bare_one_page_pdf();
        let range = LabelRange {
            style: LabelStyle::Decimal,
            prefix: String::new(),
            start: 1,
        };
        pdf.page_labels()
            .write_reconstructed_labels_with_prefix_presence(&[
                (0, range.clone(), true),
                (2, range, false),
            ])
            .unwrap();

        let catalog_ref = pdf.root_ref().unwrap();
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_is_scalar().unwrap();
        let page_labels = catalog.try_get_key(b"/PageLabels").unwrap();
        let nums = page_labels
            .try_get_key(b"/Nums")
            .unwrap()
            .as_array()
            .expect("PageLabels /Nums must be an array");
        assert_eq!(
            nums[1].try_get_key(b"/P").unwrap().as_string(),
            Some(Vec::new())
        );
        assert!(!nums[3].try_has_key(b"/P").unwrap());
    }

    #[test]
    fn write_reconstructed_labels_replaces_existing_indirect_tree() {
        // A pre-existing indirect /PageLabels root is unconditionally replaced
        // by a fresh direct dict (qpdf never merges).
        let mut pdf = pdf_with_pagelabels(vec![
            ObjectHandle::integer(0),
            label_dict("R", Some(1), None),
        ]);
        {
            let mut h = pdf.page_labels();
            h.write_reconstructed_labels(&[(0, none_range(1))]).unwrap();
        }
        let catalog_ref = pdf.root_ref().unwrap();
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_is_scalar().unwrap();
        let page_labels = catalog.try_get_key(b"/PageLabels").unwrap();
        assert!(
            page_labels.as_dictionary().is_some() && !page_labels.is_indirect(),
            "/PageLabels must now be a direct dict, not the old indirect ref"
        );
    }

    #[test]
    fn write_reconstructed_labels_rejects_missing_root() {
        // All qpdf reconstruction paths first call QPDF::getRoot.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"%PDF-1.7\n");
        let off1 = bytes.len() as u64;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref = bytes.len() as u64;
        bytes.extend_from_slice(
            format!(
                "xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \ntrailer\n<< /Size 2 >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("rootless trailer still opens");
        let mut h = pdf.page_labels();
        let error = h
            .write_reconstructed_labels(&[(0, none_range(1))])
            .expect_err("qpdf getRoot rejects a missing Catalog");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    #[test]
    fn write_reconstructed_labels_rejects_non_dict_catalog() {
        let mut pdf = bare_one_page_pdf();
        let catalog_ref = pdf.root_ref().unwrap();
        pdf.replace_object(catalog_ref, ObjectHandle::integer(0))
            .unwrap(); // catalog no longer a dict
        let mut h = pdf.page_labels();
        let error = h
            .write_reconstructed_labels(&[(0, none_range(1))])
            .expect_err("qpdf getRoot rejects a non-dictionary Catalog");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    // ---- live-qpdf 11.9.0 oracle: get_label_for_page / get_labels_for_page_range ----
    //
    // `QPDFJob::doJSONPageLabels` (`QPDFJob.cc:1095-1116`) serializes exactly
    // `getLabelsForPageRange`'s entries with `getJSON(json_version)` and no
    // schema transformation, so `qpdf --json=2 --json-key=pagelabels` is a
    // faithful window onto the raw label dictionaries these two functions
    // build. This does not exercise flpdf's own `--json` output; it observes
    // qpdf's internal state through its own JSON serializer.
    //
    // `getLabelsForPageRange`'s `skip_first` redundancy-skip branch needs a
    // non-empty accumulator from a prior call, which `doJSONPageLabels`
    // never provides (it always starts from an empty `Vec`) — so no oracle
    // here exercises it. The raw redundancy rule stays covered by the existing
    // hand-derived raw-label and get_labels_for_page_range unit tests above.

    use std::path::{Path, PathBuf};
    use std::process::Command;

    /// Resolve qpdf 11.9.0: prefer `/usr/bin/qpdf` on Linux (apt-installed,
    /// pinned by CI), otherwise resolve `qpdf` on `PATH` (CI installs the
    /// pinned build there on macOS/Windows; see `.github/workflows/ci.yml`'s
    /// "Add qpdf 11.9.0 to PATH" steps). Returns `None` — the caller skips —
    /// unless the resolved candidate reports exactly `qpdf version 11.9.0`,
    /// so a developer host without the pinned binary doesn't fail `cargo
    /// test`, and a differently-versioned `qpdf` on `PATH` doesn't produce
    /// a silently wrong oracle comparison.
    fn pinned_qpdf() -> Option<PathBuf> {
        #[cfg(target_os = "linux")]
        let candidates: &[&str] = &["/usr/bin/qpdf", "qpdf"];
        #[cfg(not(target_os = "linux"))]
        let candidates: &[&str] = &["qpdf"];

        for candidate in candidates {
            // cov:ignore-start: CI provides the pinned qpdf 11.9.0 binary on every candidate path; a launch failure, non-zero exit, or version mismatch only happens on a developer host missing it.
            let Ok(version) = Command::new(candidate).arg("--version").output() else {
                continue;
            };
            if !version.status.success() {
                continue;
            }
            // cov:ignore-end
            let first_line = String::from_utf8_lossy(&version.stdout)
                .lines()
                .next()
                .unwrap_or_default()
                .to_string();
            if first_line == "qpdf version 11.9.0" {
                return Some(PathBuf::from(candidate));
            } // cov:ignore: CI's pinned candidate always matches; the non-matching-version fallthrough only happens on a developer host with a different qpdf on PATH
        }
        None // cov:ignore: CI always resolves a pinned candidate above; only reached on a developer host missing qpdf entirely
    }

    /// A 7-page PDF whose `/PageLabels /Nums` covers, at indices 0-5: an
    /// `/S`-only range, a range with none of `/S`/`/P`/`/St`, an `/St`-only
    /// range, a `/P`-only range, an unrecognized `/S` name, and a range with
    /// an explicit empty `/P ()` alongside `/S`/`/St`. Page 6 has no
    /// explicit `/Nums` entry, exercising the `/St` offset-addition path
    /// (`QPDFPageLabelDocumentHelper.cc:38-40`).
    fn qpdf_pagelabels_probe_pdf() -> Vec<u8> {
        let npages = 7u32;
        let mut bodies: Vec<Vec<u8>> =
            vec![b"<< /Type /Catalog /Pages 2 0 R /PageLabels 10 0 R >>".to_vec()];
        let kids = (0..npages)
            .map(|i| format!("{} 0 R", 3 + i))
            .collect::<Vec<_>>()
            .join(" ");
        bodies.push(format!("<< /Type /Pages /Kids [{kids}] /Count {npages} >>").into_bytes());
        for _ in 0..npages {
            bodies.push(b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec());
        }
        // obj 10 (/PageLabels), right after the 7 pages (obj 3..=9).
        bodies.push(
            b"<< /Nums [\
              0 << /S /r >> \
              1 << >> \
              2 << /St 9 >> \
              3 << /P (Ch-) >> \
              4 << /S /Z >> \
              5 << /S /D /P () /St 2 >> \
              ] >>"
                .to_vec(),
        );

        let mut bytes = b"%PDF-1.7\n".to_vec();
        let mut offsets = Vec::with_capacity(bodies.len());
        for (index, body) in bodies.iter().enumerate() {
            offsets.push(bytes.len());
            bytes.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes());
            bytes.extend_from_slice(body);
            bytes.extend_from_slice(b"\nendobj\n");
        }
        let xref_start = bytes.len();
        let total = bodies.len() + 1;
        bytes.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
        for offset in &offsets {
            bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        bytes.extend_from_slice(
            format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        bytes
    }

    /// Run `qpdf --json=2 --json-key=pagelabels` and return the parsed
    /// `"pagelabels"` array.
    fn qpdf_json_pagelabels(qpdf: &Path, path: &Path) -> Json {
        let qpdf = Command::new(qpdf)
            .arg("--json=2")
            .arg("--json-key=pagelabels")
            .arg(path)
            .output()
            .expect("run pinned qpdf pagelabels oracle");
        let qpdf_stderr = String::from_utf8_lossy(&qpdf.stderr);
        assert!(
            qpdf.status.success(),
            "qpdf --json=2 --json-key=pagelabels failed: {qpdf_stderr}"
        );
        let document = Json::parse(&qpdf.stdout).expect("parse qpdf JSON output");
        document.get_dict_item("pagelabels")
    }

    /// Compare a raw label dictionary built by flpdf against qpdf's JSON
    /// rendering of the same dictionary (`getJSON`'s `/S`/`/P`/`/St` shape).
    ///
    /// ASCII-only: qpdf's JSON writer switches non-UTF-8-representable text
    /// strings from a `u:` prefix to a base64 `b:` prefix, which this helper
    /// does not decode.
    fn assert_label_matches_qpdf_json(
        flpdf_label: &ObjectHandle,
        qpdf_label: &Json,
        context: &str,
    ) {
        let qpdf_s = qpdf_label.get_dict_item("/S");
        if qpdf_s.is_null() {
            assert!(
                !flpdf_label.try_has_key(b"/S").unwrap(),
                "{context}: /S must be absent"
            );
        } else {
            let name = qpdf_s.get_string().expect("qpdf /S is a JSON string");
            let expected = name.strip_prefix(b"/").expect("qpdf name starts with /");
            assert_eq!(
                flpdf_label
                    .try_get_key(b"/S")
                    .unwrap()
                    .try_as_name()
                    .unwrap()
                    .as_deref(),
                Some(expected),
                "{context}: /S mismatch"
            );
        }

        let qpdf_p = qpdf_label.get_dict_item("/P");
        if qpdf_p.is_null() {
            assert!(
                !flpdf_label.try_has_key(b"/P").unwrap(),
                "{context}: /P must be absent"
            );
        } else {
            let string = qpdf_p.get_string().expect("qpdf /P is a JSON string");
            let expected = string
                .strip_prefix(b"u:")
                .expect("fixture /P values are ASCII (qpdf u: prefix)");
            assert_eq!(
                flpdf_label
                    .try_get_key(b"/P")
                    .unwrap()
                    .as_string()
                    .as_deref(),
                Some(expected),
                "{context}: /P mismatch"
            );
        }

        let qpdf_st = qpdf_label
            .get_dict_item("/St")
            .get_number()
            .expect("qpdf /St is always present");
        let qpdf_st: i64 = std::str::from_utf8(&qpdf_st)
            .unwrap()
            .parse()
            .expect("qpdf /St is an integer");
        assert_eq!(
            flpdf_label.try_get_key(b"/St").unwrap().as_integer(),
            Some(qpdf_st),
            "{context}: /St mismatch"
        );
    }

    #[test]
    fn get_labels_for_page_range_matches_pinned_qpdf_json_oracle() {
        let Some(qpdf) = pinned_qpdf() else {
            // cov:ignore-start: CI provides the pinned qpdf binary; this is a developer-host skip
            eprintln!("pinned qpdf 11.9.0 unavailable; skipping pagelabels oracle");
            return;
            // cov:ignore-end
        };
        let bytes = qpdf_pagelabels_probe_pdf();
        let directory = tempfile::tempdir().expect("temporary qpdf oracle directory");
        let path = directory.path().join("pagelabels-probe.pdf");
        std::fs::write(&path, &bytes).expect("write qpdf oracle fixture");

        let pagelabels = qpdf_json_pagelabels(&qpdf, &path);
        let mut expected: Vec<(i64, Json)> = Vec::new();
        pagelabels.for_each_array_item(|entry| {
            let index = entry
                .get_dict_item("index")
                .get_number()
                .and_then(|bytes| std::str::from_utf8(&bytes).ok()?.parse::<i64>().ok())
                .expect("qpdf pagelabels[].index is an integer");
            expected.push((index, entry.get_dict_item("label")));
        });
        // Only explicit /Nums indices (0..=5) get an entry: getLabelsForPageRange
        // gates non-leading pages on hasIndex, unlike get_label_for_page's
        // inherited-range lookup. Page 6 has no explicit entry.
        assert_eq!(
            expected.iter().map(|(index, _)| *index).collect::<Vec<_>>(),
            (0..=5).collect::<Vec<_>>(),
            "qpdf pagelabels index list"
        );

        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("open");
        let mut helper = pdf.page_labels();
        let mut actual: Vec<(i64, ObjectHandle)> = Vec::new();
        helper
            .get_labels_for_page_range(0, 6, 0, &mut actual)
            .expect("get_labels_for_page_range");

        assert_eq!(actual.len(), expected.len(), "entry count");
        for ((actual_index, actual_label), (expected_index, expected_label)) in
            actual.iter().zip(expected.iter())
        {
            assert_eq!(actual_index, expected_index, "index");
            assert_label_matches_qpdf_json(
                actual_label,
                expected_label,
                &format!("index {actual_index}"),
            );
        }
    }

    #[test]
    fn get_label_for_page_matches_pinned_qpdf_json_oracle_for_every_page() {
        let Some(qpdf) = pinned_qpdf() else {
            // cov:ignore-start: CI provides the pinned qpdf binary; this is a developer-host skip
            eprintln!("pinned qpdf 11.9.0 unavailable; skipping pagelabels oracle");
            return;
            // cov:ignore-end
        };
        let bytes = qpdf_pagelabels_probe_pdf();
        let directory = tempfile::tempdir().expect("temporary qpdf oracle directory");
        let input_path = directory.path().join("pagelabels-probe.pdf");
        std::fs::write(&input_path, &bytes).expect("write qpdf oracle fixture");

        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("open");
        let mut helper = pdf.page_labels();

        for page_idx in 0i64..7 {
            let output_path = directory.path().join(format!("page-{page_idx}.pdf"));
            let extract = Command::new(&qpdf)
                .arg("--empty")
                .arg("--pages")
                .arg(&input_path)
                .arg((page_idx + 1).to_string()) // qpdf --pages page numbers are 1-based.
                .arg("--")
                .arg(&output_path)
                .output()
                .expect("run pinned qpdf page extraction");
            let extract_stderr = String::from_utf8_lossy(&extract.stderr);
            assert!(
                extract.status.success(),
                "qpdf page {page_idx} extraction failed: {extract_stderr}"
            );

            let entries = qpdf_json_pagelabels(&qpdf, &output_path);
            let mut expected_label = None;
            entries.for_each_array_item(|entry| {
                expected_label = Some(entry.get_dict_item("label"));
            });
            let expected_label =
                expected_label.expect("single-page extraction always has an effective label");

            let actual = helper
                .get_label_for_page(page_idx)
                .expect("get_label_for_page")
                .expect("every page in this fixture has an effective label");
            assert_label_matches_qpdf_json(&actual, &expected_label, &format!("page {page_idx}"));
        }
    }
}