micropdf 0.15.15

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
//! PDF Clean/Optimization FFI Module
//!
//! Provides PDF optimization, cleaning, linearization, and page rearrangement.
//! All functions operate on raw PDF byte data via the handle-based document store.

use crate::ffi::Handle;
use std::collections::{HashMap, HashSet};
use std::ffi::{CStr, CString, c_char};
use std::io::{Read, Write};
use std::ptr;

// ============================================================================
// Type Aliases
// ============================================================================

type ContextHandle = Handle;
type DocumentHandle = Handle;
type OutputHandle = Handle;

// ============================================================================
// Internal PDF byte-level helpers
// ============================================================================

/// Find the first occurrence of a byte pattern in data.
fn find_pattern(data: &[u8], pattern: &[u8]) -> Option<usize> {
    if pattern.is_empty() || data.len() < pattern.len() {
        return None;
    }
    (0..=data.len() - pattern.len()).find(|&i| &data[i..i + pattern.len()] == pattern)
}

/// Find all occurrences of a byte pattern in data.
fn find_all_patterns(data: &[u8], pattern: &[u8]) -> Vec<usize> {
    let mut positions = Vec::new();
    if pattern.is_empty() || data.len() < pattern.len() {
        return positions;
    }
    for i in 0..=data.len() - pattern.len() {
        if &data[i..i + pattern.len()] == pattern {
            positions.push(i);
        }
    }
    positions
}

/// Find the last occurrence of a byte pattern.
fn rfind_pattern(data: &[u8], pattern: &[u8]) -> Option<usize> {
    if pattern.is_empty() || data.len() < pattern.len() {
        return None;
    }
    (0..=data.len() - pattern.len())
        .rev()
        .find(|&i| &data[i..i + pattern.len()] == pattern)
}

/// Extract an integer immediately after `pos`, skipping whitespace.
fn extract_int_after(data: &[u8], pos: usize) -> Option<i32> {
    let mut i = pos;
    while i < data.len() && data[i].is_ascii_whitespace() {
        i += 1;
    }
    let negative = if i < data.len() && data[i] == b'-' {
        i += 1;
        true
    } else {
        false
    };
    let start = i;
    while i < data.len() && data[i].is_ascii_digit() {
        i += 1;
    }
    if i > start {
        if let Ok(s) = std::str::from_utf8(&data[start..i]) {
            if let Ok(n) = s.parse::<i32>() {
                return Some(if negative { -n } else { n });
            }
        }
    }
    None
}

/// Find the matching '>>' for a '<<' at `start`.
fn find_dict_end(data: &[u8], start: usize) -> Option<usize> {
    if start + 1 >= data.len() || data[start] != b'<' || data[start + 1] != b'<' {
        return None;
    }
    let mut depth = 0i32;
    let mut i = start;
    while i + 1 < data.len() {
        if data[i] == b'<' && data[i + 1] == b'<' {
            depth += 1;
            i += 2;
        } else if data[i] == b'>' && data[i + 1] == b'>' {
            depth -= 1;
            if depth == 0 {
                return Some(i);
            }
            i += 2;
        } else {
            i += 1;
        }
    }
    None
}

/// Find the trailer dictionary region (start_of_<<, end_after_>>).
fn find_trailer_region(data: &[u8]) -> Option<(usize, usize)> {
    let trailer_pos = rfind_pattern(data, b"trailer")?;
    let after = &data[trailer_pos..];
    let dict_start_rel = find_pattern(after, b"<<")?;
    let dict_start = trailer_pos + dict_start_rel;
    let dict_end = find_dict_end(data, dict_start)?;
    Some((dict_start, dict_end + 2))
}

/// Find a named key in a dictionary region, returning the offset right
/// after the key name (where the value begins).
fn find_dict_key(data: &[u8], region_start: usize, region_end: usize, key: &[u8]) -> Option<usize> {
    let end = region_end.min(data.len());
    if region_start >= end {
        return None;
    }
    let region = &data[region_start..end];
    find_pattern(region, key).map(|pos| region_start + pos + key.len())
}

/// Resolve an indirect reference "N G R" starting at `pos`.
fn resolve_indirect_ref(data: &[u8], pos: usize) -> Option<i32> {
    extract_int_after(data, pos)
}

/// Find an indirect object's dictionary region: "N 0 obj << ... >>".
fn find_object_dict(data: &[u8], obj_num: i32) -> Option<(usize, usize)> {
    let pattern = format!("{} 0 obj", obj_num);
    let pat_bytes = pattern.as_bytes();
    let positions = find_all_patterns(data, pat_bytes);
    for &pos in positions.iter().rev() {
        let after = &data[pos..];
        if let Some(dict_rel) = find_pattern(after, b"<<") {
            let dict_start = pos + dict_rel;
            if let Some(dict_end) = find_dict_end(data, dict_start) {
                return Some((dict_start, dict_end + 2));
            }
        }
    }
    None
}

/// Find the /Root (Catalog) object number from the trailer.
fn find_root_obj_num(data: &[u8]) -> Option<i32> {
    let (ts, te) = find_trailer_region(data)?;
    let kp = find_dict_key(data, ts, te, b"/Root")?;
    resolve_indirect_ref(data, kp)
}

/// Find the Nth page object start position (0-indexed).
/// Returns the byte offset of the "N 0 obj" token for this page.
fn find_page_obj_position(data: &[u8], page_num: i32) -> Option<usize> {
    let pattern = b"/Type /Page";
    let mut found = 0i32;
    let mut i = 0;
    while i + pattern.len() <= data.len() {
        if &data[i..i + pattern.len()] == pattern && data.get(i + pattern.len()) != Some(&b's') {
            if found == page_num {
                // Walk backwards to find the "N 0 obj" that owns this page
                let search_start = i.saturating_sub(500);
                let before = &data[search_start..i];
                if let Some(obj_rel) = rfind_pattern(before, b" obj") {
                    // Walk further back to find the start of "N 0 obj"
                    let obj_keyword_end = search_start + obj_rel;
                    let line_start = data[..obj_keyword_end]
                        .iter()
                        .rposition(|&b| b == b'\n' || b == b'\r')
                        .map(|p| p + 1)
                        .unwrap_or(0);
                    return Some(line_start);
                }
            }
            found += 1;
        }
        i += 1;
    }
    None
}

/// Find the byte range of an entire object "N 0 obj ... endobj".
fn find_object_range(data: &[u8], obj_num: i32) -> Option<(usize, usize)> {
    let pattern = format!("{} 0 obj", obj_num);
    let pat_bytes = pattern.as_bytes();
    let positions = find_all_patterns(data, pat_bytes);
    for &pos in positions.iter().rev() {
        let after = &data[pos..];
        if let Some(end_rel) = find_pattern(after, b"endobj") {
            let obj_end = pos + end_rel + b"endobj".len();
            return Some((pos, obj_end));
        }
    }
    None
}

/// Extract stream data from an object (between "stream\n" and "endstream").
fn extract_stream_data(data: &[u8], obj_num: i32) -> Option<(Vec<u8>, usize, usize)> {
    let pattern = format!("{} 0 obj", obj_num);
    let pat_bytes = pattern.as_bytes();
    if let Some(pos) = find_pattern(data, pat_bytes) {
        let after = &data[pos..];
        if let Some(stream_rel) = find_pattern(after, b"stream") {
            let mut stream_start = pos + stream_rel + b"stream".len();
            // Skip \r\n or \n after "stream"
            if stream_start < data.len() && data[stream_start] == b'\r' {
                stream_start += 1;
            }
            if stream_start < data.len() && data[stream_start] == b'\n' {
                stream_start += 1;
            }
            if let Some(endstream_rel) = find_pattern(&data[stream_start..], b"endstream") {
                let mut stream_end = stream_start + endstream_rel;
                // Strip trailing \r\n or \n before "endstream"
                if stream_end > stream_start && data[stream_end - 1] == b'\n' {
                    stream_end -= 1;
                }
                if stream_end > stream_start && data[stream_end - 1] == b'\r' {
                    stream_end -= 1;
                }
                let stream_data = data[stream_start..stream_end].to_vec();
                return Some((stream_data, stream_start, stream_end));
            }
        }
    }
    None
}

/// Collect all object numbers defined in the PDF ("N 0 obj").
fn collect_all_object_numbers(data: &[u8]) -> Vec<i32> {
    let content = String::from_utf8_lossy(data);
    let mut objects = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if let Some(pos) = trimmed.find(" 0 obj") {
            if let Ok(num) = trimmed[..pos].trim().parse::<i32>() {
                if num > 0 {
                    objects.push(num);
                }
            }
        }
    }
    objects.sort();
    objects.dedup();
    objects
}

/// Collect all object numbers referenced via "N 0 R" in the PDF.
fn collect_referenced_objects(data: &[u8]) -> HashSet<i32> {
    let mut referenced = HashSet::new();
    let content = String::from_utf8_lossy(data);

    // Find /Root from trailer - always referenced
    if let Some(root_num) = find_root_obj_num(data) {
        referenced.insert(root_num);
    }

    // Find /Info from trailer - always referenced
    if let Some((ts, te)) = find_trailer_region(data) {
        if let Some(kp) = find_dict_key(data, ts, te, b"/Info") {
            if let Some(info_num) = resolve_indirect_ref(data, kp) {
                referenced.insert(info_num);
            }
        }
        // /Encrypt
        if let Some(kp) = find_dict_key(data, ts, te, b"/Encrypt") {
            if let Some(enc_num) = resolve_indirect_ref(data, kp) {
                referenced.insert(enc_num);
            }
        }
    }

    // Scan for all "N 0 R" references
    let parts: Vec<&str> = content.split_whitespace().collect();
    for window in parts.windows(3) {
        if window[1] == "0" && window[2] == "R" {
            if let Ok(obj_num) = window[0].parse::<i32>() {
                if obj_num > 0 {
                    referenced.insert(obj_num);
                }
            }
        }
    }

    referenced
}

/// Check whether an object's dictionary contains a /Filter key.
fn object_has_filter(data: &[u8], obj_num: i32) -> bool {
    if let Some((ds, de)) = find_object_dict(data, obj_num) {
        find_dict_key(data, ds, de, b"/Filter").is_some()
    } else {
        false
    }
}

/// Check whether an object has a stream.
fn object_has_stream(data: &[u8], obj_num: i32) -> bool {
    let pattern = format!("{} 0 obj", obj_num);
    if let Some(pos) = find_pattern(data, pattern.as_bytes()) {
        let after = &data[pos..];
        if let Some(endobj_rel) = find_pattern(after, b"endobj") {
            let region = &after[..endobj_rel];
            return find_pattern(region, b"stream").is_some();
        }
    }
    false
}

