flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
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
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
//! Provide a shared engine and public wrappers for PDF name trees and number
//! trees.
//!
//! qpdf correspondence: NNTree.cc behavior implemented with Rust-specific storage, error, and ownership boundaries.
//!
//!
//!
//! The traversal/mutation path is canonical `ObjectHandle` graph state: qpdf's
//! `QPDFObjectHandle` nodes and arrays are kept live through lookup, cursor
//! movement, repair, split, insert, and remove (`libqpdf/NNTree.cc:34-75,
//! 106-168, 216-390, 391-520, 560-700`). The public `NameTree` and
//! `NumberTree` facades and the shared generic engine are handle-native with no
//! independent value fixture or projection route remaining. Production tree
//! mutations do not leave the canonical handle graph. Array replacement
//! follows qpdf's `QPDFObjectHandle` live-array mutators and
//! `QPDF_Array::setFromVector` ownership/order boundary
//! (`libqpdf/QPDFObjectHandle.cc:869-955`, `libqpdf/QPDF_Array.cc:220-313`),
//! and direct-node promotion preserves the existing allocation like `QPDF::makeIndirectObject`
//! (`libqpdf/QPDF.cc:1835-1902`).
//! Indirect traversal identity follows qpdf's `QPDFObjGen::set`
//! (`include/qpdf/QPDFObjGen.hh:87-120`, `libqpdf/QPDFObjGen.cc:25-35`);
//! direct canonical handles use the existing `ObjectHandleIdentity` primitive,
//! which matches `QPDFObjectHandle::isSameObjectAs`
//! (`include/qpdf/QPDFObjectHandle.hh:304-309`,
//! `libqpdf/QPDFObjectHandle.cc:224-227`).

use crate::object_handle::{canonical_dictionary_key, ObjectHandleIdentity};
use crate::pdf_string::{new_unicode_string, normalized_utf8_value, utf8_value};
use crate::{Error, ObjectHandle, ObjectRef, Pdf, QpdfErrorCode, QpdfExc, Result};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Debug;
use std::io::{Read, Seek};
use std::marker::PhantomData;
use std::sync::Arc;

pub(crate) const DEFAULT_SPLIT_THRESHOLD: usize = 32;

/// Default `/Kids` descent depth limit for name and number tree traversal.
pub const DEFAULT_MAX_TREE_DEPTH: usize = 100;

/// Default qpdf split threshold for name and number tree leaves.
pub const LEAF_MAX: usize = DEFAULT_SPLIT_THRESHOLD;

pub(crate) trait TreeKey {
    type Key: Clone + Debug + Eq + Ord;
    const ITEMS_KEY: &'static str;

    fn from_handle(handle: &ObjectHandle) -> Option<Self::Key>;
    fn to_handle(key: &Self::Key) -> ObjectHandle;

    fn compare(left: &Self::Key, right: &Self::Key) -> Ordering {
        left.cmp(right)
    }
}

pub(crate) enum NameKey {}

impl TreeKey for NameKey {
    type Key = Vec<u8>;
    const ITEMS_KEY: &'static str = "Names";

    fn from_handle(handle: &ObjectHandle) -> Option<Self::Key> {
        handle.as_string().map(|value| utf8_value(&value))
    }

    fn to_handle(key: &Self::Key) -> ObjectHandle {
        let normalized = normalized_utf8_value(key);
        ObjectHandle::string(new_unicode_string(&normalized))
    }
}

pub(crate) enum NumberKey {}

impl TreeKey for NumberKey {
    type Key = i64;
    const ITEMS_KEY: &'static str = "Nums";

    fn from_handle(handle: &ObjectHandle) -> Option<Self::Key> {
        handle.as_integer()
    }

    fn to_handle(key: &Self::Key) -> ObjectHandle {
        ObjectHandle::integer(*key)
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum NodeAnchor {
    Root,
    Indirect(ObjectRef),
}

#[derive(Clone, Eq, Hash, PartialEq)]
enum NodeIdentity {
    /// qpdf's `QPDFObjGen::set` identity for an indirect node.
    Indirect(ObjectRef),
    /// The live allocation identity for a direct canonical ObjectHandle.
    Direct(ObjectHandleIdentity),
}

/// A node path keeps the qpdf diagnostic anchor and the live node handle
/// separately. Direct canonical children are identified by their live handle;
/// indirect children keep their own ObjGen anchor. The `handle` field is the
/// only value the canonical engine reads or mutates.
#[derive(Clone, Debug)]
struct NodeHandle {
    anchor: NodeAnchor,
    direct_kids: Vec<usize>,
    handle: ObjectHandle,
}

impl NodeHandle {
    fn root(handle: ObjectHandle) -> Self {
        Self {
            anchor: NodeAnchor::Root,
            direct_kids: Vec::new(),
            handle,
        }
    }

    fn indirect(object_ref: ObjectRef, handle: ObjectHandle) -> Self {
        Self {
            anchor: NodeAnchor::Indirect(object_ref),
            direct_kids: Vec::new(),
            handle,
        }
    }

    fn direct_kid(&self, kid_index: usize, handle: ObjectHandle) -> Self {
        let mut direct_kids = self.direct_kids.clone();
        direct_kids.push(kid_index);
        Self {
            anchor: self.anchor.clone(),
            direct_kids,
            handle,
        }
    }

    fn handle(&self) -> ObjectHandle {
        self.handle.clone()
    }

    fn identity(&self) -> NodeIdentity {
        if self.direct_kids.is_empty() {
            if let NodeAnchor::Indirect(object_ref) = self.anchor {
                return NodeIdentity::Indirect(object_ref);
            }
        }
        NodeIdentity::Direct(self.handle.identity_key())
    }

    fn diagnostic_ref(&self) -> Option<ObjectRef> {
        if !self.direct_kids.is_empty() {
            return None;
        }
        match self.anchor {
            NodeAnchor::Indirect(object_ref) => Some(object_ref),
            NodeAnchor::Root => None,
        }
    }
}

/// A live array view. `values` is only a short-lived vector of handle clones;
/// the array itself remains `handle`, so `store` mutates the canonical array
/// allocation and preserves every alias to it.
struct ResolvedArray {
    handle: ObjectHandle,
    values: Vec<ObjectHandle>,
}

impl ResolvedArray {
    fn store(&self) -> Result<()> {
        self.handle.set_array_items(self.values.clone())?;
        Ok(())
    }
}

fn resolved_array(value: Option<&ObjectHandle>) -> Result<Option<ResolvedArray>> {
    let Some(source) = value else {
        return Ok(None);
    };
    source.try_dereference()?;
    let source = source.clone();
    let Some(values) = source.try_as_array()? else {
        return Ok(None);
    };
    Ok(Some(ResolvedArray {
        handle: source,
        values,
    }))
}

fn resolved_key<K: TreeKey>(value: &ObjectHandle) -> Result<Option<K::Key>> {
    value.try_dereference()?;
    let value = value.clone();
    Ok(K::from_handle(&value))
}

/// Reject a handle-native tree value that does not belong to `pdf`.
///
/// A foreign indirect handle stored into this tree would keep resolving
/// through its original document's resolver, mixing object graphs and
/// risking that document's object reference being serialized into `pdf`.
/// This mirrors the check `EmbeddedFileDocumentHelper::replace_embedded_file`
/// already performs before its own tree insert.
///
/// An indirect `value` is checked with the same canonical-registration
/// strictness `replace_embedded_file` uses. A direct `value` is checked with
/// [`ObjectHandle::belongs_exclusively_to_pdf`], not the shallower
/// [`ObjectHandle::belongs_to_pdf`]: a freshly constructed direct wrapper
/// (e.g. `ObjectHandle::dictionary`) always reports no owner of its own even
/// when it nests an already-indirect handle from a different `Pdf`, so only
/// a full descendant walk catches that case.
fn ensure_value_owned_by_pdf<R: Read + Seek>(pdf: &Pdf<R>, value: &ObjectHandle) -> Result<()> {
    if let Some(object_ref) = value.object_ref() {
        if !pdf.is_canonical_object_handle(value) {
            return Err(Error::Unsupported(
                "name/number tree value belongs to a different Pdf".to_string(),
            ));
        }
        debug_assert_eq!(value.object_ref(), Some(object_ref));
    } else if !value.belongs_exclusively_to_pdf(pdf.unique_id()) {
        return Err(Error::Unsupported(
            "name/number tree value belongs to a different Pdf".to_string(),
        ));
    }
    Ok(())
}

fn ensure_tree_root_pdf(root: &ObjectHandle, root_pdf_id: Option<u64>, pdf_id: u64) -> Result<()> {
    let belongs_to_another_pdf = match root_pdf_id {
        Some(owner) => owner != pdf_id,
        None => !root.belongs_exclusively_to_pdf(pdf_id),
    };
    if belongs_to_another_pdf {
        return Err(Error::Unsupported(
            "name/number tree root belongs to a different Pdf".to_string(),
        ));
    }
    Ok(())
}

/// A dictionary facade over one live `ObjectHandle`. It intentionally exposes
/// only live handle values so callers cannot accidentally detach a canonical
/// tree node from its owning document.
#[derive(Clone)]
struct LiveDictionary {
    handle: ObjectHandle,
}

impl LiveDictionary {
    fn new(handle: ObjectHandle, filename: &[u8]) -> Result<Self> {
        handle.try_dereference()?;
        if !handle.try_is_dictionary()? {
            return Err(structural_error(filename, handle.object_ref(), "bad node"));
        }
        Ok(Self { handle })
    }

    fn actual_key(&self, key: &str) -> Vec<u8> {
        canonical_dictionary_key(key.as_bytes())
    }

    fn get(&self, key: &str) -> Result<Option<ObjectHandle>> {
        let key = self.actual_key(key);
        let value = self.handle.try_get_key(&key)?;
        // qpdf dereferences the value before its array/type checks, so a
        // dangling reference has the same null outcome as a literal null.
        Ok((!value.is_null()).then_some(value))
    }

    fn insert(&self, key: &str, value: ObjectHandle) -> Result<()> {
        let key = self.actual_key(key);
        self.handle.replace_key(&key, value)
    }

    fn remove(&self, key: &str) {
        let key = self.actual_key(key);
        self.handle.remove_key(&key);
    }

    fn contains(&self, key: &str) -> Result<bool> {
        let key = self.actual_key(key);
        self.handle.try_has_key(&key)
    }
}

#[derive(Clone, Debug)]
struct PathElement {
    node: NodeHandle,
    kid_number: usize,
}

pub(crate) struct NNTreeCursor<K: TreeKey> {
    path: Vec<PathElement>,
    leaf: Option<NodeHandle>,
    item_number: Option<usize>,
    current: Option<(K::Key, ObjectHandle)>,
    /// qpdf's iterator retains `QPDFObjectHandle`s owned by one `QPDF`
    /// (`QPDFObjectHandle.hh:852-872`, `NNTree.cc:30-73`). Keep the same
    /// document boundary when the Rust API receives a cursor and a `Pdf`
    /// separately.
    pdf_id: Option<u64>,
    marker: PhantomData<K>,
}

impl<K: TreeKey> NNTreeCursor<K> {
    fn empty() -> Self {
        Self {
            path: Vec::new(),
            leaf: None,
            item_number: None,
            current: None,
            pdf_id: None,
            marker: PhantomData,
        }
    }

    fn for_pdf(pdf_id: u64) -> Self {
        let mut cursor = Self::empty();
        cursor.pdf_id = Some(pdf_id);
        cursor
    }

    fn ensure_pdf<R: Read + Seek>(&mut self, pdf: &Pdf<R>) -> Result<()> {
        let pdf_id = pdf.unique_id();
        match self.pdf_id {
            None => self.pdf_id = Some(pdf_id),
            Some(owner) if owner == pdf_id => {}
            Some(_) => {
                return Err(Error::Unsupported(
                    "name/number tree cursor belongs to a different Pdf".to_string(),
                ));
            }
        }
        Ok(())
    }

    /// Whether traversal has selected an array slot.
    ///
    /// Malformed keys may leave a cursor positioned while [`Self::current`]
    /// is `None`; callers must not treat this as a usable key/value pair.
    pub(crate) fn positioned(&self) -> bool {
        self.item_number.is_some()
    }

    fn cloned_current(&self) -> Option<(K::Key, ObjectHandle)> {
        self.current.clone()
    }

    fn current_key(&self) -> Option<&K::Key> {
        self.current.as_ref().map(|(key, _value)| key)
    }

    fn clear_position(&mut self) {
        self.leaf = None;
        self.item_number = None;
        self.current = None;
    }

    fn same_position(&self, other: &Self) -> bool {
        if self.item_number.is_none() && other.item_number.is_none() {
            return true;
        }
        self.item_number == other.item_number
            && self.path.len() == other.path.len()
            && self
                .path
                .iter()
                .zip(&other.path)
                .all(|(left, right)| left.kid_number == right.kid_number)
    }
}

impl<K: TreeKey> Clone for NNTreeCursor<K> {
    fn clone(&self) -> Self {
        Self {
            path: self.path.clone(),
            leaf: self.leaf.clone(),
            item_number: self.item_number,
            current: self.current.clone(),
            pdf_id: self.pdf_id,
            marker: PhantomData,
        }
    }
}

pub(crate) struct NNTree<K: TreeKey> {
    root: ObjectHandle,
    root_pdf_id: Option<u64>,
    auto_repair: bool,
    split_threshold: usize,
    max_depth: Option<usize>,
    marker: PhantomData<K>,
}

/// Read and modify a PDF name tree (a `/Names`-style sorted key/value index).
///
/// Name keys are supplied as UTF-8 bytes. Both byte slices and strings are
/// accepted through [`AsRef<[u8]>`].
///
/// qpdf correspondence: `NNTreeImpl` (`libqpdf/NNTree.cc`) constructed with
/// `NameTreeDetails` (`libqpdf/QPDFNameTreeObjectHelper.cc`).
pub struct NameTree {
    inner: NNTree<NameKey>,
    cursor_owner: Arc<()>,
}

impl NameTree {
    /// Wrap an existing name-tree root handle.
    ///
    /// The first PDF passed to an operation claims the handle's document
    /// boundary; subsequent operations reject handles from another PDF.
    pub fn new(root: ObjectHandle, auto_repair: bool) -> Self {
        Self {
            inner: NNTree::new(root, auto_repair),
            cursor_owner: Arc::new(()),
        }
    }

    /// Create an empty name tree with an indirect root.
    ///
    /// # Errors
    ///
    /// Returns an error when the PDF object-number space is exhausted.
    pub fn new_empty<R: Read + Seek>(pdf: &mut Pdf<R>, auto_repair: bool) -> Result<Self> {
        let root = ObjectHandle::dictionary(vec![(
            canonical_dictionary_key(NameKey::ITEMS_KEY.as_bytes()),
            ObjectHandle::array(Vec::new()),
        )]);
        let root = pdf.make_indirect_from_object_handle(root)?;
        Ok(Self::new(root, auto_repair))
    }

    /// Return the live root handle, matching qpdf's `getObjectHandle`.
    pub fn get_object_handle(&self) -> ObjectHandle {
        self.inner.root.clone()
    }

    /// Return an invalid cursor representing the position past the tree.
    pub fn end(&self) -> NameTreeCursor {
        NameTreeCursor {
            inner: self.inner.end(),
            owner: Arc::clone(&self.cursor_owner),
        }
    }

    /// Return a cursor positioned at the first entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn begin<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NameTreeCursor> {
        self.inner.begin(pdf).map(|inner| NameTreeCursor {
            inner,
            owner: Arc::clone(&self.cursor_owner),
        })
    }

    /// Return a cursor positioned at the last entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn last<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NameTreeCursor> {
        self.inner.last(pdf).map(|inner| NameTreeCursor {
            inner,
            owner: Arc::clone(&self.cursor_owner),
        })
    }

    /// Find `key`, optionally returning the closest lower entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn find<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K,
        return_previous_if_missing: bool,
    ) -> Result<NameTreeCursor> {
        let key = normalized_utf8_value(key.as_ref());
        self.inner
            .find(pdf, &key, return_previous_if_missing)
            .map(|inner| NameTreeCursor {
                inner,
                owner: Arc::clone(&self.cursor_owner),
            })
    }

    /// Insert or replace an entry and return a cursor positioned at it.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated.
    pub fn insert<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K,
        value: ObjectHandle,
    ) -> Result<NameTreeCursor> {
        self.inner
            .insert(pdf, key.as_ref().to_vec(), value)
            .map(|inner| NameTreeCursor {
                inner,
                owner: Arc::clone(&self.cursor_owner),
            })
    }

    /// Return whether the tree contains an explicit entry for `key`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn has_name<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K,
    ) -> Result<bool> {
        Ok(self.find_object(pdf, key)?.is_some())
    }

    /// Find the value stored at `key`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn find_object<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K,
    ) -> Result<Option<ObjectHandle>> {
        Ok(self
            .inner
            .find(pdf, &normalized_utf8_value(key.as_ref()), false)?
            .cloned_current()
            .map(|(_, value)| value))
    }

    /// Remove the entry at `key`, returning its former value.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated.
    pub fn remove<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K,
    ) -> Result<Option<ObjectHandle>> {
        self.inner.remove(pdf, &normalized_utf8_value(key.as_ref()))
    }

    /// Materialize the tree as a sorted map.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn as_map<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
    ) -> Result<BTreeMap<Vec<u8>, ObjectHandle>> {
        let mut result = BTreeMap::new();
        let mut cursor = self.inner.begin(pdf)?;
        if cursor.positioned() && cursor.cloned_current().is_none() {
            return Err(Error::Internal(
                "attempt made to dereference an invalid name/number tree iterator".to_string(),
            ));
        }
        while let Some((key, value)) = cursor.cloned_current() {
            result.insert(key, value);
            self.inner.next(pdf, &mut cursor)?;
        }
        Ok(result)
    }

    /// Set the node split threshold.
    ///
    /// This exists for qpdf-compatible tests; production callers normally
    /// retain the default threshold of 32.
    pub fn set_split_threshold(&mut self, threshold: usize) {
        self.inner.set_split_threshold(threshold);
    }

    /// Bound `/Kids` chain traversal to `max_depth` levels.
    ///
    /// Unbounded by default; a caller reading an untrusted document should
    /// set this (e.g. to [`DEFAULT_MAX_TREE_DEPTH`]) to reject a
    /// pathologically deep tree with [`crate::Error::Unsupported`] instead
    /// of recursing without bound.
    pub fn set_max_depth(&mut self, max_depth: usize) {
        self.inner.max_depth = Some(max_depth);
    }
}

/// Cursor over a [`NameTree`] whose values retain live `ObjectHandle` identity.
pub struct NameTreeCursor {
    inner: NNTreeCursor<NameKey>,
    owner: Arc<()>,
}

impl Clone for NameTreeCursor {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            owner: Arc::clone(&self.owner),
        }
    }
}

impl PartialEq for NameTreeCursor {
    fn eq(&self, other: &Self) -> bool {
        self.inner.same_position(&other.inner)
    }
}

impl Eq for NameTreeCursor {}

impl NameTreeCursor {
    /// Whether the cursor points to a valid key/value pair.
    pub fn valid(&self) -> bool {
        self.inner.cloned_current().is_some()
    }

    /// Return a clone of the current key/value pair.
    pub fn current(&self) -> Option<(Vec<u8>, ObjectHandle)> {
        self.inner.cloned_current()
    }