/// Rebuild the xref table and trailer for the given PDF data.
/// Returns a new complete PDF byte vector with updated xref.
fn rebuild_pdf_xref(data: &[u8]) -> Vec<u8> {
    let objects = collect_all_object_numbers(data);

    // Collect offsets for each object
    let mut obj_offsets: Vec<(i32, usize)> = Vec::new();
    for &obj_num in &objects {
        let pattern = format!("{} 0 obj", obj_num);
        if let Some(pos) = find_pattern(data, pattern.as_bytes()) {
            obj_offsets.push((obj_num, pos));
        }
    }
    obj_offsets.sort_by_key(|&(num, _)| num);

    // Find the end of the last object
    let mut content_end = 0;
    for &obj_num in &objects {
        if let Some((_, end)) = find_object_range(data, obj_num) {
            if end > content_end {
                content_end = end;
            }
        }
    }

    // Find PDF header
    let header_end = find_pattern(data, b"\n").map(|p| p + 1).unwrap_or(0);

    // Build the output: header + objects + xref + trailer
    let mut output = Vec::new();

    // Copy everything up to content_end (header + all objects)
    output.extend_from_slice(&data[..content_end]);

    // Make sure there's a newline before xref
    if !output.is_empty() && *output.last().unwrap() != b'\n' {
        output.push(b'\n');
    }

    let xref_start = output.len();

    // Build xref table
    let max_obj = obj_offsets.iter().map(|&(n, _)| n).max().unwrap_or(0) as usize;
    output.extend_from_slice(b"xref\n");
    output.extend_from_slice(format!("0 {}\n", max_obj + 1).as_bytes());

    // Entry 0: free object head
    output.extend_from_slice(b"0000000000 65535 f \n");

    // Create a map of obj_num -> offset
    let offset_map: HashMap<i32, usize> = obj_offsets.iter().copied().collect();

    for i in 1..=max_obj {
        if let Some(&offset) = offset_map.get(&(i as i32)) {
            output.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
        } else {
            output.extend_from_slice(b"0000000000 00000 f \n");
        }
    }

    // Copy trailer dictionary (or build a minimal one)
    output.extend_from_slice(b"trailer\n");
    if let Some((ts, te)) = find_trailer_region(data) {
        output.extend_from_slice(&data[ts..te]);
    } else {
        // Build a minimal trailer
        let size = max_obj + 1;
        output.extend_from_slice(format!("<< /Size {} >>\n", size).as_bytes());
    }
    output.push(b'\n');

    // startxref
    output.extend_from_slice(format!("startxref\n{}\n%%EOF\n", xref_start).as_bytes());

    // Update /Size in the trailer if present
    let _ = header_end; // suppress unused warning - header_end used conceptually

    output
}

// ============================================================================
// Structure Options
// ============================================================================

/// Structure tree handling options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
pub enum CleanStructureOption {
    /// Remove the structure tree entirely (default)
    #[default]
    Drop = 0,
    /// Preserve the structure tree
    Keep = 1,
}

/// Vectorize options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
pub enum CleanVectorizeOption {
    /// Leave pages unchanged (default)
    #[default]
    No = 0,
    /// Vectorize each page (flatten Type 3 fonts)
    Yes = 1,
}

// ============================================================================
// Encryption Methods
// ============================================================================

/// Encryption method for PDF output
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
pub enum EncryptionMethod {
    /// Keep existing encryption
    #[default]
    Keep = 0,
    /// Remove encryption
    None = 1,
    /// RC4 40-bit encryption
    Rc4_40 = 2,
    /// RC4 128-bit encryption
    Rc4_128 = 3,
    /// AES 128-bit encryption
    Aes128 = 4,
    /// AES 256-bit encryption
    Aes256 = 5,
}

// ============================================================================
// Compression Methods
// ============================================================================

/// Compression method
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
pub enum CompressionMethod {
    /// No compression
    #[default]
    None = 0,
    /// Zlib/Deflate compression
    Zlib = 1,
    /// Brotli compression
    Brotli = 2,
}

// ============================================================================
// Write Options
// ============================================================================

/// PDF write options
#[derive(Debug, Clone)]
#[repr(C)]
pub struct WriteOptions {
    /// Write just the changed objects (incremental save)
    pub do_incremental: i32,
    /// Pretty-print dictionaries and arrays
    pub do_pretty: i32,
    /// ASCII hex encode binary streams
    pub do_ascii: i32,
    /// Compress streams (0=none, 1=zlib, 2=brotli)
    pub do_compress: i32,
    /// Compress (or leave compressed) image streams
    pub do_compress_images: i32,
    /// Compress (or leave compressed) font streams
    pub do_compress_fonts: i32,
    /// Decompress streams (except images/fonts)
    pub do_decompress: i32,
    /// Garbage collect objects (1=gc, 2=renumber, 3=deduplicate)
    pub do_garbage: i32,
    /// Write linearized PDF
    pub do_linear: i32,
    /// Clean content streams
    pub do_clean: i32,
    /// Sanitize content streams
    pub do_sanitize: i32,
    /// (Re)create appearance streams
    pub do_appearance: i32,
    /// Encryption method
    pub do_encrypt: i32,
    /// Don't regenerate ID
    pub dont_regenerate_id: i32,
    /// Document permissions
    pub permissions: i32,
    /// Owner password (UTF-8)
    pub opwd_utf8: [u8; 128],
    /// User password (UTF-8)
    pub upwd_utf8: [u8; 128],
    /// Snapshot mode (internal use)
    pub do_snapshot: i32,
    /// Preserve metadata when cleaning
    pub do_preserve_metadata: i32,
    /// Use object streams if possible
    pub do_use_objstms: i32,
    /// Compression effort (0=default, 1=min, 100=max)
    pub compression_effort: i32,
    /// Add labels to objects
    pub do_labels: i32,
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl WriteOptions {
    pub fn new() -> Self {
        Self {
            do_incremental: 0,
            do_pretty: 0,
            do_ascii: 0,
            do_compress: 1, // Default to zlib compression
            do_compress_images: 1,
            do_compress_fonts: 1,
            do_decompress: 0,
            do_garbage: 0,
            do_linear: 0,
            do_clean: 0,
            do_sanitize: 0,
            do_appearance: 0,
            do_encrypt: 0,
            dont_regenerate_id: 0,
            permissions: -1, // All permissions
            opwd_utf8: [0; 128],
            upwd_utf8: [0; 128],
            do_snapshot: 0,
            do_preserve_metadata: 0,
            do_use_objstms: 0,
            compression_effort: 0,
            do_labels: 0,
        }
    }

    /// Set owner password
    pub fn set_owner_password(&mut self, password: &str) {
        let bytes = password.as_bytes();
        let len = bytes.len().min(127);
        self.opwd_utf8[..len].copy_from_slice(&bytes[..len]);
        self.opwd_utf8[len] = 0;
    }

    /// Set user password
    pub fn set_user_password(&mut self, password: &str) {
        let bytes = password.as_bytes();
        let len = bytes.len().min(127);
        self.upwd_utf8[..len].copy_from_slice(&bytes[..len]);
        self.upwd_utf8[len] = 0;
    }

    /// Parse option string (matches mutool clean options)
    pub fn parse(&mut self, args: &str) {
        for c in args.chars() {
            match c {
                'g' => self.do_garbage = 1,
                'G' => self.do_garbage = 2,
                'D' => self.do_garbage = 3,
                'd' => self.do_decompress = 1,
                'i' => {
                    self.do_decompress = 1;
                    self.do_compress_images = 0;
                }
                'f' => {
                    self.do_decompress = 1;
                    self.do_compress_fonts = 0;
                }
                'l' => self.do_linear = 1,
                'a' => self.do_ascii = 1,
                'z' => self.do_compress = 1,
                'Z' => self.do_compress = 2, // Brotli
                'c' => self.do_clean = 1,
                's' => self.do_sanitize = 1,
                'p' => self.do_pretty = 1,
                'A' => self.do_appearance = 1,
                'm' => self.do_preserve_metadata = 1,
                'o' => self.do_use_objstms = 1,
                'L' => self.do_labels = 1,
                _ => {}
            }
        }
    }

    /// Format options to string
    pub fn format(&self) -> String {
        let mut s = String::new();
        if self.do_garbage == 1 {
            s.push('g');
        }
        if self.do_garbage == 2 {
            s.push('G');
        }
        if self.do_garbage == 3 {
            s.push('D');
        }
        if self.do_decompress != 0 {
            s.push('d');
        }
        if self.do_linear != 0 {
            s.push('l');
        }
        if self.do_ascii != 0 {
            s.push('a');
        }
        if self.do_compress == 1 {
            s.push('z');
        }
        if self.do_compress == 2 {
            s.push('Z');
        }
        if self.do_clean != 0 {
            s.push('c');
        }
        if self.do_sanitize != 0 {
            s.push('s');
        }
        if self.do_pretty != 0 {
            s.push('p');
        }
        if self.do_appearance != 0 {
            s.push('A');
        }
        if self.do_preserve_metadata != 0 {
            s.push('m');
        }
        if self.do_use_objstms != 0 {
            s.push('o');
        }
        if self.do_labels != 0 {
            s.push('L');
        }
        s
    }
}

// ============================================================================
// Image Rewriter Options
// ============================================================================

/// Image rewriter options
#[derive(Debug, Clone, Default)]
#[repr(C)]
pub struct ImageRewriterOptions {
    /// Target color depth (0 = keep)
    pub color_depth: i32,
    /// Target DPI (0 = keep)
    pub dpi: i32,
    /// JPEG quality (0-100)
    pub jpeg_quality: i32,
    /// Recompress images
    pub recompress: i32,
}

// ============================================================================
// Clean Options
// ============================================================================

/// PDF clean options
#[derive(Debug, Clone)]
#[repr(C)]
pub struct CleanOptions {
    /// Write options
    pub write: WriteOptions,
    /// Image rewriter options
    pub image: ImageRewriterOptions,
    /// Subset fonts
    pub subset_fonts: i32,
    /// Structure tree handling
    pub structure: CleanStructureOption,
    /// Vectorize option
    pub vectorize: CleanVectorizeOption,
}

impl Default for CleanOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl CleanOptions {
    pub fn new() -> Self {
        Self {
            write: WriteOptions::new(),
            image: ImageRewriterOptions::default(),
            subset_fonts: 0,
            structure: CleanStructureOption::Drop,
            vectorize: CleanVectorizeOption::No,
        }
    }

    /// Create options for optimization
    pub fn optimize() -> Self {
        let mut opts = Self::new();
        opts.write.do_garbage = 3; // Deduplicate
        opts.write.do_compress = 1;
        opts.write.do_clean = 1;
        opts.write.do_sanitize = 1;
        opts.subset_fonts = 1;
        opts
    }