    /// Advance to the next entry.
    ///
    /// Advancing an end cursor selects the first entry, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed, or the
    /// cursor belongs to another tree.
    pub fn next<R: Read + Seek>(&mut self, tree: &mut NameTree, pdf: &mut Pdf<R>) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner.next(pdf, &mut self.inner)
    }

    /// Move to the previous entry.
    ///
    /// Moving an end cursor backward selects the last entry, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed, or the
    /// cursor belongs to another tree.
    pub fn previous<R: Read + Seek>(
        &mut self,
        tree: &mut NameTree,
        pdf: &mut Pdf<R>,
    ) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner.previous(pdf, &mut self.inner)
    }

    /// Insert an entry immediately after the cursor and select it.
    ///
    /// This fast path does not validate key ordering, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated, or the
    /// cursor belongs to another tree.
    pub fn insert_after<R: Read + Seek, K: AsRef<[u8]>>(
        &mut self,
        tree: &mut NameTree,
        pdf: &mut Pdf<R>,
        key: K,
        value: ObjectHandle,
    ) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner
            .insert_after(pdf, &mut self.inner, key.as_ref().to_vec(), value)
    }

    /// Remove the current entry and advance to the next entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated, the
    /// cursor belongs to another tree, or the cursor is invalid.
    pub fn remove<R: Read + Seek>(&mut self, tree: &mut NameTree, pdf: &mut Pdf<R>) -> Result<()> {
        self.ensure_owner(tree)?;
        if !self.valid() {
            return Err(Error::Unsupported(
                "attempted to remove an invalid name-tree cursor".to_string(),
            ));
        }
        tree.inner.remove_at(pdf, &mut self.inner).map(|_| ())
    }

    fn ensure_owner(&self, tree: &NameTree) -> Result<()> {
        if Arc::ptr_eq(&self.owner, &tree.cursor_owner) {
            Ok(())
        } else {
            Err(Error::Unsupported(
                "name-tree cursor belongs to a different tree".to_string(),
            ))
        }
    }
}

/// Read and modify a PDF number tree (a `/PageLabels`-style sorted
/// integer-key index).
///
/// The helper owns the tree root while all indirect nodes remain in the
/// supplied [`Pdf`]. Mutating a direct root therefore updates this helper's
/// owned root; use the helper for subsequent operations.
///
/// qpdf correspondence: `NNTreeImpl` (`libqpdf/NNTree.cc`) constructed with
/// `NumberTreeDetails` (`libqpdf/QPDFNumberTreeObjectHelper.cc`).
pub struct NumberTree {
    inner: NNTree<NumberKey>,
    cursor_owner: Arc<()>,
}

impl NumberTree {
    /// Wrap an existing number-tree root handle.
    ///
    /// The first PDF passed to an operation claims the handle's document
    /// boundary; subsequent operations reject handles from another PDF.
    pub fn new(root: ObjectHandle, auto_repair: bool) -> Self {
        Self {
            inner: NNTree::new(root, auto_repair),
            cursor_owner: Arc::new(()),
        }
    }

    /// Create an empty number tree with an indirect root.
    ///
    /// # Errors
    ///
    /// Returns an error when the PDF object-number space is exhausted.
    pub fn new_empty<R: Read + Seek>(pdf: &mut Pdf<R>, auto_repair: bool) -> Result<Self> {
        let root = ObjectHandle::dictionary(vec![(
            canonical_dictionary_key(NumberKey::ITEMS_KEY.as_bytes()),
            ObjectHandle::array(Vec::new()),
        )]);
        let root = pdf.make_indirect_from_object_handle(root)?;
        Ok(Self::new(root, auto_repair))
    }

    /// Return the live root handle, matching qpdf's `getObjectHandle`.
    pub fn get_object_handle(&self) -> ObjectHandle {
        self.inner.root.clone()
    }

    /// Return an invalid cursor representing the position past the tree.
    pub fn end(&self) -> NumberTreeCursor {
        NumberTreeCursor {
            inner: self.inner.end(),
            owner: Arc::clone(&self.cursor_owner),
        }
    }

    /// Return a cursor positioned at the first entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn begin<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NumberTreeCursor> {
        self.inner.begin(pdf).map(|inner| NumberTreeCursor {
            inner,
            owner: Arc::clone(&self.cursor_owner),
        })
    }

    /// Return a cursor positioned at the last entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn last<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NumberTreeCursor> {
        self.inner.last(pdf).map(|inner| NumberTreeCursor {
            inner,
            owner: Arc::clone(&self.cursor_owner),
        })
    }

    /// Find `key`, optionally returning the closest lower entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn find<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: i64,
        return_previous_if_missing: bool,
    ) -> Result<NumberTreeCursor> {
        self.inner
            .find(pdf, &key, return_previous_if_missing)
            .map(|inner| NumberTreeCursor {
                inner,
                owner: Arc::clone(&self.cursor_owner),
            })
    }

    /// Insert or replace an entry and return a cursor positioned at it.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated.
    pub fn insert<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: i64,
        value: ObjectHandle,
    ) -> Result<NumberTreeCursor> {
        self.inner
            .insert(pdf, key, value)
            .map(|inner| NumberTreeCursor {
                inner,
                owner: Arc::clone(&self.cursor_owner),
            })
    }

    /// Find the value stored at `key`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn find_object<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: i64,
    ) -> Result<Option<ObjectHandle>> {
        Ok(self
            .inner
            .find(pdf, &key, false)?
            .cloned_current()
            .map(|(_, value)| value))
    }

    /// Return the smallest index, or `0` when the tree is empty.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn min<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<i64> {
        Ok(self
            .inner
            .begin(pdf)?
            .cloned_current()
            .map_or(0, |(key, _)| key))
    }

    /// Return the largest index, or `0` when the tree is empty.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn max<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<i64> {
        Ok(self
            .inner
            .last(pdf)?
            .cloned_current()
            .map_or(0, |(key, _)| key))
    }

    /// Return whether the tree contains an explicit entry at `key`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or searched.
    pub fn has_index<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>, key: i64) -> Result<bool> {
        Ok(self.find_object(pdf, key)?.is_some())
    }

    /// Find the value at `key`, or the closest value below it.
    ///
    /// The returned offset is `key - actual_key`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be searched or the signed offset
    /// cannot be represented as an [`i64`].
    pub fn find_object_at_or_below<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: i64,
    ) -> Result<Option<(ObjectHandle, i64)>> {
        let Some((actual_key, value)) = self.inner.find(pdf, &key, true)?.cloned_current() else {
            return Ok(None);
        };
        let offset = key.checked_sub(actual_key).ok_or_else(|| {
            Error::Unsupported("number-tree at-or-below offset overflow".to_string())
        })?;
        Ok(Some((value, offset)))
    }

    /// Remove the entry at `key`, returning its former value.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated.
    pub fn remove<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: i64,
    ) -> Result<Option<ObjectHandle>> {
        self.inner.remove(pdf, &key)
    }

    /// Materialize the tree as a sorted map.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed.
    pub fn as_map<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
    ) -> Result<BTreeMap<i64, ObjectHandle>> {
        let mut result = BTreeMap::new();
        let mut cursor = self.inner.begin(pdf)?;
        if cursor.positioned() && cursor.cloned_current().is_none() {
            return Err(Error::Internal(
                "attempt made to dereference an invalid name/number tree iterator".to_string(),
            ));
        }
        while let Some((key, value)) = cursor.cloned_current() {
            result.insert(key, value);
            self.inner.next(pdf, &mut cursor)?;
        }
        Ok(result)
    }

    /// Set the node split threshold.
    ///
    /// This exists for qpdf-compatible tests; production callers normally
    /// retain the default threshold of 32.
    pub fn set_split_threshold(&mut self, threshold: usize) {
        self.inner.set_split_threshold(threshold);
    }

    /// Bound `/Kids` chain traversal to `max_depth` levels.
    ///
    /// Unbounded by default; a caller reading an untrusted document should
    /// set this (e.g. to [`DEFAULT_MAX_TREE_DEPTH`]) to reject a
    /// pathologically deep tree with [`crate::Error::Unsupported`] instead
    /// of recursing without bound.
    pub fn set_max_depth(&mut self, max_depth: usize) {
        self.inner.max_depth = Some(max_depth);
    }
}

/// Cursor over a [`NumberTree`].
pub struct NumberTreeCursor {
    inner: NNTreeCursor<NumberKey>,
    owner: Arc<()>,
}

impl Clone for NumberTreeCursor {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            owner: Arc::clone(&self.owner),
        }
    }
}

impl PartialEq for NumberTreeCursor {
    fn eq(&self, other: &Self) -> bool {
        self.inner.same_position(&other.inner)
    }
}

impl Eq for NumberTreeCursor {}

impl NumberTreeCursor {
    /// Whether the cursor points to a valid key/value pair.
    pub fn valid(&self) -> bool {
        self.inner.cloned_current().is_some()
    }

    /// Return a clone of the current key/value pair.
    pub fn current(&self) -> Option<(i64, ObjectHandle)> {
        self.inner.cloned_current()
    }

    /// Advance to the next entry.
    ///
    /// Advancing an end cursor selects the first entry, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed, or the
    /// cursor belongs to another tree.
    pub fn next<R: Read + Seek>(&mut self, tree: &mut NumberTree, pdf: &mut Pdf<R>) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner.next(pdf, &mut self.inner)
    }

    /// Move to the previous entry.
    ///
    /// Moving an end cursor backward selects the last entry, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or traversed, or the
    /// cursor belongs to another tree.
    pub fn previous<R: Read + Seek>(
        &mut self,
        tree: &mut NumberTree,
        pdf: &mut Pdf<R>,
    ) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner.previous(pdf, &mut self.inner)
    }

    /// Insert an entry immediately after the cursor and select it.
    ///
    /// This fast path does not validate key ordering, matching qpdf.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated, or the
    /// cursor belongs to another tree.
    pub fn insert_after<R: Read + Seek>(
        &mut self,
        tree: &mut NumberTree,
        pdf: &mut Pdf<R>,
        key: i64,
        value: ObjectHandle,
    ) -> Result<()> {
        self.ensure_owner(tree)?;
        tree.inner.insert_after(pdf, &mut self.inner, key, value)
    }

    /// Remove the current entry and advance to the next entry.
    ///
    /// # Errors
    ///
    /// Returns an error when the tree cannot be resolved or mutated, the
    /// cursor belongs to another tree, or the cursor is invalid.
    pub fn remove<R: Read + Seek>(
        &mut self,
        tree: &mut NumberTree,
        pdf: &mut Pdf<R>,
    ) -> Result<()> {
        self.ensure_owner(tree)?;
        if !self.valid() {
            return Err(Error::Unsupported(
                "attempted to remove an invalid number-tree cursor".to_string(),
            ));
        }
        tree.inner.remove_at(pdf, &mut self.inner).map(|_| ())
    }

    fn ensure_owner(&self, tree: &NumberTree) -> Result<()> {
        if Arc::ptr_eq(&self.owner, &tree.cursor_owner) {
            Ok(())
        } else {
            Err(Error::Unsupported(
                "number-tree cursor belongs to a different tree".to_string(),
            ))
        }
    }
}

impl<K: TreeKey> NNTree<K> {
    fn new(root: ObjectHandle, auto_repair: bool) -> Self {
        Self {
            root,
            root_pdf_id: None,
            auto_repair,
            split_threshold: DEFAULT_SPLIT_THRESHOLD,
            max_depth: None,
            marker: PhantomData,
        }
    }

    fn ensure_root<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<ObjectHandle> {
        let pdf_id = pdf.unique_id();
        ensure_tree_root_pdf(&self.root, self.root_pdf_id, pdf_id)?;
        if self.root_pdf_id.is_none() {
            self.root_pdf_id = Some(pdf_id);
        }
        Ok(self.root.clone())
    }

    pub(crate) fn begin<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NNTreeCursor<K>> {
        let mut cursor = NNTreeCursor::for_pdf(pdf.unique_id());
        let root = self.root_node(pdf)?;
        self.descend(pdf, &mut cursor, root, true, true)?;
        Ok(cursor)
    }

    pub(crate) fn end(&self) -> NNTreeCursor<K> {
        NNTreeCursor::empty()
    }

    pub(crate) fn last<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NNTreeCursor<K>> {
        let mut cursor = NNTreeCursor::for_pdf(pdf.unique_id());
        let root = self.root_node(pdf)?;
        self.descend(pdf, &mut cursor, root, false, true)?;
        Ok(cursor)
    }