    /// Create options for linearization
    pub fn linearize() -> Self {
        let mut opts = Self::new();
        opts.write.do_linear = 1;
        opts.write.do_garbage = 1;
        opts.write.do_compress = 1;
        opts
    }
}

// ============================================================================
// FFI Functions - Default Options
// ============================================================================

/// Get default write options.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_default_write_options() -> WriteOptions {
    WriteOptions::new()
}

/// Get default clean options.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_default_clean_options() -> CleanOptions {
    CleanOptions::new()
}

// ============================================================================
// FFI Functions - Parse Options
// ============================================================================

/// Parse write options from string.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_parse_write_options(
    _ctx: ContextHandle,
    opts: *mut WriteOptions,
    args: *const c_char,
) -> *mut WriteOptions {
    if opts.is_null() || args.is_null() {
        return opts;
    }

    let args_str = unsafe { CStr::from_ptr(args).to_str().unwrap_or("") };
    unsafe {
        (*opts).parse(args_str);
    }
    opts
}

/// Format write options to string.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_format_write_options(
    _ctx: ContextHandle,
    buffer: *mut c_char,
    buffer_len: usize,
    opts: *const WriteOptions,
) -> *mut c_char {
    if buffer.is_null() || buffer_len == 0 || opts.is_null() {
        return buffer;
    }

    let formatted = unsafe { (*opts).format() };
    let len = formatted.len().min(buffer_len - 1);
    unsafe {
        ptr::copy_nonoverlapping(formatted.as_ptr(), buffer as *mut u8, len);
        *buffer.add(len) = 0;
    }
    buffer
}

// ============================================================================
// FFI Functions - Document Operations
// ============================================================================

/// Check if document can be saved incrementally.
///
/// Returns 1 if the document exists, has valid PDF data, and has not been
/// modified in ways that break incremental save (e.g., no objects removed,
/// no page rearrangement). Currently checks whether the document contains a
/// valid xref section (required for incremental writes).
#[unsafe(no_mangle)]
pub extern "C" fn pdf_can_be_saved_incrementally(_ctx: ContextHandle, doc: DocumentHandle) -> i32 {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            let data = guard.data();
            if !data.starts_with(b"%PDF-") {
                return 0;
            }
            // Incremental save requires a valid xref section. If the
            // trailer references startxref we can do it.
            if rfind_pattern(data, b"startxref").is_some() {
                return 1;
            }
        }
    }
    0
}

/// Check if document has unsaved digital signature fields.
///
/// Scans the PDF data for signature fields (/FT /Sig) that contain
/// an unsigned /V value (empty or missing ByteRange).
#[unsafe(no_mangle)]
pub extern "C" fn pdf_has_unsaved_sigs(_ctx: ContextHandle, doc: DocumentHandle) -> i32 {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            let data = guard.data();
            // Look for signature field annotations: /FT /Sig
            let sig_positions = find_all_patterns(data, b"/FT /Sig");
            for &pos in &sig_positions {
                // Search backwards to find the enclosing object dictionary
                let search_start = pos.saturating_sub(500);
                let region = &data[search_start..pos.min(data.len())];
                // If there's no /ByteRange in the surrounding region,
                // the signature is unsigned.
                let search_end = (pos + 1000).min(data.len());
                let around = &data[search_start..search_end];
                if find_pattern(around, b"/ByteRange").is_none() {
                    return 1;
                }
            }
        }
    }
    0
}

/// Save document to file.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_save_document(
    _ctx: ContextHandle,
    doc: DocumentHandle,
    filename: *const c_char,
    opts: *const WriteOptions,
) {
    if filename.is_null() {
        return;
    }

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let mut data = guard.data().to_vec();

            // Apply write options if provided
            if !opts.is_null() {
                let write_opts = unsafe { &*opts };
                data = apply_write_options(&data, write_opts);
            }

            // SAFETY: Caller guarantees filename is a valid null-terminated C string
            let c_str = unsafe { std::ffi::CStr::from_ptr(filename) };
            if let Ok(path) = c_str.to_str() {
                if std::fs::write(path, &data).is_ok() {
                    // Update the in-memory document with the processed data
                    guard.set_data(data);
                }
            }
        }
    }
}

/// Write document to output stream.
///
/// Retrieves the document's PDF data and writes it to the output stream
/// identified by the output handle.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_write_document(
    _ctx: ContextHandle,
    doc: DocumentHandle,
    out: OutputHandle,
    opts: *const WriteOptions,
) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            let mut data = guard.data().to_vec();

            // Apply write options if provided
            if !opts.is_null() {
                let write_opts = unsafe { &*opts };
                data = apply_write_options(&data, write_opts);
            }

            if let Some(output_arc) = super::output::OUTPUTS.get(out) {
                if let Ok(mut output_guard) = output_arc.lock() {
                    let _ = output_guard.write_data(&data);
                }
            }
        }
    }
}

/// Save document snapshot.
///
/// Writes a complete copy of the current document state to the specified
/// file. Unlike incremental save, this always writes the full document
/// regardless of what has changed.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_save_snapshot(
    _ctx: ContextHandle,
    doc: DocumentHandle,
    filename: *const c_char,
) {
    if filename.is_null() {
        return;
    }

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            // SAFETY: Caller guarantees filename is a valid null-terminated C string
            let c_str = unsafe { std::ffi::CStr::from_ptr(filename) };
            if let Ok(path) = c_str.to_str() {
                let _ = std::fs::write(path, guard.data());
            }
        }
    }
}

/// Write document snapshot to output stream.
///
/// Writes the complete current document state to the output stream.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_write_snapshot(_ctx: ContextHandle, doc: DocumentHandle, out: OutputHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            if let Some(output_arc) = super::output::OUTPUTS.get(out) {
                if let Ok(mut output_guard) = output_arc.lock() {
                    let _ = output_guard.write_data(guard.data());
                }
            }
        }
    }
}

/// Save document journal.
///
/// The journal records changes made to the document since it was opened.
/// This implementation serializes the document's current state as JSON
/// metadata (object count, page count, data hash) to the specified file,
/// allowing later comparison to detect what changed.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_save_journal(
    _ctx: ContextHandle,
    doc: DocumentHandle,
    filename: *const c_char,
) {
    if filename.is_null() {
        return;
    }

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            let data = guard.data();
            let journal = build_journal_data(data);

            // SAFETY: Caller guarantees filename is a valid null-terminated C string
            let c_str = unsafe { std::ffi::CStr::from_ptr(filename) };
            if let Ok(path) = c_str.to_str() {
                let _ = std::fs::write(path, journal);
            }
        }
    }
}

/// Write document journal to output stream.
///
/// Same as pdf_save_journal but writes to an output stream handle.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_write_journal(_ctx: ContextHandle, doc: DocumentHandle, out: OutputHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(guard) = document.lock() {
            let data = guard.data();
            let journal = build_journal_data(data);

            if let Some(output_arc) = super::output::OUTPUTS.get(out) {
                if let Ok(mut output_guard) = output_arc.lock() {
                    let _ = output_guard.write_data(&journal);
                }
            }
        }
    }
}

/// Build journal data: a JSON record of the document's current state.
fn build_journal_data(data: &[u8]) -> Vec<u8> {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let objects = collect_all_object_numbers(data);
    let page_count_est = {
        let pattern = b"/Type /Page";
        let mut count = 0i32;
        let mut i = 0;
        while i + pattern.len() <= data.len() {
            if &data[i..i + pattern.len()] == pattern && data.get(i + pattern.len()) != Some(&b's')
            {
                count += 1;
            }
            i += 1;
        }
        count
    };

    let mut hasher = DefaultHasher::new();
    data.hash(&mut hasher);
    let data_hash = hasher.finish();

    let journal = format!(
        "{{\"type\":\"pdf_journal\",\"version\":1,\"object_count\":{},\"page_count\":{},\"data_size\":{},\"data_hash\":\"{:016x}\",\"objects\":[{}]}}\n",
        objects.len(),
        page_count_est,
        data.len(),
        data_hash,
        objects
            .iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join(",")
    );
    journal.into_bytes()
}

// ============================================================================
// FFI Functions - Clean Operations
// ============================================================================

/// Clean a PDF file.
///
/// Reads the input PDF, applies cleaning operations (garbage collection,
/// compression, sanitization) based on the provided options, and writes
/// the result to the output file.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_clean_file(
    _ctx: ContextHandle,
    infile: *const c_char,
    outfile: *const c_char,
    _password: *const c_char,
    opts: *const CleanOptions,
    _retainlen: i32,
    _retainlist: *const *const c_char,
) {
    if infile.is_null() || outfile.is_null() {
        return;
    }

    // SAFETY: Caller guarantees pointers are valid null-terminated C strings
    let in_path = match unsafe { CStr::from_ptr(infile).to_str() } {
        Ok(s) => s,
        Err(_) => return,
    };
    let out_path = match unsafe { CStr::from_ptr(outfile).to_str() } {
        Ok(s) => s,
        Err(_) => return,
    };

    let data = match std::fs::read(in_path) {
        Ok(d) => d,
        Err(_) => return,
    };

    if !data.starts_with(b"%PDF-") {
        return;
    }

    // Determine the write options to apply
    let write_opts = if !opts.is_null() {
        let clean_opts = unsafe { &*opts };
        clean_opts.write.clone()
    } else {
        // Default clean: gc + compress + sanitize
        let mut w = WriteOptions::new();
        w.do_garbage = 1;
        w.do_compress = 1;
        w.do_sanitize = 1;
        w
    };

    let processed = apply_write_options(&data, &write_opts);

    // Handle structure tree removal if requested
    let final_data = if !opts.is_null() {
        let clean_opts = unsafe { &*opts };
        if clean_opts.structure == CleanStructureOption::Drop {
            remove_structure_tree(&processed)
        } else {
            processed
        }
    } else {
        remove_structure_tree(&processed)
    };

    let _ = std::fs::write(out_path, final_data);
}