    pub(crate) fn next<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
    ) -> Result<()> {
        cursor.ensure_pdf(pdf)?;
        self.increment(pdf, cursor, false)
    }

    pub(crate) fn previous<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
    ) -> Result<()> {
        cursor.ensure_pdf(pdf)?;
        self.increment(pdf, cursor, true)
    }

    pub(crate) fn find<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: &K::Key,
        return_previous_if_missing: bool,
    ) -> Result<NNTreeCursor<K>> {
        match self.find_internal(pdf, key, return_previous_if_missing) {
            Ok(cursor) => Ok(cursor),
            Err(Error::QpdfExc(warning)) if self.auto_repair => {
                let root = self.root_node(pdf)?;
                let mut detail = b"attempting to repair after error: ".to_vec();
                detail.extend_from_slice(warning.what_bytes());
                self.warn_bytes(pdf, &root, &detail)?;
                self.repair(pdf)?;
                self.find_internal(pdf, key, return_previous_if_missing)
            }
            Err(error) => Err(error),
        }
    }

    pub(crate) fn set_split_threshold(&mut self, threshold: usize) {
        self.split_threshold = threshold;
    }

    fn insert<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: K::Key,
        value: ObjectHandle,
    ) -> Result<NNTreeCursor<K>> {
        ensure_value_owned_by_pdf(pdf, &value)?;
        let mut allocator = ObjectAllocator::default();
        self.insert_with_allocator(pdf, &mut allocator, key, value)
    }

    fn insert_with_allocator<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &mut ObjectAllocator,
        key: K::Key,
        value: ObjectHandle,
    ) -> Result<NNTreeCursor<K>> {
        self.insert_pair_with_allocator(pdf, allocator, K::to_handle(&key), value)
    }

    fn insert_resolved_with_allocator<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &mut ObjectAllocator,
        key: K::Key,
        raw_key: ObjectHandle,
        value: ObjectHandle,
    ) -> Result<NNTreeCursor<K>> {
        let mut cursor = self.find(pdf, &key, true)?;
        if !cursor.positioned() {
            return self.insert_first(pdf, allocator, raw_key, value);
        }

        let is_exact = cursor
            .current_key()
            .is_some_and(|current_key| K::compare(&key, current_key) == Ordering::Equal);
        if is_exact {
            let leaf = cursor.leaf.clone().expect("valid cursor has a leaf");
            let item_number = cursor.item_number.expect("valid cursor has an item");
            let dictionary = self.load_node(pdf, &leaf)?;
            let Some(mut items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
                // cov:ignore-start: find returns only a leaf with an items array; no mutation callback can remove it before this reload
                return Err(structural_error(
                    &pdf.input_description(),
                    leaf.diagnostic_ref(),
                    "node contains no items array",
                ));
                // cov:ignore-end
            };
            items.values[item_number + 1] = value;
            items.store()?;
            self.update_current(pdf, &mut cursor, false)?;
        } else {
            self.insert_after_with_allocator(pdf, allocator, &mut cursor, raw_key, value)?;
        }
        Ok(cursor)
    }

    fn insert_after<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
        key: K::Key,
        value: ObjectHandle,
    ) -> Result<()> {
        cursor.ensure_pdf(pdf)?;
        ensure_value_owned_by_pdf(pdf, &value)?;
        let mut allocator = ObjectAllocator::default();
        self.insert_after_with_allocator(pdf, &mut allocator, cursor, K::to_handle(&key), value)
    }

    fn insert_after_with_allocator<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &mut ObjectAllocator,
        cursor: &mut NNTreeCursor<K>,
        raw_key: ObjectHandle,
        value: ObjectHandle,
    ) -> Result<()> {
        if !cursor.positioned() {
            *cursor = self.insert_first(pdf, allocator, raw_key, value)?;
            return Ok(());
        }

        let leaf = cursor.leaf.clone().expect("valid cursor has a leaf");
        let item_number = cursor.item_number.expect("valid cursor has an item");
        let dictionary = self.load_node(pdf, &leaf)?;
        let Some(mut items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
            // cov:ignore-start: malformed item arrays are rejected by the canonical NNTree loader before mutation
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                "node contains no items array",
            ));
            // cov:ignore-end
        };
        // cov:ignore-start: a positioned live cursor has already passed the item-array shape check
        if items.values.len() < item_number + 2 {
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                "insert: items array is too short",
            ));
            // cov:ignore-end
        }
        self.ensure_split_allocations_available(pdf, allocator, cursor, items.values.len() + 2)?;
        items.values.insert(item_number + 2, raw_key);
        items.values.insert(item_number + 3, value);
        items.store()?;
        self.reset_limits(pdf, cursor, leaf, cursor.path.len().checked_sub(1))?;
        cursor.item_number = Some(item_number + 2);
        self.update_current(pdf, cursor, false)?;
        let leaf = cursor.leaf.clone().expect("inserted item has a leaf");
        self.split_node_live(pdf, cursor, leaf, cursor.path.len().checked_sub(1))
    }

    fn remove<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: &K::Key,
    ) -> Result<Option<ObjectHandle>> {
        let mut cursor = self.find(pdf, key, false)?;
        let Some((_, value)) = cursor.cloned_current() else {
            return Ok(None);
        };
        self.remove_at(pdf, &mut cursor)?;
        Ok(Some(value))
    }

    fn remove_at<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
    ) -> Result<Option<ObjectHandle>> {
        cursor.ensure_pdf(pdf)?;
        self.remove_at_inner(pdf, cursor)
    }

    fn remove_at_inner<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
    ) -> Result<Option<ObjectHandle>> {
        // cov:ignore-start: public cursor removal and the keyed remove path validate current first
        let Some((_, removed_value)) = cursor.cloned_current() else {
            return Ok(None);
        };
        // cov:ignore-end
        let leaf = cursor.leaf.clone().expect("valid cursor has a leaf");
        let item_number = cursor.item_number.expect("valid cursor has an item");
        let dictionary = self.load_node(pdf, &leaf)?;
        let Some(mut items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
            // cov:ignore-start: malformed item arrays are rejected by the canonical NNTree loader before mutation
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                "node contains no items array",
            ));
            // cov:ignore-end
        };
        // cov:ignore-start: a positioned live cursor has already passed the item-array shape check
        if item_number + 2 > items.values.len() {
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                "found short items array while removing an item",
            ));
            // cov:ignore-end
        }
        items.values.drain(item_number..item_number + 2);
        let remaining = items.values.len();
        items.store()?;

        if remaining > 0 {
            if item_number == 0 || item_number == remaining {
                self.reset_limits(pdf, cursor, leaf.clone(), cursor.path.len().checked_sub(1))?;
            }
            if item_number == remaining {
                cursor.item_number = item_number.checked_sub(2);
                self.update_current(pdf, cursor, false)?;
                self.next(pdf, cursor)?;
            } else {
                self.update_current(pdf, cursor, false)?;
            }
            return Ok(Some(removed_value));
        }

        if cursor.path.is_empty() {
            cursor.item_number = None;
            cursor.current = None;
            self.reset_limits(pdf, cursor, leaf, None)?;
            return Ok(Some(removed_value));
        }

        self.remove_empty_leaf(pdf, cursor)?;
        Ok(Some(removed_value))
    }

    fn insert_first<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &mut ObjectAllocator,
        raw_key: ObjectHandle,
        value: ObjectHandle,
    ) -> Result<NNTreeCursor<K>> {
        let mut cursor = self.begin(pdf)?;
        let leaf = cursor.leaf.clone().ok_or_else(|| {
            structural_error(
                &pdf.input_description(),
                None,
                "unable to find a valid items node",
            )
        })?;
        let dictionary = self.load_node(pdf, &leaf)?;
        // cov:ignore-start: begin returns an empty cursor leaf only after observing its items array
        let Some(mut items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
            return Err(structural_error(
                &pdf.input_description(),
                self.root_node(pdf)?.diagnostic_ref(),
                "unable to find a valid items node",
            ));
            // cov:ignore-end
        };
        self.ensure_split_allocations_available(pdf, allocator, &cursor, items.values.len() + 2)?;
        items.values.insert(0, raw_key);
        items.values.insert(1, value);
        items.store()?;
        cursor.item_number = Some(0);
        self.update_current(pdf, &mut cursor, true)?;
        let parent_index = cursor.path.len().checked_sub(1);
        self.reset_limits(pdf, &cursor, leaf.clone(), parent_index)?;
        self.split_node_live(pdf, &mut cursor, leaf, parent_index)?;
        Ok(cursor)
    }

    fn repair<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<()> {
        let replacement_root = ObjectHandle::dictionary(vec![(
            canonical_dictionary_key(K::ITEMS_KEY.as_bytes()),
            ObjectHandle::array(Vec::new()),
        )]);
        let mut replacement = NNTree::<K>::new(replacement_root, false);
        replacement.root_pdf_id = Some(pdf.unique_id());

        let mut allocator = ObjectAllocator::default();
        let mut cursor = self.begin(pdf)?;
        while cursor.positioned() {
            let leaf = cursor
                .leaf
                .clone()
                .expect("a positioned NNTree cursor retains a leaf");
            let dictionary = self.load_node(pdf, &leaf)?;
            let items = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())?
                .expect("a positioned NNTree cursor retains an items array");
            let item_number = cursor
                .item_number
                .expect("a positioned NNTree cursor retains an item number");
            let key = items.values[item_number].clone();
            let value = items.values[item_number + 1].clone();
            replacement.insert_pair_with_allocator(pdf, &mut allocator, key, value)?;
            self.increment(pdf, &mut cursor, false)?;
        }

        let replacement = replacement.ensure_root(pdf)?;
        self.replace_root_contents(pdf, replacement)
    }

    fn ensure_split_allocations_available<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &ObjectAllocator,
        cursor: &NNTreeCursor<K>,
        item_array_len: usize,
    ) -> Result<()> {
        if item_array_len <= 2 * self.split_threshold {
            return Ok(());
        }

        // qpdf's split allocation calls nextObjGen(), which first prepares the
        // canonical cache through fixDanglingReferences. Do that before the
        // caller mutates the live items array so parser-discovered dangling
        // references participate in the same signed object-number preflight.
        pdf.next_obj_gen()?;

        let mut allocations = 0usize;
        let mut parent_index = cursor.path.len().checked_sub(1);
        loop {
            let Some(index) = parent_index else {
                allocations += 2;
                break;
            };
            allocations += 1;

            let parent_handle = &cursor.path[index].node;
            let parent = self.load_node(pdf, parent_handle)?;
            // cov:ignore-start: the cursor path was built from this parent's /Kids array
            let Some(kids) = resolved_array(parent.get("Kids")?.as_ref())? else {
                return Err(structural_error(
                    &pdf.input_description(),
                    parent_handle.diagnostic_ref(),
                    "node is missing /Kids",
                ));
            };
            // cov:ignore-end
            if kids.values.len() < self.split_threshold {
                break;
            }
            parent_index = index.checked_sub(1);
        }

        allocator.ensure_available(pdf, allocations)
    }

    fn replace_root_contents<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        replacement: ObjectHandle,
    ) -> Result<()> {
        let root = self.root_node(pdf)?;
        let current = self.load_node(pdf, &root)?;
        let replacement = self.load_node(pdf, &NodeHandle::root(replacement))?;
        current.remove("Kids");
        current.remove(K::ITEMS_KEY);
        if let Some(kids) = replacement.get("Kids")? {
            current.insert("Kids", kids)?;
        }
        if let Some(items) = replacement.get(K::ITEMS_KEY)? {
            current.insert(K::ITEMS_KEY, items)?;
        }
        Ok(())
    }

    fn split_node_live<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
        mut node: NodeHandle,
        mut parent_index: Option<usize>,
    ) -> Result<()> {
        let dictionary = self.load_node(pdf, &node)?;
        let kids = resolved_array(dictionary.get("Kids")?.as_ref())?;
        let items = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())?;
        let (array_key, array, threshold, is_leaf) = if let Some(kids) = kids {
            if kids.values.is_empty() {
                return Ok(());
            }
            ("Kids", kids, self.split_threshold, false) // cov:ignore: LLVM assigns this tuple edge to an unexecuted region; internal Kids splitting is covered by the recursive branch
        } else if let Some(items) = items {
            if items.values.is_empty() {
                return Ok(());
            }
            (K::ITEMS_KEY, items, 2 * self.split_threshold, true)
        } else {
            // cov:ignore-start: split_node_live is reached only after a validated node has selected Kids or items
            return Err(structural_error(
                &pdf.input_description(),
                node.diagnostic_ref(),
                "split called on invalid node",
            ));
            // cov:ignore-end
        };
        if array.values.len() <= threshold {
            return Ok(());
        }

        let is_root = parent_index.is_none();
        if is_root {
            let first_dictionary = ObjectHandle::dictionary(vec![(
                canonical_dictionary_key(array_key.as_bytes()),
                array.handle.clone(),
            )]);
            let first_object = pdf.make_indirect_from_object_handle(first_dictionary)?;
            let first_ref = first_object
                .object_ref()
                .expect("canonical allocation returns an indirect node");
            let first_handle = NodeHandle::indirect(first_ref, first_object);

            let root = self.load_node(pdf, &node)?;
            root.remove("Limits");
            root.remove(K::ITEMS_KEY);
            root.insert("Kids", ObjectHandle::array(vec![first_handle.handle()]))?; // cov:ignore: split allocates the replacement node in this same PDF
            if is_leaf {
                cursor.leaf = Some(first_handle.clone());
            } else if let Some(first_path) = cursor.path.first_mut() {
                first_path.node = first_handle.clone();
            }
            cursor.path.insert(
                0,
                PathElement {
                    node: node.clone(),
                    kid_number: 0,
                },
            );
            parent_index = Some(0);
            node = first_handle;
        }

        let parent_index = parent_index.expect("root was normalized above");
        let first_dictionary = self.load_node(pdf, &node)?;
        // cov:ignore-start: array_key was selected from this same node before root normalization
        let Some(mut first_half) = resolved_array(first_dictionary.get(array_key)?.as_ref())?
        else {
            return Err(structural_error(
                &pdf.input_description(),
                node.diagnostic_ref(),
                format!("/{array_key} is not an array"),
            ));
        };
        // cov:ignore-end
        // Item arrays alternate key/value pairs; /Kids entries are independent.
        let midpoint = first_half.values.len() / 2;
        let start_index = if is_leaf { midpoint & !1 } else { midpoint };
        let second_half = first_half.values.split_off(start_index);
        first_half.store()?;
        self.reset_limits(pdf, cursor, node.clone(), Some(parent_index))?;

        let second_dictionary = ObjectHandle::dictionary(vec![(
            canonical_dictionary_key(array_key.as_bytes()),
            ObjectHandle::array(second_half),
        )]);
        let second_object = pdf.make_indirect_from_object_handle(second_dictionary)?;
        let second_ref = second_object
            .object_ref()
            .expect("canonical allocation returns an indirect node");
        let second_handle = NodeHandle::indirect(second_ref, second_object);
        self.reset_limits(pdf, cursor, second_handle.clone(), Some(parent_index))?;

        let parent_handle = cursor.path[parent_index].node.clone();
        let parent = self.load_node(pdf, &parent_handle)?;
        // cov:ignore-start: split cursor path was built from this parent Kids array
        let Some(mut parent_kids) = resolved_array(parent.get("Kids")?.as_ref())? else {
            return Err(structural_error(
                &pdf.input_description(),
                parent_handle.diagnostic_ref(),
                "node is missing /Kids",
            ));
        };
        // cov:ignore-end
        let first_kid_index = cursor.path[parent_index].kid_number;
        parent_kids
            .values
            .insert(first_kid_index + 1, second_handle.handle());
        parent_kids.store()?;

        let old_index = if is_leaf {
            cursor.item_number.expect("split cursor points to an item")
        } else {
            cursor.path[parent_index + 1].kid_number
        };
        if old_index >= start_index {
            cursor.path[parent_index].kid_number += 1;
            if is_leaf {
                cursor.leaf = Some(second_handle);
                cursor.item_number = Some(old_index - start_index);
                self.update_current(pdf, cursor, false)?;
            } else {
                cursor.path[parent_index + 1].node = second_handle;
                cursor.path[parent_index + 1].kid_number -= start_index;
            }
        } // cov:ignore: LLVM assigns an uncovered region to this delimiter although both cursor-adjustment arms above execute

        if !is_root {
            let parent_handle = cursor.path[parent_index].node.clone();
            let grandparent_index = parent_index.checked_sub(1);
            self.reset_limits(pdf, cursor, parent_handle.clone(), grandparent_index)?;
            self.split_node_live(pdf, cursor, parent_handle, grandparent_index)?;
            // cov:ignore: LLVM assigns the covered recursive call terminator a zero-count region
        }
        Ok(())
    }

    fn reset_limits<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &NNTreeCursor<K>,
        mut node: NodeHandle,
        mut parent_index: Option<usize>,
    ) -> Result<()> {
        loop {
            let dictionary = self.load_node(pdf, &node)?;
            let Some(index) = parent_index else {
                dictionary.remove("Limits");
                return Ok(());
            };

            let new_limits = self.edge_limits(pdf, &dictionary)?;
            let changed = match new_limits {
                Some((first, last)) => {
                    let old_limits = resolved_array(dictionary.get("Limits")?.as_ref())?;
                    let unchanged = if let Some(old_limits) = old_limits {
                        if old_limits.values.len() == 2 {
                            let old_first = resolved_key::<K>(&old_limits.values[0])?;
                            let old_last = resolved_key::<K>(&old_limits.values[1])?;
                            let new_first = resolved_key::<K>(&first)?;
                            let new_last = resolved_key::<K>(&last)?;
                            matches!(
                                (old_first, old_last, new_first, new_last),
                                (
                                    Some(old_first),
                                    Some(old_last),
                                    Some(new_first),
                                    Some(new_last)
                                ) if K::compare(&old_first, &new_first) == Ordering::Equal
                                    && K::compare(&old_last, &new_last) == Ordering::Equal
                            )
                        } else {
                            false
                        }
                    } else {
                        false
                    };
                    if unchanged {
                        false
                    } else {
                        dictionary.insert("Limits", ObjectHandle::array(vec![first, last]))?;
                        true
                    }
                }
                None => {
                    self.warn(pdf, &node, "unable to determine limits")?;
                    true
                }
            };

            if !changed || index == 0 {
                return Ok(());
            }
            node = cursor.path[index].node.clone();
            parent_index = index.checked_sub(1);
        }
    }

    fn edge_limits<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        dictionary: &LiveDictionary,
    ) -> Result<Option<(ObjectHandle, ObjectHandle)>> {
        if let Some(items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? {
            if items.values.len() >= 2 {
                return Ok(Some((
                    items.values[0].clone(),
                    items.values[(items.values.len() - 1) & !1].clone(),
                )));
            }
        }
        if let Some(kids) = resolved_array(dictionary.get("Kids")?.as_ref())? {
            if let (Some(first_kid), Some(last_kid)) = (kids.values.first(), kids.values.last()) {
                first_kid.try_dereference()?;
                let first_kid = first_kid.clone();
                if !first_kid.try_is_dictionary()? {
                    return Ok(None);
                }
                last_kid.try_dereference()?;
                let last_kid = last_kid.clone();
                if !last_kid.try_is_dictionary()? {
                    return Ok(None);
                }
                let filename = pdf.input_description();
                let first = LiveDictionary::new(first_kid.clone(), &filename)?;
                let last = LiveDictionary::new(last_kid.clone(), &filename)?;
                let Some(first_limits) = resolved_array(first.get("Limits")?.as_ref())? else {
                    return Ok(None);
                };
                let Some(last_limits) = resolved_array(last.get("Limits")?.as_ref())? else {
                    return Ok(None);
                };
                if first_limits.values.len() >= 2 && last_limits.values.len() >= 2 {
                    return Ok(Some((
                        first_limits.values[0].clone(),
                        last_limits.values[1].clone(),
                    )));
                } // cov:ignore: LLVM assigns the covered successful edge-limit return region to this delimiter
            } // cov:ignore: LLVM assigns the covered non-empty Kids branch region to this delimiter
        }
        Ok(None)
    }

    fn remove_empty_leaf<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
    ) -> Result<()> {
        loop {
            let path_index = cursor.path.len() - 1;
            let parent_handle = cursor.path[path_index].node.clone();
            let removed_kid = cursor.path[path_index].kid_number;
            let parent = self.load_node(pdf, &parent_handle)?;
            let Some(mut kids) = resolved_array(parent.get("Kids")?.as_ref())? else {
                // cov:ignore-start: remove_empty_leaf receives path nodes created by descend, which validates /Kids
                return Err(structural_error(
                    &pdf.input_description(),
                    parent_handle.diagnostic_ref(),
                    "node is missing /Kids",
                ));
                // cov:ignore-end
            };
            kids.values.remove(removed_kid);
            let remaining_kids = kids.values.len();
            let remaining_kid_values = kids.values.clone();
            kids.store()?;

            if remaining_kids > 0 {
                if removed_kid == 0 || removed_kid == remaining_kids {
                    self.reset_limits(
                        pdf,
                        cursor,
                        parent_handle.clone(),
                        path_index.checked_sub(1),
                    )?; // cov:ignore: LLVM maps this covered multi-line call terminator to a zero-count region
                } // cov:ignore: LLVM maps this covered limit-reset branch delimiter to a zero-count region
                cursor.clear_position();
                if removed_kid == remaining_kids {
                    cursor.path[path_index].kid_number -= 1;
                    let previous = remaining_kid_values.last().expect("non-empty").clone();
                    let child =
                        self.prepare_kid(pdf, &parent_handle, remaining_kids - 1, previous)?;
                    self.descend(pdf, cursor, child, false, true)?;
                    if cursor.positioned() {
                        self.next(pdf, cursor)?;
                    } // cov:ignore: LLVM maps this covered conditional delimiter to a zero-count region
                } else {
                    let next = remaining_kid_values[removed_kid].clone();
                    let child = self.prepare_kid(pdf, &parent_handle, removed_kid, next)?;
                    self.descend(pdf, cursor, child, true, true)?;
                }
                return Ok(());
            }

            if path_index == 0 {
                let root = self.load_node(pdf, &parent_handle)?;
                root.remove("Kids");
                root.insert(K::ITEMS_KEY, ObjectHandle::array(Vec::new()))?;
                cursor.path.clear();
                cursor.clear_position();
                return Ok(());
            }
            cursor.path.pop();
        }
    }

    fn find_internal<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: &K::Key,
        return_previous_if_missing: bool,
    ) -> Result<NNTreeCursor<K>> {
        let first = self.begin(pdf)?;
        if !first.positioned() {
            return Ok(self.end());
        }
        if let Some(first_key) = first.current_key() {
            if K::compare(key, first_key) == Ordering::Less {
                return Ok(self.end());
            }
        }
        // qpdf 11.9.0 initializes its `last_item` check with end(), not
        // last(), so after-maximum keys intentionally use the general search.

        let root = self.root_node(pdf)?;
        let root_diagnostic_ref = root.diagnostic_ref();
        let mut node = root;
        // `ObjectHandleIdentity` hashes and compares only its Rc allocation
        // pointer; the RefCell payload cannot change the set key.
        #[allow(clippy::mutable_key_type)]
        let mut seen: HashSet<NodeIdentity> = HashSet::new();
        let mut cursor = NNTreeCursor::for_pdf(pdf.unique_id());

        loop {
            if self
                .max_depth
                .is_some_and(|max_depth| cursor.path.len() >= max_depth)
            {
                let max_depth = self.max_depth.expect("checked above");
                // cov:ignore-start: depth-limit formatting is a defensive bounded-traversal diagnostic
                return Err(Error::Unsupported(format!(
                    "name/number tree: /Kids depth limit {max_depth} exceeded" // cov:ignore: depth-limit formatting is a defensive bounded-traversal diagnostic
                )));
                // cov:ignore-end
            }
            // cov:ignore-start: identity-cycle rejection is a defensive guard after canonical traversal bookkeeping
            if !seen.insert(node.identity()) {
                return Err(structural_error(
                    &pdf.input_description(),
                    node.diagnostic_ref(),
                    "loop detected in find",
                ));
            }
            // cov:ignore-end

            let dictionary = self.load_node(pdf, &node).map_err(|error| {
                // cov:ignore-start: begin() has already traversed this same live node path; without a mutation boundary, this defensive reload error cannot be reached
                structuralize(
                    &pdf.input_description(),
                    error,
                    node.diagnostic_ref(),
                    "bad node during find",
                )
            })?; // cov:ignore-end
            let items_source = dictionary.get(K::ITEMS_KEY)?;
            let items = resolved_array(items_source.as_ref())?;
            let kids_source = dictionary.get("Kids")?;
            let kids = resolved_array(kids_source.as_ref())?;

            if let Some(items) = items.as_ref().filter(|items| !items.values.is_empty()) {
                let index = binary_search(
                    items.values.len() / 2,
                    return_previous_if_missing,
                    |index| {
                        let item_number = 2 * index;
                        let Some(item) = items.values.get(item_number) else {
                            // cov:ignore-start: binary_search only supplies indices below items length divided by two
                            return Err(structural_error(
                                &pdf.input_description(),
                                root_diagnostic_ref,
                                format!("item at index {item_number} is not the right type"),
                            ));
                            // cov:ignore-end
                        };
                        let Some(item_key) = resolved_key::<K>(item)? else {
                            return Err(structural_error(
                                &pdf.input_description(),
                                root_diagnostic_ref,
                                format!("item at index {item_number} is not the right type"),
                            ));
                        };
                        Ok(K::compare(key, &item_key))
                    },
                )?;
                if let Some(index) = index {
                    cursor.leaf = Some(node);
                    cursor.item_number = Some(2 * index);
                    self.update_current(pdf, &mut cursor, false)?;
                }
                return Ok(cursor);
            }

            if let Some(kids) = kids.filter(|kids| !kids.values.is_empty()) {
                let index = binary_search(kids.values.len(), true, |index| {
                    let kid = kids
                        .values
                        .get(index)
                        .expect("binary-search index is in range");
                    let filename = pdf.input_description();
                    kid.try_dereference()?;
                    if !kid.try_is_dictionary()? {
                        return Err(structural_error(
                            &filename,
                            root_diagnostic_ref,
                            format!("invalid kid at index {index}"),
                        ));
                    }
                    let kid_dictionary = LiveDictionary::new(kid.clone(), &filename)?;
                    self.within_limits(pdf, key, &kid_dictionary, kid.object_ref())
                })?;
                // cov:ignore-start: binary_search supplies an in-range index and validated limits for every kid
                let index = index.ok_or_else(|| {
                    structural_error(
                        &pdf.input_description(),
                        node.diagnostic_ref(),
                        "unexpected -1 from binary search of kids; limits may by wrong",
                    )
                })?;
                // cov:ignore-end
                let kid_object = kids.values[index].clone();
                cursor.path.push(PathElement {
                    node: node.clone(),
                    kid_number: index,
                });
                node = self.handle_for_kid(&node, index, &kid_object)?;
                continue;
            }

            // cov:ignore-start: a node with neither items nor Kids cannot be produced by canonical tree construction
            return Err(structural_error(
                &pdf.input_description(),
                node.diagnostic_ref(),
                "bad node during find",
            ));
            // cov:ignore-end
        }
    }

    fn within_limits<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        key: &K::Key,
        dictionary: &LiveDictionary,
        object_ref: Option<ObjectRef>,
    ) -> Result<Ordering> {
        let Some(limits) = resolved_array(dictionary.get("Limits")?.as_ref())? else {
            // cov:ignore-start: update_current is called only for a live leaf with a validated item array
            return Err(structural_error(
                &pdf.input_description(),
                object_ref,
                "node is missing /Limits",
            ));
            // cov:ignore-end
        };
        let (Some(first), Some(last)) = (
            limits
                .values
                .first()
                .map(|value| resolved_key::<K>(value))
                .transpose()?
                .flatten(),
            limits
                .values
                .get(1)
                .map(|value| resolved_key::<K>(value))
                .transpose()?
                .flatten(),
        ) else {
            // cov:ignore-start: malformed item keys are rejected by find before update_current is reached
            return Err(structural_error(
                &pdf.input_description(),
                object_ref,
                "node is missing /Limits",
            ));
            // cov:ignore-end
        };
        if K::compare(key, &first) == Ordering::Less {
            Ok(Ordering::Less)
        } else if K::compare(key, &last) == Ordering::Greater {
            Ok(Ordering::Greater)
        } else {
            Ok(Ordering::Equal)
        }
    }

    fn handle_for_kid(
        &mut self,
        parent: &NodeHandle,
        kid_number: usize,
        kid: &ObjectHandle,
    ) -> Result<NodeHandle> {
        let kid = kid.clone();
        if let Some(object_ref) = kid.object_ref() {
            Ok(NodeHandle::indirect(object_ref, kid))
        } else {
            Ok(parent.direct_kid(kid_number, kid))
        }
    }

    fn root_node<R: Read + Seek>(&mut self, pdf: &mut Pdf<R>) -> Result<NodeHandle> {
        let root = self.ensure_root(pdf)?;
        Ok(match root.object_ref() {
            Some(object_ref) => NodeHandle::indirect(object_ref, root),
            None => NodeHandle::root(root),
        })
    }

    fn descend<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
        start: NodeHandle,
        first: bool,
        allow_empty: bool,
    ) -> Result<bool> {
        let original_path = cursor.path.clone();
        let original_leaf = cursor.leaf.clone();
        let original_item_number = cursor.item_number;
        let original_current = cursor.current.clone();
        // `ObjectHandleIdentity` hashes and compares only its Rc allocation
        // pointer; the RefCell payload cannot change the set key.
        #[allow(clippy::mutable_key_type)]
        let mut seen: HashSet<NodeIdentity> = cursor
            .path
            .iter()
            .map(|element| element.node.identity())
            .collect();
        let mut node = start;

        loop {
            if self
                .max_depth
                .is_some_and(|max_depth| cursor.path.len() >= max_depth)
            {
                let max_depth = self.max_depth.expect("checked above");
                return Err(Error::Unsupported(format!(
                    "name/number tree: /Kids depth limit {max_depth} exceeded"
                )));
            }
            if !seen.insert(node.identity()) {
                self.warn(
                    pdf,
                    &node,
                    "loop detected while traversing name/number tree",
                )?;
                break;
            }

            let dictionary = match self.load_node(pdf, &node) {
                Ok(dictionary) => dictionary,
                Err(error) => {
                    if matches!(error, Error::QpdfExc(_)) {
                        self.warn(
                            pdf,
                            &node,
                            "non-dictionary node while traversing name/number tree",
                        )?;
                        break;
                    }
                    return Err(error);
                }
            };
            let items_source = dictionary.get(K::ITEMS_KEY)?;
            let items = resolved_array(items_source.as_ref())?;
            let kids_source = dictionary.get("Kids")?;
            let kids = resolved_array(kids_source.as_ref())?;

            if let Some(items) = items.as_ref().filter(|items| !items.values.is_empty()) {
                let item_number = if first {
                    0
                } else {
                    // qpdf 11.9.0 NNTreeIterator::deepen uses nitems - 2
                    // verbatim, including value-slot selection in odd arrays.
                    items.values.len().saturating_sub(2)
                };
                cursor.leaf = Some(node);
                cursor.item_number = Some(item_number);
                self.update_current(pdf, cursor, true)?;
                return Ok(true);
            }

            if let Some(kids) = kids.filter(|kids| !kids.values.is_empty()) {
                let kid_number = if first { 0 } else { kids.values.len() - 1 };
                let kid_object = kids.values[kid_number].clone();
                cursor.path.push(PathElement {
                    node: node.clone(),
                    kid_number,
                });
                node = self.prepare_kid(pdf, &node, kid_number, kid_object)?;
                continue;
            }

            if allow_empty && items.is_some() {
                cursor.leaf = Some(node);
                cursor.item_number = None;
                cursor.current = None;
                return Ok(true);
            }

            self.warn(
                pdf,
                &node,
                format!(
                    "name/number tree node has neither non-empty /{} nor /Kids",
                    K::ITEMS_KEY
                ),
            )?;
            break;
        }

        cursor.path = original_path;
        cursor.leaf = original_leaf;
        cursor.item_number = original_item_number;
        cursor.current = original_current;
        Ok(false)
    }

    fn increment<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
        backward: bool,
    ) -> Result<()> {
        if cursor.item_number.is_none() {
            cursor.path.clear();
            cursor.clear_position();
            let root = self.root_node(pdf)?;
            self.descend(pdf, cursor, root, !backward, true)?;
            return Ok(());
        }

        loop {
            let leaf = cursor.leaf.clone().expect("valid cursor has a leaf");
            let dictionary = self.load_node(pdf, &leaf)?;
            let Some(items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
                cursor.clear_position();
                return Ok(());
            };
            let item_number = cursor.item_number.expect("checked above");
            let candidate = if backward {
                item_number.checked_sub(2)
            } else {
                item_number
                    .checked_add(2)
                    .filter(|index| *index < items.values.len())
            };

            if let Some(candidate) = candidate {
                cursor.item_number = Some(candidate);
                if candidate + 1 >= items.values.len() {
                    self.warn(pdf, &leaf, "items array doesn't have enough elements")?;
                    cursor.current = None;
                    continue;
                }
                self.update_current(pdf, cursor, true)?;
                if cursor.current.is_some() {
                    return Ok(());
                }
                self.warn(pdf, &leaf, format!("item {candidate} has the wrong type"))?;
                continue;
            }

            cursor.clear_position();
            let mut descended = false;
            while let Some(last_index) = cursor.path.len().checked_sub(1) {
                let parent = cursor.path[last_index].node.clone();
                let dictionary = self.load_node(pdf, &parent)?;
                let Some(kids) = resolved_array(dictionary.get("Kids")?.as_ref())? else {
                    cursor.path.pop();
                    continue;
                };
                let mut kid_number = cursor.path[last_index].kid_number;
                loop {
                    let next_index = if backward {
                        kid_number.checked_sub(1)
                    } else {
                        kid_number
                            .checked_add(1)
                            .filter(|index| *index < kids.values.len())
                    };
                    let Some(next_index) = next_index else {
                        break;
                    };
                    kid_number = next_index;
                    let kid_object = kids.values[kid_number].clone();
                    if !self.kid_has_tree_shape(pdf, &kid_object)? {
                        self.warn(
                            pdf,
                            &parent,
                            format!("skipping over invalid kid at index {kid_number}"),
                        )?;
                        continue;
                    }
                    cursor.path[last_index].kid_number = kid_number;
                    let kid = self.prepare_kid(pdf, &parent, kid_number, kid_object)?;
                    if self.descend(pdf, cursor, kid, !backward, false)? {
                        if cursor.current.is_none() {
                            let item_number = cursor
                                .item_number
                                .expect("descended non-empty leaf has an item number");
                            self.warn(
                                pdf,
                                cursor.leaf.as_ref().expect("descended leaf is present"),
                                format!("item {item_number} has the wrong type"),
                            )?;
                        }
                        descended = true;
                        break;
                    }
                }
                if descended {
                    break;
                }
                cursor.path.pop();
            }

            if !descended {
                return Ok(());
            }
            if cursor.current.is_some() {
                return Ok(());
            }
        }
    }

    fn update_current<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        cursor: &mut NNTreeCursor<K>,
        allow_invalid: bool,
    ) -> Result<()> {
        cursor.current = None;
        let (Some(leaf), Some(item_number)) = (&cursor.leaf, cursor.item_number) else {
            return Ok(());
        };
        let dictionary = self.load_node(pdf, leaf)?;
        // cov:ignore-start: update_current is called only for a live leaf with a validated item array
        let Some(items) = resolved_array(dictionary.get(K::ITEMS_KEY)?.as_ref())? else {
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                format!("update ivalue: /{} is not an array", K::ITEMS_KEY),
            ));
        };
        // cov:ignore-end
        if item_number + 1 >= items.values.len() {
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                "update ivalue: items array is too short",
            ));
        }
        let raw_key = items.values[item_number].clone();
        let raw_value = items.values[item_number + 1].clone();
        // cov:ignore-start: malformed item keys are rejected by find before update_current is reached
        let Some(key) = resolved_key::<K>(&raw_key)? else {
            if allow_invalid {
                return Ok(());
            }
            return Err(structural_error(
                &pdf.input_description(),
                leaf.diagnostic_ref(),
                format!("item at index {item_number} is not the right type"),
            ));
        };
        // cov:ignore-end
        cursor.current = Some((key, raw_value));
        Ok(())
    }

    fn insert_pair_with_allocator<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        allocator: &mut ObjectAllocator,
        key: ObjectHandle,
        value: ObjectHandle,
    ) -> Result<NNTreeCursor<K>> {
        if let Some(resolved_key) = resolved_key::<K>(&key)? {
            self.insert_resolved_with_allocator(pdf, allocator, resolved_key, key, value)
        } else {
            // cov:ignore-start: increment skips later malformed keys before repair observes them
            // qpdf can insert the first pair into an empty replacement
            // before its next insert observes that the key is invalid. Later
            // malformed keys are skipped by increment and never reach this
            // path.
            let cursor = self.begin(pdf)?;
            if cursor.positioned() {
                Err(structural_error(
                    &pdf.input_description(),
                    self.root_node(pdf)?.diagnostic_ref(),
                    "item at index 0 is not the right type",
                ))
                // cov:ignore-end
            } else {
                self.insert_first(pdf, allocator, key, value)
            }
        }
    }

    fn prepare_kid<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        parent: &NodeHandle,
        kid_number: usize,
        kid_object: ObjectHandle,
    ) -> Result<NodeHandle> {
        if let Some(object_ref) = kid_object.object_ref() {
            return Ok(NodeHandle::indirect(object_ref, kid_object));
        }

        if self.auto_repair {
            self.warn(
                pdf,
                parent,
                format!("converting kid number {kid_number} to an indirect object"),
            )?;
            let indirect = pdf.make_indirect_from_object_handle(kid_object)?;
            let object_ref = indirect
                .object_ref()
                .expect("canonical allocation returns an indirect kid");
            let dictionary = self.load_node(pdf, parent)?;
            let Some(mut kids) = resolved_array(dictionary.get("Kids")?.as_ref())? else {
                // cov:ignore-start: prepare_kid receives kid_object from this same parent Kids array; its parent Kids array cannot disappear between these calls
                return Err(structural_error(
                    &pdf.input_description(),
                    parent.diagnostic_ref(),
                    "node is missing /Kids",
                ));
                // cov:ignore-end
            };
            kids.values[kid_number] = indirect.clone();
            kids.store()?;
            Ok(NodeHandle::indirect(object_ref, indirect))
        } else {
            self.warn(
                pdf,
                parent,
                format!("kid number {kid_number} is not an indirect object"),
            )?;
            Ok(parent.direct_kid(kid_number, kid_object))
        }
    }

    fn kid_has_tree_shape<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        kid: &ObjectHandle,
    ) -> Result<bool> {
        if !kid.try_is_dictionary()? {
            return Ok(false); // cov:ignore: non-dictionary kids are rejected by LiveDictionary before traversal
        }
        let filename = pdf.input_description();
        let dictionary = LiveDictionary::new(kid.clone(), &filename)?;
        if dictionary.contains("Kids")? {
            return Ok(true); // cov:ignore: a Kids-shaped node is normalized through the canonical child path
        }
        dictionary.contains(K::ITEMS_KEY)
    }

    fn warn<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        node: &NodeHandle,
        message: impl AsRef<str>,
    ) -> Result<()> {
        self.warn_bytes(pdf, node, message.as_ref().as_bytes())
    }

    fn warn_bytes<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        node: &NodeHandle,
        message: &[u8],
    ) -> Result<()> {
        let object = match node.diagnostic_ref() {
            Some(object_ref) => format!("Name/Number tree node (object {})", object_ref.number),
            None => "Name/Number tree node".to_owned(),
        };
        pdf.push_qpdf_warning(QpdfExc::new(
            QpdfErrorCode::DamagedPdf,
            pdf.input_description(),
            object,
            0,
            message,
        ))
    }

    fn load_node<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        handle: &NodeHandle,
    ) -> Result<LiveDictionary> {
        let node = self.load_anchor(pdf, handle)?;
        let filename = pdf.input_description();
        LiveDictionary::new(node, &filename)
    }

    fn load_anchor<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        handle: &NodeHandle,
    ) -> Result<ObjectHandle> {
        let live = handle.handle();
        if matches!(handle.anchor, NodeAnchor::Root)
            && handle.direct_kids.is_empty()
            && self.root.is_same_object_as(&live)
        {
            return self.ensure_root(pdf);
        }
        Ok(live)
    }
}