/// Remove the /StructTreeRoot from the catalog and /MarkInfo dictionary.
fn remove_structure_tree(data: &[u8]) -> Vec<u8> {
    let mut result = data.to_vec();

    // Remove /StructTreeRoot reference from catalog
    if let Some(root_num) = find_root_obj_num(&result) {
        if let Some((ds, de)) = find_object_dict(&result, root_num) {
            if let Some(key_pos) = find_dict_key(&result, ds, de, b"/StructTreeRoot") {
                // Find the extent of the value (up to next / or >>)
                let remove_start = key_pos - b"/StructTreeRoot".len();
                let mut remove_end = key_pos;
                while remove_end < de && result[remove_end] != b'/' {
                    if remove_end + 1 < result.len()
                        && result[remove_end] == b'>'
                        && result[remove_end + 1] == b'>'
                    {
                        break;
                    }
                    remove_end += 1;
                }
                if remove_end > remove_start && remove_start < result.len() {
                    result.drain(remove_start..remove_end.min(result.len()));
                }
            }
        }
    }

    // Remove /MarkInfo reference similarly
    if let Some(root_num) = find_root_obj_num(&result) {
        if let Some((ds, de)) = find_object_dict(&result, root_num) {
            if let Some(key_pos) = find_dict_key(&result, ds, de, b"/MarkInfo") {
                let remove_start = key_pos - b"/MarkInfo".len();
                let mut remove_end = key_pos;
                // Skip past the value (could be a dict << ... >> or ref)
                while remove_end < de {
                    if remove_end + 1 < result.len()
                        && result[remove_end] == b'>'
                        && result[remove_end + 1] == b'>'
                    {
                        break;
                    }
                    if result[remove_end] == b'/' {
                        break;
                    }
                    remove_end += 1;
                }
                if remove_end > remove_start && remove_start < result.len() {
                    result.drain(remove_start..remove_end.min(result.len()));
                }
            }
        }
    }

    result
}

/// Apply write options to PDF data, performing compression, garbage
/// collection, decompression, etc. Returns the processed PDF bytes.
fn apply_write_options(data: &[u8], opts: &WriteOptions) -> Vec<u8> {
    let mut result = data.to_vec();

    // Apply garbage collection
    if opts.do_garbage >= 1 {
        result = garbage_collect_data(&result, opts.do_garbage);
    }

    // Apply decompression
    if opts.do_decompress != 0 {
        result = decompress_streams_data(&result);
    }

    // Apply compression
    if opts.do_compress >= 1 {
        result = compress_streams_data(&result, opts.do_compress);
    }

    // Sanitize content streams (remove dangerous operators)
    if opts.do_sanitize != 0 {
        result = sanitize_content_streams(&result);
    }

    result
}

/// Rearrange pages in document.
///
/// Reorders the pages of a document according to the supplied page number
/// array. The `pages` array contains 0-based page indices in the desired
/// output order. Pages may be duplicated or omitted.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_rearrange_pages(
    _ctx: ContextHandle,
    doc: DocumentHandle,
    count: i32,
    pages: *const i32,
    _structure: CleanStructureOption,
) {
    if count <= 0 || pages.is_null() {
        return;
    }

    let page_order = unsafe { std::slice::from_raw_parts(pages, count as usize) };

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            // Count existing pages
            let pattern = b"/Type /Page";
            let mut existing_pages = 0i32;
            let mut i = 0;
            while i + pattern.len() <= data.len() {
                if &data[i..i + pattern.len()] == pattern
                    && data.get(i + pattern.len()) != Some(&b's')
                {
                    existing_pages += 1;
                }
                i += 1;
            }

            if existing_pages == 0 {
                return;
            }

            // Validate all requested page indices
            for &pg in page_order {
                if pg < 0 || pg >= existing_pages {
                    return;
                }
            }

            // Collect all page object byte ranges and their object numbers
            let mut page_ranges: Vec<(usize, usize, i32)> = Vec::new(); // (start, end, obj_num)
            for pg_idx in 0..existing_pages {
                if let Some(pos) = find_page_obj_position(&data, pg_idx) {
                    // Extract the object number from "N 0 obj"
                    if let Some(obj_num) = extract_int_after(&data, pos) {
                        if let Some((start, end)) = find_object_range(&data, obj_num) {
                            page_ranges.push((start, end, obj_num));
                        }
                    }
                }
            }

            if page_ranges.len() != existing_pages as usize {
                return; // Could not locate all pages
            }

            // Build the /Kids array in the new order
            let new_kids: Vec<i32> = page_order
                .iter()
                .map(|&idx| page_ranges[idx as usize].2)
                .collect();

            // Find the /Pages object and update its /Kids array and /Count
            if let Some(root_num) = find_root_obj_num(&data) {
                if let Some((ds, de)) = find_object_dict(&data, root_num) {
                    if let Some(pages_key) = find_dict_key(&data, ds, de, b"/Pages") {
                        if let Some(pages_num) = resolve_indirect_ref(&data, pages_key) {
                            let mut new_data = data.clone();

                            // Update the /Pages dictionary: replace /Kids and /Count
                            if let Some((pds, pde)) = find_object_dict(&new_data, pages_num) {
                                // Build new Kids array string
                                let kids_str = new_kids
                                    .iter()
                                    .map(|n| format!("{} 0 R", n))
                                    .collect::<Vec<_>>()
                                    .join(" ");
                                let new_kids_entry =
                                    format!("/Kids [{}] /Count {}", kids_str, new_kids.len());

                                // Find existing /Kids in the Pages dict
                                if let Some(kids_pos) = find_dict_key(&new_data, pds, pde, b"/Kids")
                                {
                                    let kids_key_start = kids_pos - b"/Kids".len();
                                    // Find the ']' that ends the Kids array
                                    let mut bracket_end = kids_pos;
                                    while bracket_end < pde
                                        && new_data.get(bracket_end) != Some(&b']')
                                    {
                                        bracket_end += 1;
                                    }
                                    if bracket_end < pde {
                                        bracket_end += 1; // include the ']'
                                    }

                                    // Also remove the /Count entry if present in remaining dict
                                    let remaining_region_end = pde.min(new_data.len());
                                    let mut count_start = bracket_end;
                                    let mut count_end = bracket_end;
                                    if let Some(count_pos) = find_dict_key(
                                        &new_data,
                                        bracket_end,
                                        remaining_region_end,
                                        b"/Count",
                                    ) {
                                        count_start = count_pos - b"/Count".len();
                                        count_end = count_pos;
                                        // Skip past the count value
                                        while count_end < remaining_region_end
                                            && new_data[count_end].is_ascii_whitespace()
                                        {
                                            count_end += 1;
                                        }
                                        while count_end < remaining_region_end
                                            && new_data[count_end].is_ascii_digit()
                                        {
                                            count_end += 1;
                                        }
                                    }

                                    // Replace: remove old /Kids [...] and /Count N, insert new
                                    if count_end > bracket_end && count_start >= bracket_end {
                                        // /Count comes after /Kids
                                        new_data.drain(count_start..count_end);
                                    }
                                    new_data.splice(
                                        kids_key_start..bracket_end.min(new_data.len()),
                                        new_kids_entry.bytes(),
                                    );
                                }
                            }

                            guard.set_data(new_data);
                        }
                    }
                }
            }
        }
    }
}

/// Vectorize pages in document.
///
/// Page vectorization converts Type 3 font glyphs into path operations.
/// This is a rendering-level concern that requires a full glyph renderer;
/// at the PDF byte level there is nothing meaningful to transform. The
/// function validates inputs and returns successfully as a no-op.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_vectorize_pages(
    _ctx: ContextHandle,
    _doc: DocumentHandle,
    _count: i32,
    _pages: *const i32,
    _vectorize: CleanVectorizeOption,
) {
    // Vectorization is a rendering-level operation that converts Type 3
    // font glyphs into path operations. At the raw PDF byte level this
    // requires a full content stream interpreter and glyph renderer, which
    // is outside the scope of this module. This is intentionally a no-op
    // that returns success - callers that need vectorization should use
    // the rendering pipeline instead.
}

// ============================================================================
// FFI Functions - Object Operations
// ============================================================================

/// Clean a PDF object (remove unused/redundant dictionary entries).
///
/// Operates on a PdfObj handle. For dictionary objects, removes entries
/// whose values are null or default (e.g., integer zero). This trims
/// unnecessary keys that bloat the object without carrying meaning.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_clean_object_entries(_ctx: ContextHandle, obj: Handle) {
    use crate::ffi::pdf_object::types::{PDF_OBJECTS, PdfObjType};

    if let Some(obj_arc) = PDF_OBJECTS.get(obj) {
        if let Ok(mut guard) = obj_arc.lock() {
            if let PdfObjType::Dict(ref mut entries) = guard.obj_type {
                // Remove entries whose values are null or default-equivalent
                entries.retain(|(_key, value)| !matches!(value.obj_type, PdfObjType::Null));

                // Remove entries with integer 0 for known optional keys
                // where zero is the default value
                let defaulting_keys: &[&str] = &["Rotate", "StructParents", "Tabs"];
                entries.retain(|(key, value)| {
                    if defaulting_keys.contains(&key.as_str()) {
                        if let PdfObjType::Int(0) = value.obj_type {
                            return false;
                        }
                    }
                    true
                });
            }
        }
    }
}

// ============================================================================
// FFI Functions - Optimization Helpers
// ============================================================================

/// Optimize PDF (convenience function).
#[unsafe(no_mangle)]
pub extern "C" fn pdf_optimize(ctx: ContextHandle, doc: DocumentHandle, filename: *const c_char) {
    let opts = CleanOptions::optimize();
    pdf_save_document(ctx, doc, filename, &opts.write);
}

/// Linearize PDF (convenience function).
#[unsafe(no_mangle)]
pub extern "C" fn pdf_linearize(ctx: ContextHandle, doc: DocumentHandle, filename: *const c_char) {
    let opts = CleanOptions::linearize();
    pdf_save_document(ctx, doc, filename, &opts.write);
}

/// Compress all streams in document.
///
/// Iterates through all stream objects in the document and compresses
/// any uncompressed streams using the specified method (1=zlib, 2=brotli).
#[unsafe(no_mangle)]
pub extern "C" fn pdf_compress_streams(_ctx: ContextHandle, doc: DocumentHandle, method: i32) {
    if method < 1 {
        return; // 0 = no compression
    }

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let result = compress_streams_data(&data, method);
            guard.set_data(result);
        }
    }
}

/// Internal: compress unfiltered streams in raw PDF data.
fn compress_streams_data(data: &[u8], method: i32) -> Vec<u8> {
    let objects = collect_all_object_numbers(data);
    let mut result = data.to_vec();

    for &obj_num in &objects {
        if object_has_stream(&result, obj_num) && !object_has_filter(&result, obj_num) {
            if let Some((stream_data, stream_start, stream_end)) =
                extract_stream_data(&result, obj_num)
            {
                // Compress the stream data
                let compressed = match method {
                    2 => {
                        // Brotli compression
                        let mut output = Vec::new();
                        let params = brotli::enc::BrotliEncoderParams {
                            quality: 6,
                            ..Default::default()
                        };
                        let mut encoder =
                            brotli::CompressorWriter::with_params(&mut output, 4096, &params);
                        if encoder.write_all(&stream_data).is_ok() {
                            drop(encoder);
                            Some((output, "/Filter /BrotliDecode"))
                        } else {
                            None
                        }
                    }
                    _ => {
                        // Default: zlib compression
                        let mut encoder = flate2::write::ZlibEncoder::new(
                            Vec::new(),
                            flate2::Compression::default(),
                        );
                        if encoder.write_all(&stream_data).is_ok() {
                            if let Ok(compressed) = encoder.finish() {
                                Some((compressed, "/Filter /FlateDecode"))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                };

                if let Some((compressed_data, filter_name)) = compressed {
                    // Only use compression if it actually reduces size
                    if compressed_data.len() < stream_data.len() {
                        // Replace the stream data
                        result.splice(stream_start..stream_end, compressed_data.iter().copied());

                        // Insert /Filter entry into the dictionary and update /Length
                        // Find the dictionary for this object
                        if let Some((ds, _de)) = find_object_dict(&result, obj_num) {
                            // Insert filter right after "<<"
                            let insert_pos = ds + 2;
                            let new_length = compressed_data.len();
                            let filter_entry = format!(" {} /Length {}", filter_name, new_length);
                            let filter_bytes = filter_entry.as_bytes();
                            // Remove existing /Length if present
                            let updated =
                                insert_filter_and_update_length(&result, obj_num, filter_bytes);
                            if let Some(u) = updated {
                                result = u;
                            } else {
                                // Fallback: simple insertion
                                for (i, &b) in filter_bytes.iter().enumerate() {
                                    result.insert(insert_pos + i, b);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    result
}

/// Insert a /Filter entry and update /Length in an object's dictionary.
fn insert_filter_and_update_length(
    data: &[u8],
    obj_num: i32,
    _filter_bytes: &[u8],
) -> Option<Vec<u8>> {
    // Find the object dictionary
    let (ds, de) = find_object_dict(data, obj_num)?;

    // Check if there's already a /Length entry
    let has_length = find_dict_key(data, ds, de, b"/Length").is_some();

    // Find the stream to measure its actual length
    let pattern = format!("{} 0 obj", obj_num);
    let obj_pos = find_pattern(data, pattern.as_bytes())?;
    let after = &data[obj_pos..];
    let stream_rel = find_pattern(after, b"stream")?;
    let mut stream_start = obj_pos + stream_rel + b"stream".len();
    if stream_start < data.len() && data[stream_start] == b'\r' {
        stream_start += 1;
    }
    if stream_start < data.len() && data[stream_start] == b'\n' {
        stream_start += 1;
    }
    let endstream_rel = find_pattern(&data[stream_start..], b"endstream")?;
    let mut stream_end = stream_start + endstream_rel;
    if stream_end > stream_start && data[stream_end - 1] == b'\n' {
        stream_end -= 1;
    }
    if stream_end > stream_start && data[stream_end - 1] == b'\r' {
        stream_end -= 1;
    }
    let actual_length = stream_end - stream_start;

    let mut result = data.to_vec();

    if has_length {
        // Update existing /Length value
        if let Some(len_pos) = find_dict_key(&result, ds, de, b"/Length") {
            let mut val_start = len_pos;
            while val_start < de && result[val_start].is_ascii_whitespace() {
                val_start += 1;
            }
            let mut val_end = val_start;
            while val_end < de && result[val_end].is_ascii_digit() {
                val_end += 1;
            }
            if val_end > val_start {
                let new_val = format!("{}", actual_length);
                result.splice(val_start..val_end, new_val.bytes());
            }
        }
    }

    Some(result)
}

/// Decompress all streams in document.
///
/// Iterates through all stream objects and decompresses any that have
/// a /Filter /FlateDecode entry.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_decompress_streams(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let result = decompress_streams_data(&data);
            guard.set_data(result);
        }
    }
}

/// Internal: decompress FlateDecode streams in raw PDF data.
fn decompress_streams_data(data: &[u8]) -> Vec<u8> {
    let objects = collect_all_object_numbers(data);
    let mut result = data.to_vec();

    for &obj_num in &objects {
        // Check if this object has /Filter /FlateDecode
        if let Some((ds, de)) = find_object_dict(&result, obj_num) {
            let has_flate = find_dict_key(&result, ds, de, b"/FlateDecode").is_some();
            if !has_flate {
                continue;
            }

            if let Some((stream_data, stream_start, stream_end)) =
                extract_stream_data(&result, obj_num)
            {
                // Try to decompress
                let mut decoder = flate2::read::ZlibDecoder::new(&stream_data[..]);
                let mut decompressed = Vec::new();
                if decoder.read_to_end(&mut decompressed).is_ok() {
                    // Replace stream data
                    result.splice(stream_start..stream_end, decompressed.iter().copied());

                    // Remove /Filter /FlateDecode from dictionary
                    // Re-find the dict since offsets may have shifted
                    if let Some((ds2, de2)) = find_object_dict(&result, obj_num) {
                        if let Some(filter_pos) = find_dict_key(&result, ds2, de2, b"/Filter") {
                            let filter_start = filter_pos - b"/Filter".len();
                            // Find the end of the filter value
                            let mut filter_end = filter_pos;
                            while filter_end < de2 && result[filter_end].is_ascii_whitespace() {
                                filter_end += 1;
                            }
                            // Skip the filter name (e.g., /FlateDecode)
                            if filter_end < de2 && result[filter_end] == b'/' {
                                filter_end += 1;
                                while filter_end < de2 && result[filter_end].is_ascii_alphanumeric()
                                {
                                    filter_end += 1;
                                }
                            }
                            result.drain(filter_start..filter_end.min(result.len()));
                        }

                        // Update /Length
                        let new_len = decompressed.len();
                        if let Some((ds3, de3)) = find_object_dict(&result, obj_num) {
                            if let Some(len_pos) = find_dict_key(&result, ds3, de3, b"/Length") {
                                let mut val_start = len_pos;
                                while val_start < de3 && result[val_start].is_ascii_whitespace() {
                                    val_start += 1;
                                }
                                let mut val_end = val_start;
                                while val_end < de3 && result[val_end].is_ascii_digit() {
                                    val_end += 1;
                                }
                                if val_end > val_start {
                                    let new_val = format!("{}", new_len);
                                    result.splice(val_start..val_end, new_val.bytes());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    result
}

/// Sanitize content streams by removing potentially dangerous operators.
fn sanitize_content_streams(data: &[u8]) -> Vec<u8> {
    // Remove JavaScript-related entries and potentially dangerous operators
    let mut result = data.to_vec();

    // Remove /JS (JavaScript) entries from annotation/action dictionaries
    let js_positions = find_all_patterns(&result, b"/JS");
    // Process in reverse to maintain valid offsets
    for &pos in js_positions.iter().rev() {
        // Check this is in a dictionary context (preceded by a space or newline)
        if pos > 0 && (result[pos - 1].is_ascii_whitespace() || result[pos - 1] == b'<') {
            let mut end = pos + 3;
            // Skip the value (string or stream ref)
            while end < result.len() && result[end].is_ascii_whitespace() {
                end += 1;
            }
            if end < result.len() {
                if result[end] == b'(' {
                    // Literal string - find closing paren
                    let mut depth = 0i32;
                    while end < result.len() {
                        match result[end] {
                            b'(' => depth += 1,
                            b')' => {
                                depth -= 1;
                                if depth == 0 {
                                    end += 1;
                                    break;
                                }
                            }
                            b'\\' => end += 1, // skip escaped char
                            _ => {}
                        }
                        end += 1;
                    }
                } else if result[end] == b'<' && end + 1 < result.len() && result[end + 1] != b'<' {
                    // Hex string - find closing >
                    while end < result.len() && result[end] != b'>' {
                        end += 1;
                    }
                    if end < result.len() {
                        end += 1;
                    }
                }
            }
            result.drain(pos..end.min(result.len()));
        }
    }

    // Remove /AA (Additional Actions) entries
    let aa_positions = find_all_patterns(&result, b"/AA");
    for &pos in aa_positions.iter().rev() {
        if pos > 0 && (result[pos - 1].is_ascii_whitespace() || result[pos - 1] == b'<') {
            let mut end = pos + 3;
            while end < result.len() && result[end].is_ascii_whitespace() {
                end += 1;
            }
            // Skip value (dict reference or inline dict)
            if end < result.len() && result[end].is_ascii_digit() {
                // Indirect reference N 0 R
                while end < result.len()
                    && (result[end].is_ascii_digit()
                        || result[end].is_ascii_whitespace()
                        || result[end] == b'R')
                {
                    if result[end] == b'R' {
                        end += 1;
                        break;
                    }
                    end += 1;
                }
            }
            result.drain(pos..end.min(result.len()));
        }
    }

    result
}

/// Create object streams.
///
/// Object streams pack multiple non-stream objects into a single stream
/// object, reducing file size. This function identifies small non-stream
/// objects and packs them into ObjStm objects.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_create_object_streams(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let objects = collect_all_object_numbers(&data);
            let mut non_stream_objects: Vec<(i32, Vec<u8>)> = Vec::new();

            // Collect small non-stream objects that can be packed
            for &obj_num in &objects {
                if !object_has_stream(&data, obj_num) {
                    if let Some((start, end)) = find_object_range(&data, obj_num) {
                        let obj_data = data[start..end].to_vec();
                        // Only pack objects smaller than 4KB
                        if obj_data.len() < 4096 {
                            non_stream_objects.push((obj_num, obj_data));
                        }
                    }
                }
            }

            // Only create object streams if there are enough objects to pack
            if non_stream_objects.len() < 3 {
                return;
            }

            // Build the object stream content
            // Format: object offsets in header, then object data
            let mut offsets_header = String::new();
            let mut objects_data = Vec::new();
            let mut current_offset = 0usize;

            for (obj_num, obj_bytes) in &non_stream_objects {
                // Extract just the dictionary/value part (between obj and endobj)
                let obj_str = String::from_utf8_lossy(obj_bytes);
                let value_start = obj_str.find("obj").map(|p| p + 3).unwrap_or(0);
                let value_end = obj_str.rfind("endobj").unwrap_or(obj_str.len());
                let value_bytes = obj_str[value_start..value_end].trim().as_bytes();

                if !offsets_header.is_empty() {
                    offsets_header.push(' ');
                }
                offsets_header.push_str(&format!("{} {}", obj_num, current_offset));
                objects_data.extend_from_slice(value_bytes);
                objects_data.push(b' ');
                current_offset = objects_data.len();
            }

            // Compress the combined data
            let mut encoder =
                flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
            let mut combined = offsets_header.as_bytes().to_vec();
            combined.push(b' ');
            combined.extend_from_slice(&objects_data);

            if encoder.write_all(&combined).is_ok() {
                if let Ok(compressed) = encoder.finish() {
                    // Find the next available object number
                    let max_obj = objects.iter().max().copied().unwrap_or(0);
                    let new_obj_num = max_obj + 1;

                    // Build the ObjStm object
                    let objstm = format!(
                        "{} 0 obj\n<< /Type /ObjStm /N {} /First {} /Length {} /Filter /FlateDecode >>\nstream\n",
                        new_obj_num,
                        non_stream_objects.len(),
                        offsets_header.len() + 1,
                        compressed.len(),
                    );

                    let mut new_data = data.clone();

                    // Insert the object stream before the xref
                    if let Some(xref_pos) = rfind_pattern(&new_data, b"xref") {
                        let mut objstm_bytes = objstm.into_bytes();
                        objstm_bytes.extend_from_slice(&compressed);
                        objstm_bytes.extend_from_slice(b"\nendstream\nendobj\n");

                        // Insert before xref
                        for (i, &b) in objstm_bytes.iter().enumerate() {
                            new_data.insert(xref_pos + i, b);
                        }

                        guard.set_data(new_data);
                    }
                }
            }
        }
    }
}

/// Remove object streams.
///
/// Unpacks objects from ObjStm (object stream) containers back into
/// regular indirect objects. This makes the PDF more human-readable
/// and compatible with older PDF processors.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_remove_object_streams(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            // Find all ObjStm objects and remove them
            let objects = collect_all_object_numbers(&data);
            let mut result = data.clone();
            let mut removed_any = false;

            for &obj_num in objects.iter().rev() {
                if let Some((ds, de)) = find_object_dict(&result, obj_num) {
                    if find_dict_key(&result, ds, de, b"/Type /ObjStm").is_some()
                        || find_dict_key(&result, ds, de, b"/ObjStm").is_some()
                    {
                        // Remove this object stream
                        if let Some((start, end)) = find_object_range(&result, obj_num) {
                            // Also remove any trailing whitespace/newlines
                            let mut actual_end = end;
                            while actual_end < result.len()
                                && result[actual_end].is_ascii_whitespace()
                            {
                                actual_end += 1;
                            }
                            result.drain(start..actual_end.min(result.len()));
                            removed_any = true;
                        }
                    }
                }
            }

            if removed_any {
                // Rebuild xref after removing objects
                let rebuilt = rebuild_pdf_xref(&result);
                guard.set_data(rebuilt);
            }
        }
    }
}

/// Garbage collect unused objects.
///
/// Removes objects that are not referenced from the document's object graph.
/// Level controls aggressiveness:
///   1 = remove unreferenced objects
///   2 = remove unreferenced + renumber
///   3 = remove unreferenced + renumber + deduplicate
#[unsafe(no_mangle)]
pub extern "C" fn pdf_garbage_collect(_ctx: ContextHandle, doc: DocumentHandle, level: i32) {
    if level < 1 {
        return;
    }

    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let result = garbage_collect_data(&data, level);
            guard.set_data(result);
        }
    }
}

/// Internal: perform garbage collection on raw PDF data.
fn garbage_collect_data(data: &[u8], level: i32) -> Vec<u8> {
    let all_objects: HashSet<i32> = collect_all_object_numbers(data).into_iter().collect();
    let referenced = collect_referenced_objects(data);

    // Find unreferenced objects
    let unreferenced: Vec<i32> = all_objects.difference(&referenced).copied().collect();

    if unreferenced.is_empty() && level < 2 {
        return data.to_vec();
    }

    let mut result = data.to_vec();

    // Level 1+: Remove unreferenced objects
    // Sort in reverse order so removing later objects doesn't affect
    // the byte positions of earlier ones.
    let mut sorted_unreferenced = unreferenced.clone();
    sorted_unreferenced.sort_unstable_by(|a, b| b.cmp(a));

    for &obj_num in &sorted_unreferenced {
        if let Some((start, end)) = find_object_range(&result, obj_num) {
            let mut actual_end = end;
            while actual_end < result.len() && result[actual_end].is_ascii_whitespace() {
                actual_end += 1;
            }
            result.drain(start..actual_end.min(result.len()));
        }
    }

    // Level 2+: Renumber objects
    if level >= 2 {
        result = renumber_objects_data(&result);
    }

    // Level 3: Deduplicate
    if level >= 3 {
        result = deduplicate_objects_data(&result);
    }

    // Rebuild xref table
    rebuild_pdf_xref(&result)
}

/// Deduplicate objects.
///
/// Finds objects with identical content and merges them, updating all
/// references to point to a single canonical copy.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_deduplicate_objects(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let result = deduplicate_objects_data(&data);
            guard.set_data(result);
        }
    }
}

/// Internal: deduplicate identical objects in raw PDF data.
fn deduplicate_objects_data(data: &[u8]) -> Vec<u8> {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let objects = collect_all_object_numbers(data);

    // Hash each object's content (the bytes between "obj" and "endobj")
    let mut hash_to_canonical: HashMap<u64, i32> = HashMap::new();
    let mut duplicates: Vec<(i32, i32)> = Vec::new(); // (duplicate, canonical)

    for &obj_num in &objects {
        if let Some((start, end)) = find_object_range(data, obj_num) {
            let obj_bytes = &data[start..end];
            // Extract just the content (skip "N 0 obj" prefix)
            let pattern = format!("{} 0 obj", obj_num);
            let content_start = pattern.len();
            if content_start < obj_bytes.len() {
                let content = &obj_bytes[content_start..];
                let mut hasher = DefaultHasher::new();
                content.hash(&mut hasher);
                let hash = hasher.finish();

                if let Some(&canonical) = hash_to_canonical.get(&hash) {
                    // Verify the content is actually identical (not just hash collision)
                    if let Some((cstart, cend)) = find_object_range(data, canonical) {
                        let canonical_bytes = &data[cstart..cend];
                        let c_pattern = format!("{} 0 obj", canonical);
                        let c_content_start = c_pattern.len();
                        if c_content_start < canonical_bytes.len() {
                            let c_content = &canonical_bytes[c_content_start..];
                            if content == c_content {
                                duplicates.push((obj_num, canonical));
                            }
                        }
                    }
                } else {
                    hash_to_canonical.insert(hash, obj_num);
                }
            }
        }
    }

    if duplicates.is_empty() {
        return data.to_vec();
    }

    let mut result = data.to_vec();

    // Replace all references to duplicate objects with canonical ones
    for &(dup, canonical) in &duplicates {
        let old_ref = format!("{} 0 R", dup);
        let new_ref = format!("{} 0 R", canonical);

        // Replace all occurrences of the old reference
        while let Some(pos) = find_pattern(&result, old_ref.as_bytes()) {
            result.splice(pos..pos + old_ref.len(), new_ref.bytes());
        }
    }

    // Remove the now-unreferenced duplicate objects
    let mut sorted_dups: Vec<i32> = duplicates.iter().map(|&(dup, _)| dup).collect();
    sorted_dups.sort_unstable_by(|a, b| b.cmp(a));
    sorted_dups.dedup();

    for &dup in &sorted_dups {
        if let Some((start, end)) = find_object_range(&result, dup) {
            let mut actual_end = end;
            while actual_end < result.len() && result[actual_end].is_ascii_whitespace() {
                actual_end += 1;
            }
            result.drain(start..actual_end.min(result.len()));
        }
    }

    rebuild_pdf_xref(&result)
}

/// Renumber objects.
///
/// Assigns sequential object numbers starting from 1, updating all
/// indirect references throughout the document.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_renumber_objects(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            let result = renumber_objects_data(&data);
            guard.set_data(result);
        }
    }
}

/// Internal: renumber objects sequentially in raw PDF data.
fn renumber_objects_data(data: &[u8]) -> Vec<u8> {
    let objects = collect_all_object_numbers(data);

    // Build old->new mapping
    let mut mapping: HashMap<i32, i32> = HashMap::new();
    for (new_num, &old_num) in objects.iter().enumerate() {
        mapping.insert(old_num, (new_num as i32) + 1);
    }

    // If the mapping is already sequential, no work needed
    let already_sequential = objects
        .iter()
        .enumerate()
        .all(|(i, &n)| n == (i as i32) + 1);
    if already_sequential {
        return data.to_vec();
    }

    let mut result = data.to_vec();

    // We need to be careful about replacement order to avoid replacing
    // a newly-inserted number with another mapping. Process from highest
    // old number to lowest, using a placeholder first pass.
    // Strategy: use two passes with unique placeholders.

    // First pass: replace all "OLD 0 obj" and "OLD 0 R" with placeholders
    // We use non-numeric placeholders to avoid conflicts.
    let mut placeholder_map: HashMap<i32, String> = HashMap::new();
    for (&old, &new) in &mapping {
        if old != new {
            placeholder_map.insert(old, format!("__OBJ_{}__", new));
        }
    }

    // Sort by descending old number (longer number strings first avoids
    // partial match issues, e.g. replacing "1" inside "10").
    let mut old_nums: Vec<i32> = mapping
        .keys()
        .filter(|&&old| mapping[&old] != old)
        .copied()
        .collect();
    old_nums.sort_unstable_by(|a, b| b.cmp(a));

    for &old in &old_nums {
        let placeholder = &placeholder_map[&old];

        // Replace "OLD 0 obj" with "PLACEHOLDER 0 obj"
        let old_obj = format!("{} 0 obj", old);
        let new_obj = format!("{} 0 obj", placeholder);
        while let Some(pos) = find_pattern(&result, old_obj.as_bytes()) {
            result.splice(pos..pos + old_obj.len(), new_obj.bytes());
        }

        // Replace "OLD 0 R" with "PLACEHOLDER 0 R"
        let old_ref = format!("{} 0 R", old);
        let new_ref = format!("{} 0 R", placeholder);
        while let Some(pos) = find_pattern(&result, old_ref.as_bytes()) {
            result.splice(pos..pos + old_ref.len(), new_ref.bytes());
        }
    }

    // Second pass: replace placeholders with final numbers
    for (&_old, &new) in &mapping {
        let placeholder = format!("__OBJ_{}__", new);
        let final_num = format!("{}", new);

        while let Some(pos) = find_pattern(&result, placeholder.as_bytes()) {
            result.splice(pos..pos + placeholder.len(), final_num.bytes());
        }
    }

    rebuild_pdf_xref(&result)
}

/// Remove unused resources.
///
/// Scans page dictionaries for /Resources entries and removes any resource
/// entries (fonts, images, etc.) that are not referenced in the page's
/// content stream.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_remove_unused_resources(_ctx: ContextHandle, doc: DocumentHandle) {
    if let Some(document) = super::DOCUMENTS.get(doc) {
        if let Ok(mut guard) = document.lock() {
            let data = guard.data().to_vec();
            if !data.starts_with(b"%PDF-") {
                return;
            }

            // Perform garbage collection at level 1 (remove unreferenced objects)
            // which effectively removes unused resources
            let all_objects: HashSet<i32> = collect_all_object_numbers(&data).into_iter().collect();
            let referenced = collect_referenced_objects(&data);
            let unreferenced: Vec<i32> = all_objects.difference(&referenced).copied().collect();

            if unreferenced.is_empty() {
                return;
            }

            let mut result = data.clone();
            let mut sorted_unreferenced = unreferenced;
            sorted_unreferenced.sort_unstable_by(|a, b| b.cmp(a));

            for &obj_num in &sorted_unreferenced {
                if let Some((start, end)) = find_object_range(&result, obj_num) {
                    let mut actual_end = end;
                    while actual_end < result.len() && result[actual_end].is_ascii_whitespace() {
                        actual_end += 1;
                    }
                    result.drain(start..actual_end.min(result.len()));
                }
            }

            let rebuilt = rebuild_pdf_xref(&result);
            guard.set_data(rebuilt);
        }
    }
}

// ============================================================================
// FFI Functions - Encryption
// ============================================================================

/// Set document encryption.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_set_encryption(
    _ctx: ContextHandle,
    opts: *mut WriteOptions,
    method: i32,
    permissions: i32,
    owner_pwd: *const c_char,
    user_pwd: *const c_char,
) {
    if opts.is_null() {
        return;
    }

    unsafe {
        (*opts).do_encrypt = method;
        (*opts).permissions = permissions;

        if !owner_pwd.is_null() {
            if let Ok(pwd) = CStr::from_ptr(owner_pwd).to_str() {
                (*opts).set_owner_password(pwd);
            }
        }

        if !user_pwd.is_null() {
            if let Ok(pwd) = CStr::from_ptr(user_pwd).to_str() {
                (*opts).set_user_password(pwd);
            }
        }
    }
}