#[derive(Default)]
struct ObjectAllocator {
    next: Option<u64>,
}

impl ObjectAllocator {
    fn next_number<R: Read + Seek>(&self, pdf: &Pdf<R>) -> u64 {
        self.next.unwrap_or_else(|| {
            let legacy_max = pdf
                .canonical_object_refs()
                .into_iter()
                .map(|object_ref| u64::from(object_ref.number))
                .max()
                .unwrap_or(0);
            let canonical_max = pdf.resolver.max_object_number().map(u64::from).unwrap_or(0);
            legacy_max.max(canonical_max) + 1
        })
    }

    fn ensure_available<R: Read + Seek>(&self, pdf: &Pdf<R>, count: usize) -> Result<()> {
        debug_assert!(count > 0);
        let available = (i32::MAX as u64 + 1).saturating_sub(self.next_number(pdf));
        if (count as u64) <= available {
            Ok(())
        } else {
            Err(Error::Unsupported(
                "object-number space exhausted".to_string(),
            ))
        }
    }
}

fn binary_search<F>(
    count: usize,
    return_previous_if_missing: bool,
    mut compare: F,
) -> Result<Option<usize>>
where
    F: FnMut(usize) -> Result<Ordering>,
{
    let mut max_index = 1usize;
    while max_index < count {
        max_index <<= 1;
    }
    let mut step = max_index / 2;
    let mut checks = max_index;
    let mut index = step;
    let mut found_index = None;
    let mut found = false;
    let mut found_less_or_equal = false;

    while !found && checks > 0 {
        let status = if index < count {
            let status = compare(index)?;
            if status != Ordering::Less {
                found_less_or_equal = true;
                found_index = Some(index);
            }
            status
        } else {
            Ordering::Less
        };
        if status == Ordering::Equal {
            found = true;
        } else {
            checks >>= 1;
            if checks > 0 {
                step >>= 1;
                if step == 0 {
                    step = 1;
                }
                if status == Ordering::Less {
                    index = index.saturating_sub(step);
                } else {
                    index = index.saturating_add(step);
                }
            }
        }
    }

    Ok(
        if found || (found_less_or_equal && return_previous_if_missing) {
            found_index
        } else {
            None
        },
    )
}