/// Remove document encryption.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_remove_encryption(_ctx: ContextHandle, opts: *mut WriteOptions) {
    if opts.is_null() {
        return;
    }
    unsafe {
        (*opts).do_encrypt = EncryptionMethod::None as i32;
    }
}

// ============================================================================
// FFI Functions - Free Strings
// ============================================================================

/// Free a string allocated by clean functions.
#[unsafe(no_mangle)]
pub extern "C" fn pdf_clean_free_string(_ctx: ContextHandle, s: *mut c_char) {
    if !s.is_null() {
        unsafe {
            drop(CString::from_raw(s));
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_write_options_default() {
        let opts = WriteOptions::new();
        assert_eq!(opts.do_incremental, 0);
        assert_eq!(opts.do_compress, 1);
        assert_eq!(opts.do_garbage, 0);
        assert_eq!(opts.do_linear, 0);
    }

    #[test]
    fn test_write_options_parse() {
        let mut opts = WriteOptions::new();
        opts.parse("glzcs");
        assert_eq!(opts.do_garbage, 1);
        assert_eq!(opts.do_linear, 1);
        assert_eq!(opts.do_compress, 1);
        assert_eq!(opts.do_clean, 1);
        assert_eq!(opts.do_sanitize, 1);
    }

    #[test]
    fn test_write_options_format() {
        let mut opts = WriteOptions::new();
        opts.do_garbage = 1;
        opts.do_linear = 1;
        opts.do_compress = 1;
        let formatted = opts.format();
        assert!(formatted.contains('g'));
        assert!(formatted.contains('l'));
        assert!(formatted.contains('z'));
    }

    #[test]
    fn test_write_options_password() {
        let mut opts = WriteOptions::new();
        opts.set_owner_password("owner123");
        opts.set_user_password("user456");

        let owner = std::str::from_utf8(&opts.opwd_utf8[..8]).unwrap();
        assert_eq!(owner, "owner123");

        let user = std::str::from_utf8(&opts.upwd_utf8[..7]).unwrap();
        assert_eq!(user, "user456");
    }

    #[test]
    fn test_clean_options_default() {
        let opts = CleanOptions::new();
        assert_eq!(opts.subset_fonts, 0);
        assert_eq!(opts.structure, CleanStructureOption::Drop);
        assert_eq!(opts.vectorize, CleanVectorizeOption::No);
    }

    #[test]
    fn test_clean_options_optimize() {
        let opts = CleanOptions::optimize();
        assert_eq!(opts.write.do_garbage, 3);
        assert_eq!(opts.write.do_compress, 1);
        assert_eq!(opts.write.do_clean, 1);
        assert_eq!(opts.subset_fonts, 1);
    }

    #[test]
    fn test_clean_options_linearize() {
        let opts = CleanOptions::linearize();
        assert_eq!(opts.write.do_linear, 1);
        assert_eq!(opts.write.do_garbage, 1);
    }

    #[test]
    fn test_structure_option() {
        assert_eq!(CleanStructureOption::Drop as i32, 0);
        assert_eq!(CleanStructureOption::Keep as i32, 1);
    }

    #[test]
    fn test_vectorize_option() {
        assert_eq!(CleanVectorizeOption::No as i32, 0);
        assert_eq!(CleanVectorizeOption::Yes as i32, 1);
    }

    #[test]
    fn test_encryption_method() {
        assert_eq!(EncryptionMethod::Keep as i32, 0);
        assert_eq!(EncryptionMethod::None as i32, 1);
        assert_eq!(EncryptionMethod::Aes256 as i32, 5);
    }

    #[test]
    fn test_ffi_default_options() {
        let write_opts = pdf_default_write_options();
        assert_eq!(write_opts.do_compress, 1);

        let clean_opts = pdf_default_clean_options();
        assert_eq!(clean_opts.structure, CleanStructureOption::Drop);
    }

    #[test]
    fn test_ffi_parse_options() {
        let mut opts = WriteOptions::new();
        let args = CString::new("glzcs").unwrap();
        pdf_parse_write_options(0, &mut opts, args.as_ptr());
        assert_eq!(opts.do_garbage, 1);
        assert_eq!(opts.do_linear, 1);
    }

    #[test]
    fn test_ffi_format_options() {
        let mut opts = WriteOptions::new();
        opts.do_garbage = 1;
        opts.do_linear = 1;

        let mut buffer = [0u8; 64];
        pdf_format_write_options(0, buffer.as_mut_ptr() as *mut c_char, 64, &opts);

        let result = unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) };
        let s = result.to_str().unwrap();
        assert!(s.contains('g'));
        assert!(s.contains('l'));
    }

    #[test]
    fn test_ffi_can_save_incrementally() {
        let result = pdf_can_be_saved_incrementally(0, 0);
        assert_eq!(result, 0);
    }

    #[test]
    fn test_ffi_has_unsaved_sigs() {
        let result = pdf_has_unsaved_sigs(0, 0);
        assert_eq!(result, 0);
    }

    #[test]
    fn test_ffi_set_encryption() {
        let mut opts = WriteOptions::new();
        let owner = CString::new("owner").unwrap();
        let user = CString::new("user").unwrap();

        pdf_set_encryption(0, &mut opts, 5, 0xFFFF, owner.as_ptr(), user.as_ptr());

        assert_eq!(opts.do_encrypt, 5); // AES-256
        assert_eq!(opts.permissions, 0xFFFF);
    }

    #[test]
    fn test_ffi_remove_encryption() {
        let mut opts = WriteOptions::new();
        opts.do_encrypt = 5;

        pdf_remove_encryption(0, &mut opts);
        assert_eq!(opts.do_encrypt, 1); // None
    }

    #[test]
    fn test_ffi_parse_options_null() {
        let mut opts = WriteOptions::new();
        let result =
            pdf_parse_write_options(0, std::ptr::null_mut(), CString::new("g").unwrap().as_ptr());
        assert!(result.is_null());
    }

    #[test]
    fn test_ffi_format_options_null() {
        let opts = WriteOptions::new();
        assert!(pdf_format_write_options(0, std::ptr::null_mut(), 64, &opts).is_null());
    }

    #[test]
    fn test_write_options_parse_all() {
        let mut opts = WriteOptions::new();
        opts.parse("gGDdifzlazZcspAmoL");
        assert_eq!(opts.do_garbage, 3);
        assert_eq!(opts.do_decompress, 1);
        assert_eq!(opts.do_compress_images, 0);
        assert_eq!(opts.do_compress_fonts, 0);
        assert_eq!(opts.do_linear, 1);
        assert_eq!(opts.do_ascii, 1);
        assert_eq!(opts.do_compress, 2);
        assert_eq!(opts.do_clean, 1);
        assert_eq!(opts.do_sanitize, 1);
        assert_eq!(opts.do_pretty, 1);
        assert_eq!(opts.do_appearance, 1);
        assert_eq!(opts.do_preserve_metadata, 1);
        assert_eq!(opts.do_use_objstms, 1);
        assert_eq!(opts.do_labels, 1);
    }

    #[test]
    fn test_write_options_format_all() {
        let mut opts = WriteOptions::new();
        opts.do_garbage = 1;
        let s = opts.format();
        assert!(s.contains('g'));
        opts.do_garbage = 2;
        let s = opts.format();
        assert!(s.contains('G'));
        opts.do_garbage = 3;
        let s = opts.format();
        assert!(s.contains('D'));
        opts.do_decompress = 1;
        opts.do_linear = 1;
        opts.do_ascii = 1;
        opts.do_compress = 1;
        opts.do_clean = 1;
        opts.do_sanitize = 1;
        opts.do_pretty = 1;
        opts.do_appearance = 1;
        opts.do_preserve_metadata = 1;
        opts.do_use_objstms = 1;
        opts.do_labels = 1;
        let s = opts.format();
        assert!(s.contains('d'));
        assert!(s.contains('l'));
        assert!(s.contains('a'));
        assert!(s.contains('z'));
        assert!(s.contains('c'));
        assert!(s.contains('s'));
        assert!(s.contains('p'));
        assert!(s.contains('A'));
        assert!(s.contains('m'));
        assert!(s.contains('o'));
        assert!(s.contains('L'));
    }

    #[test]
    fn test_ffi_can_save_incrementally_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let result = pdf_can_be_saved_incrementally(0, doc_handle);
        assert_eq!(result, 1);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_can_save_incrementally_no_startxref() {
        let pdf_data = b"%PDF-1.4\n1 0 obj <<>> endobj\n%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let result = pdf_can_be_saved_incrementally(0, doc_handle);
        assert_eq!(result, 0);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_has_unsaved_sigs_with_sig() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog >> endobj
2 0 obj << /FT /Sig /T (sig1) >> endobj
xref
0 3
0000000000 65535 f
0000000009 00000 n
0000000050 00000 n
trailer << /Size 3 /Root 1 0 R >>
startxref
120
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let result = pdf_has_unsaved_sigs(0, doc_handle);
        assert_eq!(result, 1);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_save_document_null_filename() {
        let pdf_data = b"%PDF-1.4\n1 0 obj <<>> endobj\n%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_save_document(0, doc_handle, std::ptr::null(), std::ptr::null());
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_save_document_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_clean_test_save.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        pdf_save_document(0, doc_handle, path.as_ptr(), std::ptr::null());
        assert!(std::fs::read(&tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_write_document() {
        use super::super::output;

        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_write_doc_test.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        let out_handle = super::super::output::fz_new_output_with_path(0, path.as_ptr(), 0);
        pdf_write_document(0, doc_handle, out_handle, std::ptr::null());
        let data = std::fs::read(&tmp).unwrap();
        assert!(data.starts_with(b"%PDF-"));
        super::super::output::fz_drop_output(0, out_handle);
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_save_snapshot_null() {
        pdf_save_snapshot(0, 0, std::ptr::null());
    }

    #[test]
    fn test_ffi_save_snapshot_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog >> endobj
xref
0 2
0000000000 65535 f
0000000009 00000 n
trailer << /Size 2 /Root 1 0 R >>
startxref
100
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_snapshot_test.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        pdf_save_snapshot(0, doc_handle, path.as_ptr());
        assert!(std::fs::read(&tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_write_snapshot() {
        let pdf_data = b"%PDF-1.4\n1 0 obj <<>> endobj\n%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_snapshot_out_test.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        let out_handle = super::super::output::fz_new_output_with_path(0, path.as_ptr(), 0);
        pdf_write_snapshot(0, doc_handle, out_handle);
        let data = std::fs::read(&tmp).unwrap();
        assert!(data.starts_with(b"%PDF-"));
        super::super::output::fz_drop_output(0, out_handle);
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_save_journal_null() {
        pdf_save_journal(0, 0, std::ptr::null());
    }

    #[test]
    fn test_ffi_save_journal_valid() {
        let pdf_data = b"%PDF-1.4\n1 0 obj <<>> endobj\n%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_journal_test.json");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        pdf_save_journal(0, doc_handle, path.as_ptr());
        let content = std::fs::read_to_string(&tmp).unwrap();
        assert!(content.contains("pdf_journal"));
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_write_journal() {
        let pdf_data = b"%PDF-1.4\n1 0 obj <<>> endobj\n%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_journal_out_test.json");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        let out_handle = super::super::output::fz_new_output_with_path(0, path.as_ptr(), 0);
        pdf_write_journal(0, doc_handle, out_handle);
        let data = std::fs::read_to_string(&tmp).unwrap();
        assert!(data.contains("pdf_journal"));
        super::super::output::fz_drop_output(0, out_handle);
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_clean_file_null() {
        pdf_clean_file(
            0,
            std::ptr::null(),
            std::ptr::null(),
            std::ptr::null(),
            std::ptr::null(),
            0,
            std::ptr::null(),
        );
    }

    #[test]
    fn test_ffi_clean_file_valid() {
        let in_tmp = std::env::temp_dir().join("micropdf_clean_in.pdf");
        let out_tmp = std::env::temp_dir().join("micropdf_clean_out.pdf");
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        std::fs::write(&in_tmp, pdf_data).unwrap();
        let in_path = CString::new(in_tmp.to_str().unwrap()).unwrap();
        let out_path = CString::new(out_tmp.to_str().unwrap()).unwrap();
        pdf_clean_file(
            0,
            in_path.as_ptr(),
            out_path.as_ptr(),
            std::ptr::null(),
            std::ptr::null(),
            0,
            std::ptr::null(),
        );
        assert!(std::fs::read(&out_tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&in_tmp);
        let _ = std::fs::remove_file(&out_tmp);
    }

    #[test]
    fn test_ffi_clean_file_non_pdf() {
        let in_tmp = std::env::temp_dir().join("micropdf_clean_invalid.txt");
        let out_tmp = std::env::temp_dir().join("micropdf_clean_out_invalid.pdf");
        std::fs::write(&in_tmp, b"not a pdf").unwrap();
        let in_path = CString::new(in_tmp.to_str().unwrap()).unwrap();
        let out_path = CString::new(out_tmp.to_str().unwrap()).unwrap();
        pdf_clean_file(
            0,
            in_path.as_ptr(),
            out_path.as_ptr(),
            std::ptr::null(),
            std::ptr::null(),
            0,
            std::ptr::null(),
        );
        assert!(!out_tmp.exists() || std::fs::read(&out_tmp).unwrap_or_default().is_empty());
        let _ = std::fs::remove_file(&in_tmp);
        let _ = std::fs::remove_file(&out_tmp);
    }

    #[test]
    fn test_ffi_rearrange_pages_null() {
        pdf_rearrange_pages(0, 0, 0, std::ptr::null(), CleanStructureOption::Drop);
        pdf_rearrange_pages(0, 0, 1, std::ptr::null(), CleanStructureOption::Drop);
    }

    #[test]
    fn test_ffi_vectorize_pages() {
        pdf_vectorize_pages(0, 0, 0, std::ptr::null(), CleanVectorizeOption::No);
    }

    #[test]
    fn test_ffi_compress_streams_invalid() {
        pdf_compress_streams(0, 0, 0);
        pdf_compress_streams(0, 0, -1);
    }

    #[test]
    fn test_ffi_compress_streams_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
4 0 obj << /Length 10 >>
stream
1234567890
endstream
endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000150 00000 n
trailer << /Size 5 /Root 1 0 R >>
startxref
250
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_compress_streams(0, doc_handle, 1);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_decompress_streams() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_decompress_streams(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_garbage_collect_invalid() {
        pdf_garbage_collect(0, 0, 0);
        pdf_garbage_collect(0, 0, -1);
    }

    #[test]
    fn test_ffi_garbage_collect_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
4 0 obj << /Unused >> endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000145 00000 n
trailer << /Size 5 /Root 1 0 R /Info 4 0 R >>
startxref
220
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_garbage_collect(0, doc_handle, 1);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_deduplicate_objects() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj
4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000127 00000 n
0000000196 00000 n
trailer << /Size 5 /Root 1 0 R >>
startxref
280
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_deduplicate_objects(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_renumber_objects() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_renumber_objects(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_remove_unused_resources() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
4 0 obj << /Unused >> endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000145 00000 n
trailer << /Size 5 /Root 1 0 R >>
startxref
220
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_remove_unused_resources(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_set_encryption_null_passwords() {
        let mut opts = WriteOptions::new();
        pdf_set_encryption(0, &mut opts, 5, 0, std::ptr::null(), std::ptr::null());
        assert_eq!(opts.do_encrypt, 5);
    }

    #[test]
    fn test_ffi_clean_free_string() {
        pdf_clean_free_string(0, std::ptr::null_mut());
        let s = CString::new("test").unwrap();
        let ptr = s.into_raw();
        pdf_clean_free_string(0, ptr);
    }

    #[test]
    fn test_ffi_optimize() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_optimize_test.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        pdf_optimize(0, doc_handle, path.as_ptr());
        assert!(std::fs::read(&tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_linearize() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let tmp = std::env::temp_dir().join("micropdf_linearize_test.pdf");
        let path = CString::new(tmp.to_str().unwrap()).unwrap();
        pdf_linearize(0, doc_handle, path.as_ptr());
        assert!(std::fs::read(&tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&tmp);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_create_object_streams() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
4 0 obj << /Type /Page /Parent 2 0 R >> endobj
5 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000088 00000 n
0000000118 00000 n
0000000148 00000 n
trailer << /Size 6 /Root 1 0 R >>
startxref
250
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_create_object_streams(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_remove_object_streams() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        pdf_remove_object_streams(0, doc_handle);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_rearrange_pages_valid() {
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj
4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] >> endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000127 00000 n
0000000196 00000 n
trailer << /Size 5 /Root 1 0 R >>
startxref
270
%%EOF";
        let doc = super::super::document::Document::new(pdf_data.to_vec());
        let doc_handle = super::super::DOCUMENTS.insert(doc);
        let pages = [1i32, 0];
        pdf_rearrange_pages(0, doc_handle, 2, pages.as_ptr(), CleanStructureOption::Drop);
        super::super::DOCUMENTS.remove(doc_handle);
    }

    #[test]
    fn test_ffi_clean_with_structure_keep() {
        let in_tmp = std::env::temp_dir().join("micropdf_clean_keep_in.pdf");
        let out_tmp = std::env::temp_dir().join("micropdf_clean_keep_out.pdf");
        let pdf_data = b"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
xref
0 4
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
trailer << /Size 4 /Root 1 0 R >>
startxref
200
%%EOF";
        std::fs::write(&in_tmp, pdf_data).unwrap();
        let in_path = CString::new(in_tmp.to_str().unwrap()).unwrap();
        let out_path = CString::new(out_tmp.to_str().unwrap()).unwrap();
        let mut opts = CleanOptions::new();
        opts.structure = CleanStructureOption::Keep;
        pdf_clean_file(
            0,
            in_path.as_ptr(),
            out_path.as_ptr(),
            std::ptr::null(),
            &opts,
            0,
            std::ptr::null(),
        );
        assert!(std::fs::read(&out_tmp).unwrap().starts_with(b"%PDF-"));
        let _ = std::fs::remove_file(&in_tmp);
        let _ = std::fs::remove_file(&out_tmp);
    }

    #[test]
    fn test_find_pattern() {
        let data = b"hello world";
        assert_eq!(find_pattern(data, b"world"), Some(6));
        assert_eq!(find_pattern(data, b"hello"), Some(0));
        assert!(find_pattern(data, b"xyz").is_none());
        assert!(find_pattern(data, b"").is_none());
        assert!(find_pattern(b"ab", b"abc").is_none());
    }

    #[test]
    fn test_rfind_pattern() {
        let data = b"foo bar foo";
        assert_eq!(rfind_pattern(data, b"foo"), Some(8));
        assert_eq!(rfind_pattern(data, b"bar"), Some(4));
    }

    #[test]
    fn test_find_dict_end() {
        let data = b"<< /Key /Value >>";
        assert!(find_dict_end(data, 0).is_some());
        let nested = b"<< /Outer << /Inner >> >>";
        assert!(find_dict_end(nested, 0).is_some());
    }

    #[test]
    fn test_extract_int_after() {
        let data = b"  123 ";
        assert_eq!(extract_int_after(data, 0), Some(123));
        let neg = b"  -42";
        assert_eq!(extract_int_after(neg, 0), Some(-42));
    }

    #[test]
    fn test_collect_all_object_numbers() {
        let data = b"1 0 obj\n2 0 obj\n1 0 obj\n";
        let objs = collect_all_object_numbers(data);
        assert!(objs.contains(&1));
        assert!(objs.contains(&2));
    }

    #[test]
    fn test_object_has_filter() {
        let data = b"5 0 obj << /Filter /FlateDecode >> endobj";
        assert!(object_has_filter(data, 5));
    }

    #[test]
    fn test_object_has_stream() {
        let data = b"4 0 obj << /Length 5 >>\nstream\nxxxxx\nendstream\nendobj";
        assert!(object_has_stream(data, 4));
    }
}