fn structuralize(
    filename: &[u8],
    error: Error,
    object_ref: Option<ObjectRef>,
    message: impl AsRef<str>,
) -> Error {
    match error {
        Error::Parse { .. } => structural_error(filename, object_ref, message),
        other => other,
    }
}

fn structural_error(
    filename: &[u8],
    object_ref: Option<ObjectRef>,
    message: impl AsRef<str>,
) -> Error {
    let object = match object_ref {
        Some(object_ref) => format!("Name/Number tree node (object {})", object_ref.number),
        None => "Name/Number tree node".to_owned(),
    };
    Error::QpdfExc(QpdfExc::new(
        QpdfErrorCode::DamagedPdf,
        filename,
        object,
        0,
        message.as_ref(),
    ))
}

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

    #[test]
    fn find_reports_an_invalid_middle_kid_after_begin_takes_leftmost_path() {
        let leaf = |first, last| {
            ObjectHandle::dictionary(vec![
                (
                    b"/Limits".to_vec(),
                    ObjectHandle::array(vec![
                        ObjectHandle::integer(first),
                        ObjectHandle::integer(last),
                    ]),
                ),
                (
                    b"/Nums".to_vec(),
                    ObjectHandle::array(vec![
                        ObjectHandle::integer(first),
                        ObjectHandle::integer(1),
                    ]),
                ),
            ])
        };
        let root = ObjectHandle::dictionary(vec![(
            b"/Kids".to_vec(),
            ObjectHandle::array(vec![leaf(0, 9), ObjectHandle::integer(7), leaf(20, 29)]),
        )]);
        let mut pdf = Pdf::empty().expect("empty PDF");
        let mut tree = NumberTree::new(root, false);

        let error = tree
            .find_object(&mut pdf, 15)
            .expect_err("binary search must inspect the invalid middle kid");
        assert!(matches!(
            error,
            Error::QpdfExc(warning)
                if warning.get_object() == b"Name/Number tree node"
                    && warning.get_message_detail() == b"invalid kid at index 1"
        ));
    }

    #[test]
    fn find_rejects_kids_with_missing_or_malformed_limits() {
        for limits in [
            ObjectHandle::null(),
            ObjectHandle::array(vec![]),
            ObjectHandle::array(vec![ObjectHandle::integer(0)]),
        ] {
            let leaf = ObjectHandle::dictionary(vec![
                (b"Limits".to_vec(), limits),
                (
                    b"Nums".to_vec(),
                    ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(1)]),
                ),
            ]);
            let root =
                ObjectHandle::dictionary(vec![(b"Kids".to_vec(), ObjectHandle::array(vec![leaf]))]);
            let mut pdf = Pdf::empty().expect("empty PDF");
            let mut tree = NumberTree::new(root, false);
            assert!(
                tree.find_object(&mut pdf, 0).is_err(),
                "malformed Limits must be rejected"
            );
        }
    }

    #[test]
    fn find_reports_bad_leaf_items_empty_nodes_and_out_of_range_kids() {
        let mut pdf = Pdf::empty().expect("empty PDF");
        let bad_items = ObjectHandle::dictionary(vec![
            (
                b"Limits".to_vec(),
                ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(9)]),
            ),
            (
                b"Nums".to_vec(),
                ObjectHandle::array(vec![
                    ObjectHandle::name(b"bad".to_vec()),
                    ObjectHandle::integer(1),
                ]),
            ),
        ]);
        assert!(NumberTree::new(bad_items, false)
            .find_object(&mut pdf, 0)
            .is_err());

        let leaf = ObjectHandle::dictionary(vec![
            (
                b"Limits".to_vec(),
                ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(9)]),
            ),
            (
                b"Nums".to_vec(),
                ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(1)]),
            ),
        ]);
        let root =
            ObjectHandle::dictionary(vec![(b"Kids".to_vec(), ObjectHandle::array(vec![leaf]))]);
        assert!(NumberTree::new(root, false)
            .find_object(&mut pdf, 20)
            .is_ok());
    }

    #[test]
    fn structuralize_rewrites_parse_errors_but_preserves_operations() {
        let parse = structuralize(
            b"",
            Error::parse(17, "raw parse"),
            Some(ObjectRef::new(8, 0)),
            "bad node",
        );
        assert!(matches!(
            parse,
            Error::QpdfExc(warning)
                if warning.get_object() == b"Name/Number tree node (object 8)"
                    && warning.get_message_detail() == b"bad node"
        ));

        let system = structuralize(
            b"",
            Error::System("sink write failure 1".to_owned()),
            Some(ObjectRef::new(8, 0)),
            "bad node",
        );
        assert!(matches!(
            system,
            Error::System(message) if message == "sink write failure 1"
        ));
    }

    #[test]
    fn live_dictionary_indirect_bad_node_preserves_qpdf_exception_fields() {
        let pdf = Pdf::empty().expect("empty PDF");
        let node = pdf
            .make_indirect_from_object_handle(ObjectHandle::integer(7))
            .expect("indirect integer node");
        let object_number = node.object_ref().unwrap().number;
        let error = LiveDictionary::new(node, b"input\xFF.pdf")
            .err()
            .expect("an indirect integer is a bad name/number tree node");
        let object = format!("Name/Number tree node (object {object_number})");
        let mut what = b"input\xFF.pdf (".to_vec();
        what.extend_from_slice(object.as_bytes());
        what.extend_from_slice(b"): bad node");
        assert!(matches!(
            error,
            Error::QpdfExc(warning)
                if warning.get_error_code() == QpdfErrorCode::DamagedPdf
                    && warning.get_filename() == b"input\xFF.pdf"
                    && warning.get_object() == object.as_bytes()
                    && warning.get_file_position() == 0
                    && warning.get_message_detail() == b"bad node"
                    && warning.what_bytes() == what.as_slice()
        ));
    }

    #[test]
    fn tree_shape_probe_distinguishes_scalar_and_kids_nodes() {
        let mut pdf = Pdf::empty().expect("empty PDF");
        let mut tree = NNTree::<NumberKey>::new(ObjectHandle::null(), false);
        assert!(!tree
            .kid_has_tree_shape(&mut pdf, &ObjectHandle::integer(1))
            .expect("scalar shape probe"));
        let kids =
            ObjectHandle::dictionary(vec![(b"Kids".to_vec(), ObjectHandle::array(Vec::new()))]);
        assert!(tree
            .kid_has_tree_shape(&mut pdf, &kids)
            .expect("Kids shape probe"));
    }
}