flpdf 0.1.6

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
//! Layout writer — orchestrates the full linearized PDF output.
//!
//! This module assembles the six-part Annex F layout in correct order, tracks
//! byte offsets for back-patching, and returns the finished bytes together with
//! all offset information that the back-patcher needs.
//!
//! # Part ordering (Annex F)
//!
//! ```text
//! Annex F Part | Contents in this impl
//! -------------|-------------------------------------------------------------------
//! Part 1       | header + linearization param dict (`renumber.param_dict_ref()`)
//!              | with placeholders + Part 1 xref subsection (param-dict obj only)
//!              | + trailer
//! Part 2       | hint stream object (compressed, with /Filter /FlateDecode /S …)
//! Part 3       | first-page body — Plan.part2_objects with renumbered refs
//! Part 4       | shared/catalog/info — Plan.part3_objects with renumbered refs
//! Part 5       | remaining body — `Plan.part4_objects()` (derived view of
//!              | `part4_other_pages_private` + `_shared` + `_rest`) with
//!              | renumbered refs
//! Part 6       | cross-reference table for all objects + trailer
//! ```
//!
//! **Terminology note**: the `LinearizationPlan` field names (`part2_objects`,
//! `part3_objects`, `part4_objects`) do **not** correspond to the Annex F "Part"
//! numbers above.  Mapping:
//!
//! - `Plan.part2_objects` → Annex F Part 3 (first-page body)
//! - `Plan.part3_objects` → Annex F Part 4 (shared/catalog/info)
//! - `Plan.part4_objects()` → Annex F Part 5 (remaining body)
//!
//! The param-dict and hint-stream object numbers are **dynamic** — the
//! renumber map decides which slots they occupy. Use
//! [`RenumberMap::param_dict_ref`] and [`RenumberMap::hint_stream_slot`]
//! to query their actual positions; the writer reads both fields from
//! the renumber map rather than assuming `1` and `renumber.len() + 1`.
//! /Size in the trailer is `renumber.len() as u32 + 1` (the `total_count`
//! local), which already accounts for both reserved slots.
//!
//! # 2-pass algorithm
//!
//! Because the hint stream itself occupies bytes (and shifts every offset that
//! follows it), we use a convergence loop:
//!
//! 1. **Probe pass**: write the file with a placeholder hint stream of a given
//!    byte length.  Collect per-object offsets and byte lengths.
//! 2. **Patch hint tables**: use the probed lengths to fill in
//!    `page_length_minus_least`, `least_page_length`, `location_of_first_page`,
//!    shared object lengths, and `location`.
//! 3. **Re-encode** the hint stream with the patched tables.  If the compressed
//!    length is the same as the placeholder, convergence is reached.  Otherwise
//!    repeat from step 1 with the new length.
//! 4. **Final pass**: write the file using the converged hint stream.
//!
//! # Scope
//!
//! Back-patching the placeholder values is the responsibility of a later step.
//! This module returns `LinearizedOffsets` containing all information required
//! for that step.

use std::collections::BTreeMap;
use std::io::{Read, Seek};

use crate::linearization::hint_page::{bits_needed, PageOffsetHintTable};
use crate::linearization::hint_shared::SharedObjectHintTable;
use crate::linearization::hint_stream::encode_hint_stream;
use crate::linearization::part1::{Part1Bytes, Part1Placeholders};
use crate::linearization::plan::LinearizationPlan;
use crate::linearization::renumber::{ObjStmRelocation, RenumberMap};
use crate::writer::object_streams::{
    emit_objstm_body_from_resolved, planner_config_from_options, wrap_objstm_body,
};
use crate::writer::{effective_pdf_version, WriteOptions, QPDF_STATIC_ID};
use crate::{Dictionary, Object, ObjectRef, Pdf, Result, Stream};

// ---------------------------------------------------------------------------
// ObjStm layout (flpdf-9hc.5.8.2)
// ---------------------------------------------------------------------------

/// A single ObjStm container scheduled for the linearized output.
///
/// `members` carries the **renumbered** member refs in batch order (the
/// pair-table order inside the container).  `container_new_num` is the fresh
/// object number assigned to the container itself — always above every
/// `RenumberMap` slot so it never collides with a planned object, the param
/// dict, or the hint stream.
#[derive(Debug, Clone)]
struct ObjStmContainer {
    /// Fresh object number for the container indirect object.
    container_new_num: u32,
    /// `(original_ref, new_ref)` pairs in batch order.
    members: Vec<(ObjectRef, ObjectRef)>,
}

/// Resolved ObjStm layout for a linearized write.
///
/// Built once, before the convergence loop, from the Part-tagged
/// [`crate::linearization::plan::ObjStmBatchPlan`].  The contained-object set
/// and per-container membership are **stable across iterations** (only the
/// surrounding byte offsets shift), which keeps the convergence loop bounded.
#[derive(Debug, Clone, Default)]
struct ObjStmLayout {
    /// Containers emitted inside the first-page section (Annex F Part 3,
    /// before `/E`).
    part3: Vec<ObjStmContainer>,
    /// Containers emitted in the remaining body (Annex F Part 5, after `/E`).
    part4: Vec<ObjStmContainer>,
    /// `original_ref → (container_new_num, index_within_container)` for every
    /// object that lives inside an ObjStm.  Drives type-2 xref entries and
    /// the skip-from-plain-emission decision.
    member_to_container: BTreeMap<ObjectRef, (u32, u32)>,
}

impl ObjStmLayout {
    /// `true` when no ObjStm containers are scheduled — the writer then keeps
    /// its classic-xref-table path verbatim (no regression).
    fn is_empty(&self) -> bool {
        self.part3.is_empty() && self.part4.is_empty()
    }

    /// Resolve the Part-tagged, writer-filtered ObjStm batch plan.
    ///
    /// This is the single source of truth for *which* objects are ObjStm
    /// members and *in what order* — consumed both by
    /// [`RenumberMap::relocate_objstm_members`] (slot allocation) and by
    /// [`ObjStmLayout::build_from_batches`] (container construction), so the
    /// two never disagree about membership or pair-table order.
    fn resolve_batches<R: Read + Seek>(
        plan: &LinearizationPlan,
        pdf: &mut Pdf<R>,
        options: &WriteOptions,
    ) -> Result<crate::linearization::plan::ObjStmBatchPlan> {
        let config = planner_config_from_options(options);
        let batch_plan = plan.objstm_batches(pdf, &config)?;

        // Writer-level invariant (qpdf linearization rule, not encoded by the
        // 5.8.1 planner): per-page *private* objects must remain plain
        // indirects — qpdf rejects a linearized file whose page dictionaries
        // are compressed.  Drop any `part4_other_pages_private` member here.
        let other_pages_private: std::collections::BTreeSet<ObjectRef> =
            plan.part4_other_pages_private.iter().copied().collect();
        let filter_batches = |batches: Vec<Vec<ObjectRef>>| -> Vec<Vec<ObjectRef>> {
            batches
                .into_iter()
                .filter_map(|batch| {
                    let kept: Vec<ObjectRef> = batch
                        .into_iter()
                        .filter(|r| !other_pages_private.contains(r))
                        .collect();
                    if kept.is_empty() {
                        None
                    } else {
                        Some(kept)
                    }
                })
                .collect()
        };
        Ok(crate::linearization::plan::ObjStmBatchPlan {
            part3_batches: filter_batches(batch_plan.part3_batches),
            part4_batches: filter_batches(batch_plan.part4_batches),
        })
    }

    /// The flat batch order (Part-3 then Part-4) fed to
    /// [`RenumberMap::relocate_objstm_members`].
    fn flat_batches(
        batch_plan: &crate::linearization::plan::ObjStmBatchPlan,
    ) -> Vec<Vec<ObjectRef>> {
        batch_plan
            .part3_batches
            .iter()
            .chain(&batch_plan.part4_batches)
            .cloned()
            .collect()
    }

    /// Build the layout from an already-resolved batch plan, mapping every
    /// member + container through the **relocated** `renumber` map.
    ///
    /// `container_numbers` are the per-batch container object numbers returned
    /// by [`RenumberMap::relocate_objstm_members`] (Part-3 batches first, then
    /// Part-4), so the layout never re-derives numbers independently.  Every
    /// member ref is mapped through `renumber`; a missing entry is a planner /
    /// renumber inconsistency and is surfaced loudly.
    fn build_from_batches(
        batch_plan: &crate::linearization::plan::ObjStmBatchPlan,
        container_numbers: &[u32],
        renumber: &RenumberMap,
    ) -> Result<Self> {
        if batch_plan.part3_batches.is_empty() && batch_plan.part4_batches.is_empty() {
            return Ok(Self::default());
        }

        let mut member_to_container = BTreeMap::new();

        let take = |batches: &[Vec<ObjectRef>],
                    out: &mut Vec<ObjStmContainer>,
                    map: &mut BTreeMap<ObjectRef, (u32, u32)>,
                    container_iter: &mut std::vec::IntoIter<u32>|
         -> Result<()> {
            for batch in batches {
                if batch.is_empty() {
                    continue;
                }
                let container_new_num = container_iter.next().ok_or_else(|| {
                    crate::Error::Unsupported(
                        "linearization writer: ObjStm container-number stream exhausted \
                         (renumber relocation / batch-plan inconsistency)"
                            .to_string(),
                    )
                })?;
                let mut members = Vec::with_capacity(batch.len());
                for (idx, &orig) in batch.iter().enumerate() {
                    let new_ref = renumber.new_for_original(orig).ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "linearization writer: ObjStm member {orig} has no renumber \
                             entry (planner / renumber inconsistency)"
                        ))
                    })?;
                    map.insert(orig, (container_new_num, idx as u32));
                    members.push((orig, new_ref));
                }
                out.push(ObjStmContainer {
                    container_new_num,
                    members,
                });
            }
            Ok(())
        };

        let container_numbers_vec: Vec<u32> = container_numbers.to_vec();
        let mut container_iter = container_numbers_vec.into_iter();
        let mut part3 = Vec::new();
        let mut part4 = Vec::new();
        take(
            &batch_plan.part3_batches,
            &mut part3,
            &mut member_to_container,
            &mut container_iter,
        )?;
        take(
            &batch_plan.part4_batches,
            &mut part4,
            &mut member_to_container,
            &mut container_iter,
        )?;
        let _ = container_iter;

        Ok(Self {
            part3,
            part4,
            member_to_container,
        })
    }
}

/// Build (and FlateDecode-wrap) the ObjStm container stream object for one
/// scheduled container, resolving + renumbering each member from `pdf`.
fn build_objstm_container_object<R: Read + Seek>(
    container: &ObjStmContainer,
    renumber: &RenumberMap,
    pdf: &mut Pdf<R>,
) -> Result<Object> {
    let mut resolved: Vec<(ObjectRef, Object)> = Vec::with_capacity(container.members.len());
    for &(orig, new_ref) in &container.members {
        let object = pdf.resolve_borrowed(orig)?;
        let renumbered = renumber_object(object, renumber)?;
        resolved.push((new_ref, renumbered));
    }
    let body = emit_objstm_body_from_resolved(&resolved)?;
    // Linearized output always uses FlateDecode for ObjStm containers —
    // the linearization writer does not expose a CompressStreams knob.
    let stream = wrap_objstm_body(&body, crate::writer::CompressStreams::Yes)?;
    Ok(Object::Stream(stream))
}

// ---------------------------------------------------------------------------
// Public result types
// ---------------------------------------------------------------------------

/// Byte offsets and derived values returned by [`write_linearized`].
///
/// All values are absolute byte positions within `LinearizedDocument::bytes`
/// unless stated otherwise.  The back-patcher uses these to
/// fill the placeholder fields in the Part 1 parameter dictionary.
#[derive(Debug, Clone)]
pub struct LinearizedOffsets {
    /// Total file length in bytes — corresponds to `/L` in the param dict.
    pub file_length: usize,

    /// Byte offset of the hint stream object (its `N 0 obj` header) —
    /// corresponds to `/H[0]` in the param dict.
    pub hint_stream_offset: usize,

    /// Byte length of the hint stream's compressed data — corresponds to
    /// `/H[1]` in the param dict.
    ///
    /// Note: this is the length of the *compressed* (FlateDecode) byte
    /// sequence inside the `stream … endstream` envelope, i.e. the value of
    /// the hint stream object's own `/Length` key.
    pub hint_stream_length: usize,

    /// New object number assigned to the first-page page object — corresponds
    /// to `/O` in the param dict.  Typically `2` (first Part-2 object).
    pub first_page_object_new_num: u32,

    /// Byte offset immediately after the last byte of Annex F Part 3 (the
    /// first-page body section, `Plan.part2_objects`).  Corresponds to `/E`.
    pub end_of_first_page_offset: usize,

    /// Byte offset of the Part 6 cross-reference table (`xref` keyword).
    /// Used internally for convergence checks.
    pub last_xref_keyword_offset: usize,

    /// Byte offset of the first entry in the Part 6 cross-reference table
    /// (= position immediately after the `xref\n0 N\n` header line) —
    /// corresponds to `/T` in the param dict per qpdf's linearization convention.
    pub last_xref_offset: usize,

    /// Total number of pages — corresponds to `/N`.
    pub page_count: u32,

    /// Placeholder byte ranges inside the Part 1 bytes.  Pre-back-patch these
    /// are 10-wide zero slots; post-back-patch the back-patcher updates them
    /// to point at the rewritten variable-width decimal value bytes.
    pub part1_placeholders: Part1Placeholders,

    /// `new_object_number → byte_offset` map covering every object in the
    /// linearized file.  Used for structural verification.
    pub xref_offsets: BTreeMap<u32, usize>,

    /// Byte range of the `/Prev` value placeholder in the Part 1 (first)
    /// trailer.  The value is written as a left-justified decimal integer
    /// padded on the right with spaces to exactly `PREV_PLACEHOLDER_WIDTH`
    /// bytes.  The back-patcher overwrites this range with the actual
    /// `last_xref_keyword_offset` value.
    pub first_trailer_prev_range: std::ops::Range<usize>,

    /// Absolute byte range spanning the rewritable param-dict region:
    /// `<<` through the end of the trailing pad (inclusive of `\nendobj\n`).
    /// The back-patcher splices a variable-width dict body + space-pad into
    /// this region in one operation.
    pub dict_writable_region: std::ops::Range<usize>,
}

/// The finished linearized PDF together with the offset metadata.
#[derive(Debug)]
pub struct LinearizedDocument {
    /// Raw bytes of the complete linearized PDF file.
    pub bytes: Vec<u8>,
    /// Offset metadata for back-patching.
    pub offsets: LinearizedOffsets,
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Width of the `/Prev` value field in the Part 1 (first) trailer.
///
/// The value is written as a left-justified decimal integer with space-padding
/// on the right, matching qpdf's convention.  22 bytes is sufficient for any
/// PDF file offset up to 10^22 - 1 (qpdf uses the same width).
pub(crate) const PREV_PLACEHOLDER_WIDTH: usize = 22;

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Deep-clone `object`, replacing every `Reference(r)` with the renumbered
/// equivalent from `renumber`.  Returns an error if a reference cannot be
/// mapped — leaving an un-renumbered reference in a renumbered file would
/// produce a mixed old/new object number that the generated xref does not
/// describe, silently corrupting the linearized output.
///
/// Stream data bytes are **not** inspected — they are opaque binary blobs.
fn renumber_object(object: &Object, renumber: &RenumberMap) -> Result<Object> {
    match object {
        Object::Reference(r) => match renumber.new_for_original(*r) {
            Some(new_ref) => Ok(Object::Reference(new_ref)),
            None => Err(crate::Error::Unsupported(format!(
                "linearization writer: reference {r} has no entry in RenumberMap \
                 (planner / renumber inconsistency — would emit mixed old/new \
                 object numbers)"
            ))),
        },
        Object::Array(elements) => {
            let mut renumbered = Vec::with_capacity(elements.len());
            for e in elements {
                renumbered.push(renumber_object(e, renumber)?);
            }
            Ok(Object::Array(renumbered))
        }
        Object::Dictionary(dict) => {
            let mut new_dict = Dictionary::new();
            for (key, value) in dict.iter() {
                new_dict.insert(key, renumber_object(value, renumber)?);
            }
            Ok(Object::Dictionary(new_dict))
        }
        Object::Stream(stream) => {
            // Renumber the dictionary; leave the stream data bytes alone.
            let mut new_dict = Dictionary::new();
            for (key, value) in stream.dict.iter() {
                new_dict.insert(key, renumber_object(value, renumber)?);
            }
            Ok(Object::Stream(Stream::new(new_dict, stream.data.clone())))
        }
        // Scalar types contain no references — clone unchanged.
        _ => Ok(object.clone()),
    }
}

/// Append `N G obj\n<object>\nendobj\n` to `bytes` and return the offset of the
/// `N G obj` header (i.e. the start of the object).
fn append_object(bytes: &mut Vec<u8>, new_ref: ObjectRef, object: &Object) -> usize {
    let offset = bytes.len();
    bytes.extend_from_slice(format!("{} {} obj\n", new_ref.number, new_ref.generation).as_bytes());
    object.write_pdf(bytes);
    bytes.extend_from_slice(b"\nendobj\n");
    offset
}

/// Write a Part 1 xref subsection (the linearization parameter dict only) plus
/// a first-page trailer, then return `(xref_offset, prev_value_range)`.
///
/// The Part 1 xref is required by the linearized PDF spec so that a viewer can
/// quickly locate the linearization parameter dict without parsing the whole
/// file.  It covers only the param-dict object (at whatever number the
/// renumber map assigned it); all other objects are recorded in Part 6.
///
/// The first-page trailer includes `/Info` (when present), `/Root`, `/Size`,
/// `/Prev`, and `/ID` — matching qpdf's key order and content for linearized
/// PDFs.  The `/Prev` value is written as a left-justified decimal integer
/// padded on the right with spaces to [`PREV_PLACEHOLDER_WIDTH`] bytes so it
/// can be back-patched in-place once the Part 6 xref offset is known.
///
/// Returns `(xref_keyword_offset, prev_value_byte_range)` where
/// `prev_value_byte_range` is the absolute byte range of the `/Prev` value
/// field in `bytes` (for back-patching).
#[allow(clippy::too_many_arguments)]
fn write_part1_xref_and_trailer(
    bytes: &mut Vec<u8>,
    param_dict_offset: usize,
    param_dict_obj_number: u32,
    total_object_count: u32,
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
    source_trailer: &Dictionary,
) -> (usize, std::ops::Range<usize>) {
    let xref_offset = bytes.len();

    // Subsection: param dict object only.
    bytes.extend_from_slice(format!("xref\n{param_dict_obj_number} 1\n").as_bytes());
    bytes.extend_from_slice(format!("{:010} 00000 n \n", param_dict_offset).as_bytes());

    // First-page trailer for Part 1.  qpdf emits keys in this order:
    //   /Info /Root /Size /Prev /ID
    // We write the dict as raw bytes (not via Dictionary::write_pdf) to:
    //   (a) preserve qpdf's key order (BTreeMap would alphabetise),
    //   (b) reserve a fixed-width space-padded field for /Prev back-patching.
    bytes.extend_from_slice(b"trailer << ");

    // /Info (omit when absent — qpdf also omits it when the source has none)
    if let Some(info_ref) = info_new_ref {
        bytes.extend_from_slice(
            format!("/Info {} {} R ", info_ref.number, info_ref.generation).as_bytes(),
        );
    }

    // /Root
    bytes.extend_from_slice(
        format!(
            "/Root {} {} R ",
            catalog_new_ref.number, catalog_new_ref.generation
        )
        .as_bytes(),
    );

    // /Size
    bytes.extend_from_slice(format!("/Size {} ", total_object_count).as_bytes());

    // /Prev — placeholder: left-justified 0, space-padded to PREV_PLACEHOLDER_WIDTH bytes.
    bytes.extend_from_slice(b"/Prev ");
    let prev_value_start = bytes.len();
    // Write placeholder: "0" left-justified, padded to PREV_PLACEHOLDER_WIDTH with spaces.
    let placeholder = format!("{:<PREV_PLACEHOLDER_WIDTH$}", 0);
    bytes.extend_from_slice(placeholder.as_bytes());
    let prev_value_end = bytes.len();

    // /ID — emit the file identifier verbatim.
    //
    // `write_linearized` finalizes the /ID exactly once per save (via
    // `finalize_linearized_id`) and stores it on `source_trailer["ID"]`, so
    // the Part-1 trailer and every split xref/trailer in the same output all
    // emit the *same* identifier.  A PDF file identifier is file-scoped, so
    // regenerating a fresh random /ID here (as before) produced inconsistent
    // identifiers across trailers within one linearized file.
    if let Some(id_obj) = source_trailer.get("ID") {
        bytes.extend_from_slice(b" /ID ");
        id_obj.write_pdf(bytes);
    }

    bytes.extend_from_slice(b" >>");
    // Per linearized PDF convention (ISO 32000-1 Annex F and qpdf practice),
    // the Part 1 first trailer's startxref value is always 0.  The main xref
    // at the end of the file (Part 6) carries the real byte offset in its own
    // trailing startxref, so readers that follow the tail-startxref path are
    // unaffected.  qpdf uses 0 here to signal "this is the first trailer of a
    // linearized file"; we adopt the same convention for byte-identical output.
    bytes.extend_from_slice(b"\nstartxref\n0\n%%EOF\n");

    (xref_offset, prev_value_start..prev_value_end)
}

/// Write the Part 6 cross-reference table covering all objects (0 through N),
/// followed by the main trailer.
///
/// Returns `(xref_keyword_offset, xref_first_entry_offset)` where:
/// - `xref_keyword_offset` is the byte offset of the `xref` keyword
/// - `xref_first_entry_offset` is the byte offset of the first xref entry
///   (after the `xref\n0 N\n` header), which is the correct `/T` value per
///   qpdf's linearization checker.
fn write_main_xref_and_trailer(
    bytes: &mut Vec<u8>,
    xref_offsets: &BTreeMap<u32, usize>,
    total_count: u32, // /Size — highest object number + 1
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
) -> (usize, usize) {
    let xref_start = bytes.len();

    // Dense table: objects 0 .. total_count.
    let xref_header = format!("xref\n0 {}\n", total_count);
    bytes.extend_from_slice(xref_header.as_bytes());
    let xref_first_entry_offset = bytes.len();
    // Object 0 — free head.
    bytes.extend_from_slice(b"0000000000 65535 f \n");
    for number in 1..total_count {
        match xref_offsets.get(&number) {
            Some(offset) => {
                bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes())
            }
            None => bytes.extend_from_slice(b"0000000000 65535 f \n"),
        }
    }

    // Main trailer.
    let mut trailer = Dictionary::new();
    trailer.insert("Size", Object::Integer(i64::from(total_count)));
    trailer.insert("Root", Object::Reference(catalog_new_ref));
    if let Some(info_ref) = info_new_ref {
        trailer.insert("Info", Object::Reference(info_ref));
    }
    bytes.extend_from_slice(b"trailer\n");
    trailer.write_pdf(bytes);
    bytes.extend_from_slice(format!("\nstartxref\n{}\n%%EOF\n", xref_start).as_bytes());

    (xref_start, xref_first_entry_offset)
}

/// Byte width of every type-1/2 entry in the split xref streams: `W = [1, 8,
/// 4]` → `1 + 8 + 4 = 13` bytes per object.  Kept in one place so the
/// first-page placeholder length and the back-patch entry encoder agree.
const SPLIT_XREF_ENTRY_WIDTH: usize = 13;

/// Byte ranges (inside the writer's `bytes` buffer) the first-page xref stream
/// reserves for in-place back-patching once every downstream object offset and
/// the main (Part-6) xref offset are known.
struct FirstPageXrefPatch {
    /// Absolute byte offset of the `{num} 0 obj` header (= the value the
    /// main xref's `/Prev` and `/T` point at; mirrors the legacy
    /// `write_part1_xref_and_trailer` xref-keyword return).
    obj_offset: usize,
    /// Object number the first-page xref stream itself was assigned.
    first_xref_num: u32,
    /// Number of dense-table entries the stream covers: `[0, first_count)`.
    first_count: u32,
    /// Byte range of the raw (uncompressed) entry payload — overwritten with
    /// the real type-1/2 entries once offsets are final.
    data_range: std::ops::Range<usize>,
}

/// Encode the dense-table slice `[start, start+count)` as `W=[1,8,4]` xref
/// entry bytes.  Type-1 for plain objects with a known offset, type-2 for
/// ObjStm members, type-0 (free) otherwise.
fn encode_split_xref_slice(
    offs: &BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
    start: u32,
    count: u32,
) -> Vec<u8> {
    let mut data = Vec::with_capacity(count as usize * SPLIT_XREF_ENTRY_WIDTH);
    for number in start..start + count {
        if number == 0 {
            data.push(0);
            data.extend_from_slice(&0u64.to_be_bytes());
            data.extend_from_slice(&65535u32.to_be_bytes()[0..4]);
        } else if let Some(&off) = offs.get(&number) {
            data.push(1);
            data.extend_from_slice(&(off as u64).to_be_bytes());
            data.extend_from_slice(&0u32.to_be_bytes()[0..4]);
        } else if let Some(&(container, index)) = member_new.get(&number) {
            data.push(2);
            data.extend_from_slice(&u64::from(container).to_be_bytes());
            data.extend_from_slice(&index.to_be_bytes()[0..4]);
        } else {
            data.push(0);
            data.extend_from_slice(&0u64.to_be_bytes());
            data.extend_from_slice(&0u32.to_be_bytes()[0..4]);
        }
    }
    data
}

/// Compute the linearized output's `/ID` **once per save**.
///
/// A PDF file identifier is file-scoped: every trailer / xref-stream dict in
/// one linearized output must carry the *same* `/ID`.  `write_linearized`
/// calls this exactly once and stores the result on the working
/// `source_trailer` so the Part-1 trailer and all split xref/trailers emit an
/// identical identifier (previously each site regenerated a fresh random /ID,
/// producing inconsistent identifiers within a single file).
///
/// Policy mirrors `crate::writer`:
///   - `--static-id`: `[source_id0_or_π, π_const]`
///   - default: a fresh random two-element /ID — element 1 preserved from a
///     well-formed source /ID on re-save, both fresh on first save
///     (ISO 32000-1 §14.4).
fn finalize_linearized_id(options: &WriteOptions, source_trailer: &Dictionary) -> Object {
    let pi_bytes = Object::String(QPDF_STATIC_ID.to_vec());
    if options.static_id {
        let first_id = match source_trailer.get("ID") {
            Some(Object::Array(values))
                if values.len() == 2 && matches!(values[0], Object::String(_)) =>
            {
                values[0].clone()
            }
            _ => pi_bytes.clone(),
        };
        Object::Array(vec![first_id, pi_bytes])
    } else {
        crate::writer::random_id_array(source_trailer.get("ID"))
    }
}

/// `/ID` array for the split xref stream dicts.  Reads the file-scoped
/// identifier that `write_linearized` already finalized onto `source_trailer`
/// (see [`finalize_linearized_id`]) so it stays consistent with the Part-1
/// trailer.
fn split_xref_common_id(source_trailer: &Dictionary) -> Option<Object> {
    source_trailer.get("ID").cloned()
}

/// Emit the **first-page (Part-1) cross-reference stream** at its proper
/// position — physically inside the first-page region, *before* `/E*, in the
/// slot where the classic Part-1 mini-xref + first trailer would otherwise go.
///
/// A linearized PDF's first-page cross-reference section is part of the
/// first-page byte range so a reader can resolve page 1 from the leading
/// bytes; emitting it only at EOF defeats linearization.
///
/// The stream is written **uncompressed** with a *deterministic* payload
/// length (`first_count * 13`, where `first_count = first_xref_slot + 1` is a
/// stable plan-derived value), so its byte length never depends on the
/// downstream object offsets it records.  The entry payload is emitted as a
/// zero placeholder and back-patched in place by [`patch_first_page_xref`]
/// once every downstream object offset is known.  Because the emitted byte
/// length is invariant, no extra convergence variable is introduced — the
/// hint stream remains the sole degree of freedom.
///
/// This stream carries **no** `/Prev`: it is the leaf of the xref chain.
/// The main (Part-6) xref at EOF holds `/Prev → here` (chain main → first,
/// unchanged from the original split implementation) and the file's trailing
/// `startxref` points at the main xref, so the chain is acyclic.
///
/// `/Index [0, first_count]`: objects `0 ..= first_xref_slot`, all type-1
/// (param dict, hint, catalog, Part-2, Part-3-plain objects, and the
/// first-page xref object itself), so the stream carries a single contiguous
/// range with no type-1-after-type-2 interleave.
///
/// Note: every ObjStm container and member is numbered **above**
/// `first_xref_slot` (and above `main_xref_slot`) by
/// [`RenumberMap::relocate_objstm_members`], so none of them fall in this
/// range — they live exclusively in the main xref's `/Index`.  Part-3
/// (page-1 shared) objects are additionally kept *plain* by the planner
/// (`LinearizationPlan::objstm_batches` unconditionally clears
/// `part3_batches`), so no Part-3 ObjStm container is ever
/// emitted before `/E`.  Re-enabling Part-3 packing requires reconciling
/// container numbering with this split-xref range; until then this range is
/// exactly the Part-3-plain set.
#[allow(clippy::too_many_arguments)]
fn write_first_page_xref_stream(
    bytes: &mut Vec<u8>,
    relocation: &ObjStmRelocation,
    total_count: u32, // /Size (relocated renumber.len() + 1) — already final
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
    source_trailer: &Dictionary,
) -> Result<FirstPageXrefPatch> {
    let final_size = total_count;
    let first_xref_num = relocation.first_xref_slot;
    let first_count = first_xref_num
        .checked_add(1)
        .ok_or_else(|| crate::Error::Unsupported("xref /Index overflow".to_string()))?;
    let payload_len = (first_count as usize)
        .checked_mul(SPLIT_XREF_ENTRY_WIDTH)
        .ok_or_else(|| {
            crate::Error::Unsupported("first-page xref payload length overflow".to_string())
        })?;

    let obj_offset = bytes.len();

    let mut d1 = Dictionary::new();
    d1.insert("Type", Object::Name(b"XRef".to_vec()));
    d1.insert("Size", Object::Integer(i64::from(final_size)));
    d1.insert(
        "W",
        Object::Array(vec![
            Object::Integer(1),
            Object::Integer(8),
            Object::Integer(4),
        ]),
    );
    d1.insert(
        "Index",
        Object::Array(vec![
            Object::Integer(0),
            Object::Integer(i64::from(first_count)),
        ]),
    );
    d1.insert("Root", Object::Reference(catalog_new_ref));
    if let Some(info_ref) = info_new_ref {
        d1.insert("Info", Object::Reference(info_ref));
    }
    if let Some(id) = split_xref_common_id(source_trailer) {
        d1.insert("ID", id);
    }
    // The payload is stored uncompressed so /Length is the constant
    // `payload_len` regardless of the offsets it will later carry.
    d1.insert("Length", Object::Integer(payload_len as i64));

    // Emit the object header + stream via the normal serialiser.  Key order
    // is BTreeMap-lexicographic (qpdf reads xref streams regardless of key
    // order; the project targets observed qpdf-clean equivalence, not byte
    // identity).  The payload is a zero placeholder of the exact final length.
    bytes.extend_from_slice(format!("{first_xref_num} 0 obj\n").as_bytes());
    Object::Stream(Stream::new(d1, vec![0u8; payload_len])).write_pdf(bytes);
    bytes.extend_from_slice(b"\nendobj\n");

    // Locate the placeholder payload range so the caller can back-patch it
    // once downstream offsets are final.  The serialiser emits the stream
    // body verbatim between `stream\n` and `\nendstream`; the payload has a
    // fixed length so the byte range is unambiguous.
    let marker = b"stream\n";
    let obj_slice = &bytes[obj_offset..];
    let rel = obj_slice
        .windows(marker.len())
        .position(|w| w == marker)
        .ok_or_else(|| {
            crate::Error::Unsupported(
                "first-page xref stream: `stream` keyword not found after emission".to_string(),
            )
        })?;
    let data_start = obj_offset + rel + marker.len();
    let data_end = data_start + payload_len;
    debug_assert!(
        data_end <= bytes.len() && &bytes[data_end..data_end + 1] == b"\n",
        "first-page xref payload range mislocated"
    );

    Ok(FirstPageXrefPatch {
        obj_offset,
        first_xref_num,
        first_count,
        data_range: data_start..data_end,
    })
}

/// Overwrite the first-page xref stream's placeholder entry payload in place,
/// now that every downstream object offset is known.
///
/// The first-page xref's `/Index [0, first_count)` covers only the type-1
/// plain objects (members live in the main xref's range), so the encoder only
/// needs `xref_offsets` plus the first-page xref object's own offset.  Because
/// the payload was emitted at its final byte length, this is a pure in-place
/// patch — no offsets shift, the hint-stream convergence loop is untouched.
/// The first-page stream has no `/Prev` (it is the chain leaf), so nothing
/// else needs patching here.
fn patch_first_page_xref(
    bytes: &mut [u8],
    patch: &FirstPageXrefPatch,
    xref_offsets: &BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
) -> Result<()> {
    let mut offs = xref_offsets.clone();
    offs.insert(patch.first_xref_num, patch.obj_offset);

    let data = encode_split_xref_slice(&offs, member_new, 0, patch.first_count);
    if data.len() != patch.data_range.len() {
        return Err(crate::Error::Unsupported(format!(
            "first-page xref payload length drift: encoded {} bytes, reserved {}",
            data.len(),
            patch.data_range.len()
        )));
    }
    if patch.data_range.end > bytes.len() {
        return Err(crate::Error::Unsupported(
            "first-page xref patch range out of bounds".to_string(),
        ));
    }
    bytes[patch.data_range.clone()].copy_from_slice(&data);
    Ok(())
}

/// Emit the **main (Part-6) cross-reference stream** at end-of-body, followed
/// by the trailing `startxref`/`%%EOF`.
///
/// `/Index [main_xref_slot, Size − main_xref_slot]`: objects `main_xref_slot
/// ..= last`, type-1 (the main xref object + remaining Part-4 containers)
/// then type-2 (all ObjStm members) — a single contiguous range with no
/// type-1-after-type-2 interleave.
///
/// The `/Prev` chain stays main → first-page (unchanged from the original
/// split implementation; qpdf accepts either direction and the first-page
/// stream's own `/Prev` points back here).  Returns `(main_xref_offset,
/// first_page_obj_offset)` so the caller's `/Prev` / `/T` contract is
/// preserved: `/T = first_page_obj_offset − 1` (caller applies the
/// `saturating_sub(1)`), matching qpdf's "byte before the first-page xref".
#[allow(clippy::too_many_arguments)]
fn write_main_xref_stream_and_trailer(
    bytes: &mut Vec<u8>,
    xref_offsets: &BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
    relocation: &ObjStmRelocation,
    total_count: u32, // /Size (relocated renumber.len() + 1) — already final
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
    source_trailer: &Dictionary,
    first_page_obj_offset: usize,
) -> Result<(usize, usize)> {
    let final_size = total_count;
    let first_xref_num = relocation.first_xref_slot;
    let main_xref_num = relocation.main_xref_slot;

    let main_count = final_size
        .checked_sub(main_xref_num)
        .ok_or_else(|| crate::Error::Unsupported("xref /Index underflow".to_string()))?;
    let main_xref_offset = bytes.len();
    let mut offs2 = xref_offsets.clone();
    offs2.insert(first_xref_num, first_page_obj_offset);
    offs2.insert(main_xref_num, main_xref_offset);

    let main_data = encode_split_xref_slice(&offs2, member_new, main_xref_num, main_count);
    let mut enc_dict2 = Dictionary::new();
    enc_dict2.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
    let main_encoded = crate::filters::encode_stream_data(&enc_dict2, &main_data)?;

    let mut d2 = Dictionary::new();
    d2.insert("Type", Object::Name(b"XRef".to_vec()));
    d2.insert("Size", Object::Integer(i64::from(final_size)));
    d2.insert(
        "W",
        Object::Array(vec![
            Object::Integer(1),
            Object::Integer(8),
            Object::Integer(4),
        ]),
    );
    d2.insert(
        "Index",
        Object::Array(vec![
            Object::Integer(i64::from(main_xref_num)),
            Object::Integer(i64::from(main_count)),
        ]),
    );
    d2.insert("Root", Object::Reference(catalog_new_ref));
    if let Some(info_ref) = info_new_ref {
        d2.insert("Info", Object::Reference(info_ref));
    }
    if let Some(id) = split_xref_common_id(source_trailer) {
        d2.insert("ID", id);
    }
    // /Prev → first-page xref stream object offset (qpdf chains main → first).
    d2.insert("Prev", Object::Integer(first_page_obj_offset as i64));
    d2.insert("Length", Object::Integer(main_encoded.len() as i64));
    d2.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
    bytes.extend_from_slice(format!("{main_xref_num} 0 obj\n").as_bytes());
    Object::Stream(Stream::new(d2, main_encoded)).write_pdf(bytes);
    bytes.extend_from_slice(b"\nendobj\n");
    bytes.extend_from_slice(format!("startxref\n{main_xref_offset}\n%%EOF\n").as_bytes());

    // `/T` rule for the split linearized file is the byte just before the
    // **first-page** cross-reference stream (the object the main xref's
    // `/Prev` chains back to).  The caller computes `/T =
    // second_return.saturating_sub(1)`, so return `first_page_obj_offset`
    // here.  The first element is the main xref offset (used as the file's
    // trailing `startxref` / convergence diagnostics).
    Ok((main_xref_offset, first_page_obj_offset))
}

/// Build the hint stream object bytes for a given compressed payload.
///
/// Returns the full object bytes (header + dict + stream + endobj) and the
/// byte length of the object for `/H[1]`.
fn build_hint_stream_object(
    new_ref: ObjectRef,
    compressed_payload: &[u8],
    shared_section_offset: usize,
) -> Object {
    let compressed_len = compressed_payload.len();
    let mut hint_dict = Dictionary::new();
    hint_dict.insert("Length", Object::Integer(compressed_len as i64));
    hint_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
    hint_dict.insert("S", Object::Integer(shared_section_offset as i64));
    let _ = new_ref; // ref is used at call site via append_object
    Object::Stream(Stream::new(hint_dict, compressed_payload.to_vec()))
}

/// Perform a complete single-pass write of the linearized PDF body.
///
/// Returns `(bytes, xref_offsets, hint_stream_offset, hint_stream_obj_total_len,
///           end_of_first_page_offset, last_xref_offset, last_xref_first_entry_offset,
///           first_trailer_prev_range)`.
///
/// `hint_compressed` is the compressed payload to use for the hint stream object.
/// `hint_shared_section_offset` is the `/S` value (offset within the uncompressed stream).
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn do_write_pass<R: Read + Seek>(
    plan: &LinearizationPlan,
    renumber: &RenumberMap,
    pdf: &mut Pdf<R>,
    part1: &Part1Bytes,
    catalog_new_ref: ObjectRef,
    hint_stream_new_num: u32,
    total_count: u32,
    info_new_ref: Option<ObjectRef>,
    _first_page_object_new_num: u32,
    hint_compressed: &[u8],
    hint_shared_section_offset: usize,
    source_trailer: &Dictionary,
    objstm_layout: &ObjStmLayout,
    relocation: &ObjStmRelocation,
) -> Result<(
    Vec<u8>,
    BTreeMap<u32, usize>,
    usize,                  // hint_stream_offset
    usize,                  // hint_stream_obj_total_len
    usize,                  // end_of_first_page_offset
    usize,                  // last_xref_offset (xref keyword position)
    usize,                  // last_xref_first_entry_offset (= /T value per qpdf's convention)
    std::ops::Range<usize>, // first_trailer_prev_range
)> {
    let mut bytes: Vec<u8> = Vec::new();
    let mut xref_offsets: BTreeMap<u32, usize> = BTreeMap::new();

    // Part 1
    let param_dict_obj_number = renumber.param_dict_ref().number;
    let param_dict_absolute_offset = part1.obj1_offset;
    bytes.extend_from_slice(&part1.bytes);
    xref_offsets.insert(param_dict_obj_number, param_dict_absolute_offset);

    // member new-number → (container new-number, index) for the type-2 xref
    // entries.  Built once: the first-page xref stream (emitted just below,
    // before /E) and the main xref stream (emitted at EOF) both consume it.
    let mut member_new: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    for container in objstm_layout.part3.iter().chain(&objstm_layout.part4) {
        for (idx, &(_orig, new_ref)) in container.members.iter().enumerate() {
            member_new.insert(new_ref.number, (container.container_new_num, idx as u32));
        }
    }

    // The classic Part-1 mini-xref + first trailer is only emitted on the
    // non-ObjStm path.  For ObjStm-bearing output the first-page (Part-1)
    // *xref stream* takes its place — and, per the flpdf-56u review, it MUST
    // sit physically here (inside the first-page region, before /E) so a
    // reader can resolve page 1 from the leading bytes.  It is written with a
    // deterministic byte length (uncompressed payload + fixed-width /Prev) and
    // back-patched in place once the downstream offsets and the main (Part-6)
    // xref offset are known (see `patch_first_page_xref` below) — so the
    // hint-stream convergence loop stays single-variable.  Returning an empty
    // `/Prev` range tells the back-patcher there is no classic Part-1 trailer
    // `/Prev` to patch.
    let mut first_page_xref_patch: Option<FirstPageXrefPatch> = None;
    let first_trailer_prev_range = if objstm_layout.is_empty() {
        let (_p1_xref_offset, range) = write_part1_xref_and_trailer(
            &mut bytes,
            param_dict_absolute_offset,
            param_dict_obj_number,
            total_count,
            catalog_new_ref,
            info_new_ref,
            source_trailer,
        );
        range
    } else {
        let patch = write_first_page_xref_stream(
            &mut bytes,
            relocation,
            total_count,
            catalog_new_ref,
            info_new_ref,
            source_trailer,
        )?;
        first_page_xref_patch = Some(patch);
        0..0
    };

    // Hint stream object
    let hint_new_ref = ObjectRef::new(hint_stream_new_num, 0);
    let hint_obj =
        build_hint_stream_object(hint_new_ref, hint_compressed, hint_shared_section_offset);
    let hint_stream_offset = append_object(&mut bytes, hint_new_ref, &hint_obj);
    xref_offsets.insert(hint_stream_new_num, hint_stream_offset);
    let hint_stream_obj_total_len = bytes.len() - hint_stream_offset;

    // Part 3 (Annex F): first-page body — Plan.part2_objects (page-0 private
    // objects).  part2_objects can never be ObjStm members (the planner's
    // invariant), but skip defensively via the membership map so a planner
    // bug surfaces as a missing xref entry rather than a duplicate object.
    for original_ref in &plan.part2_objects {
        if objstm_layout.member_to_container.contains_key(original_ref) {
            continue;
        }
        let Some(new_ref) = renumber.new_for_original(*original_ref) else {
            return Err(crate::Error::Unsupported(format!(
                "part2 object {} has no renumber entry",
                original_ref
            )));
        };
        let object = pdf.resolve_borrowed(*original_ref)?;
        let renumbered = renumber_object(object, renumber)?;
        let offset = append_object(&mut bytes, new_ref, &renumbered);
        xref_offsets.insert(new_ref.number, offset);
    }

    // Part 3 (Annex F) continued: shared objects sit INSIDE the first-page
    // section.  qpdf's hint table validator counts page 0's object_count
    // as Part-2 + Part-3 (all objects before /E), and /E itself is the
    // byte after the last shared object.  Putting shared objects after /E
    // causes "/E mismatch" and "object count for page 0 = N; computed = M"
    // warnings.  ObjStm members are routed into a container instead of a
    // plain indirect; their container is emitted below, still before /E.
    for original_ref in &plan.part3_objects {
        if objstm_layout.member_to_container.contains_key(original_ref) {
            continue;
        }
        let Some(new_ref) = renumber.new_for_original(*original_ref) else {
            return Err(crate::Error::Unsupported(format!(
                "part3 object {} has no renumber entry",
                original_ref
            )));
        };
        let object = pdf.resolve_borrowed(*original_ref)?;
        let renumbered = renumber_object(object, renumber)?;
        let offset = append_object(&mut bytes, new_ref, &renumbered);
        xref_offsets.insert(new_ref.number, offset);
    }

    // Part-3 ObjStm containers.  These hold shared/catalog members and MUST
    // sit before /E so qpdf's first-page object count (and the observed
    // qpdf 11.9 /E placement, which includes the Part-3 ObjStm) stays
    // consistent.  The container itself is a plain indirect object.
    for container in &objstm_layout.part3 {
        let container_obj = build_objstm_container_object(container, renumber, pdf)?;
        let container_ref = ObjectRef::new(container.container_new_num, 0);
        let offset = append_object(&mut bytes, container_ref, &container_obj);
        xref_offsets.insert(container.container_new_num, offset);
    }

    // /E: end of first-page section, AFTER Part-2, Part-3 and the Part-3
    // ObjStm containers.
    let end_of_first_page_offset = bytes.len();

    // Part 5 (Annex F): remaining body — derived view of all Part-4
    // sub-partitions in writer-emission order.  ObjStm members are skipped
    // here and emitted via their Part-4 container below.
    for original_ref in &plan.part4_objects() {
        if objstm_layout.member_to_container.contains_key(original_ref) {
            continue;
        }
        let Some(new_ref) = renumber.new_for_original(*original_ref) else {
            return Err(crate::Error::Unsupported(format!(
                "part4 object {} has no renumber entry",
                original_ref
            )));
        };
        let object = pdf.resolve_borrowed(*original_ref)?;
        let renumbered = renumber_object(object, renumber)?;
        let offset = append_object(&mut bytes, new_ref, &renumbered);
        xref_offsets.insert(new_ref.number, offset);
    }

    // Part-4 ObjStm containers (after /E, in the remaining body).
    for container in &objstm_layout.part4 {
        let container_obj = build_objstm_container_object(container, renumber, pdf)?;
        let container_ref = ObjectRef::new(container.container_new_num, 0);
        let offset = append_object(&mut bytes, container_ref, &container_obj);
        xref_offsets.insert(container.container_new_num, offset);
    }

    // Part 6: main cross-reference + trailer.
    //
    // When ObjStm containers are present the body holds compressed (type-2)
    // members which a classic xref table cannot represent, so Part 6 becomes
    // an xref stream.  With an empty layout the classic table path is kept
    // verbatim — no behavioural change for Disable / no-ObjStm inputs.
    let (last_xref_offset, last_xref_first_entry_offset) = if objstm_layout.is_empty() {
        write_main_xref_and_trailer(
            &mut bytes,
            &xref_offsets,
            total_count,
            catalog_new_ref,
            info_new_ref,
        )
    } else {
        // The first-page xref stream was already emitted before /E; record
        // where it landed so the main xref's /Prev (main → first) and /T can
        // point at it.
        let patch = first_page_xref_patch.as_ref().ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization writer: ObjStm path produced no first-page xref patch \
                 (internal invariant violated)"
                    .to_string(),
            )
        })?;
        let first_page_obj_offset = patch.obj_offset;

        // Boundary invariant (epic 5.8 acceptance / flpdf-56u): the first-page
        // cross-reference section must be physically inside the first-page
        // region, i.e. before /E.
        debug_assert!(
            first_page_obj_offset < end_of_first_page_offset,
            "first-page xref stream offset ({first_page_obj_offset}) must be before \
             /E ({end_of_first_page_offset}) — linearization boundary violated"
        );

        let result = write_main_xref_stream_and_trailer(
            &mut bytes,
            &xref_offsets,
            &member_new,
            relocation,
            total_count,
            catalog_new_ref,
            info_new_ref,
            source_trailer,
            first_page_obj_offset,
        )?;

        // Every downstream object offset is now known, so back-patch the
        // first-page xref's placeholder entry payload in place.  The payload
        // length was reserved exactly, so this shifts no bytes and the
        // hint-stream convergence loop is unaffected.
        patch_first_page_xref(&mut bytes, patch, &xref_offsets, &member_new)?;

        result
    };

    Ok((
        bytes,
        xref_offsets,
        hint_stream_offset,
        hint_stream_obj_total_len,
        end_of_first_page_offset,
        last_xref_offset,
        last_xref_first_entry_offset,
        first_trailer_prev_range,
    ))
}

/// Compute per-object byte lengths from a written-out `xref_offsets` map.
///
/// Each object's byte length = offset of the next object (or end-of-xref-section)
/// minus this object's offset.
///
/// Returns `new_number → byte_length` map.
fn compute_byte_lengths(
    xref_offsets: &BTreeMap<u32, usize>,
    last_xref_offset: usize,
    hint_stream_new_num: u32,
    param_dict_new_num: u32,
) -> BTreeMap<u32, usize> {
    // Build a sorted list of (offset, new_number) pairs, plus a sentinel for
    // the last_xref_offset (= start of main xref, which terminates the body).
    let mut sorted: Vec<(usize, u32)> = xref_offsets
        .iter()
        // Exclude the param dict (Part 1, written before the hint stream).
        // The slot is dynamic because the renumber map may promote /Pages,
        // /Info, /Catalog ahead of it — hard-coding `1` here would skip the
        // wrong object whenever the param dict moves.
        .filter(|(&num, _)| num != param_dict_new_num)
        .map(|(&num, &off)| (off, num))
        .collect();
    sorted.sort_unstable();

    let mut lengths: BTreeMap<u32, usize> = BTreeMap::new();
    for (idx, &(off, num)) in sorted.iter().enumerate() {
        // Skip the hint stream — its "length" is used separately.
        if num == hint_stream_new_num {
            continue;
        }
        let next_off = if idx + 1 < sorted.len() {
            sorted[idx + 1].0
        } else {
            last_xref_offset
        };
        lengths.insert(num, next_off.saturating_sub(off));
    }
    lengths
}

/// Compute `adjusted_offset`: if `off >= hint_offset`, add `hint_length` to
/// account for the fact that the hint stream object is inserted between Part 1
/// and the body objects.
///
/// Probed offsets do NOT include the real hint stream; final offsets DO.
/// The difference is exactly `hint_length` (the hint stream object byte length).
///
/// Currently unused — the writer uses `do_write_pass` returns directly — but
/// kept here as a reference for future probe/final-pass refactoring.
#[allow(dead_code)]
fn adjusted_offset(off: usize, hint_offset: usize, hint_length: usize) -> usize {
    if off >= hint_offset {
        off + hint_length
    } else {
        off
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Write a complete linearized PDF to an in-memory buffer.
///
/// Given a [`LinearizationPlan`] (which partitions all objects into the four
/// body parts) and a [`RenumberMap`] (which assigns the correct linearized
/// object numbers), this function:
///
/// 1. Emits Part 1: header + linearization param dict (whose object number is
///    `renumber.param_dict_ref().number` — typically 3 with the qpdf-aligned
///    slot allocation, never assumed to be 1) with placeholder numeric values,
///    followed by a one-object xref subsection and trailer.
/// 2. Emits the hint stream object at `renumber.hint_stream_slot()` (Annex F
///    Part 2). /Size in both trailers is `renumber.len() as u32 + 1`.
/// 3. Emits the first-page body objects (`Plan.part2_objects` — Annex F Part 3).
/// 4. Emits the shared/catalog/info objects (`Plan.part3_objects` — Annex F Part 4).
/// 5. Emits the remaining body objects (`Plan.part4_objects()` — Annex F Part 5).
/// 6. Emits the main cross-reference table and trailer (Annex F Part 6).
///
/// Uses a convergence loop (max 3 iterations) to ensure the hint stream's
/// compressed byte length is stable before the final write.
///
/// Returns [`LinearizedDocument`] containing both the bytes and the
/// [`LinearizedOffsets`] needed for back-patching.
///
/// # Errors
///
/// Returns [`crate::Error::Unsupported`] when the plan and renumber map are
/// inconsistent or a layout value does not fit its slot — for example an
/// object (catalog, page, shared, or body object) has no entry in the
/// [`RenumberMap`], the plan has no page hints or a `per_page_private_objects`
/// length that disagrees with `page_hints`, `/Size` overflows `u32`, a shared
/// object lacks a probed byte length, or the hint-stream compressed length
/// fails to converge within the iteration budget.
///
/// Propagates any error from resolving source objects via
/// [`Pdf::resolve_borrowed`] (e.g. [`crate::Error::Io`] or
/// [`crate::Error::Parse`]) and from the underlying ObjStm-batch planning,
/// hint-stream encoding, and xref-stream filtering steps.
pub fn write_linearized<R: Read + Seek>(
    plan: &LinearizationPlan,
    renumber: &RenumberMap,
    pdf: &mut Pdf<R>,
    options: &WriteOptions,
) -> Result<LinearizedDocument> {
    // ------------------------------------------------------------------
    // Pre-compute values that do not change across iterations.
    // ------------------------------------------------------------------
    // ------------------------------------------------------------------
    // ObjStm relocation (flpdf-56u).
    //
    // qpdf's linearization checker forbids an uncompressed (type-1) xref
    // entry appearing after a compressed (type-2) one within a cross-
    // reference stream.  flpdf's classic slot allocation leaves ObjStm
    // members at their low Part-3 slots while containers sit above
    // `renumber.len()`, which interleaves type-1 and type-2 entries.
    //
    // Fix: resolve the writer-filtered batch plan ONCE, then relocate every
    // member to a contiguous high-numbered block (qpdf "container < members,
    // members trailing") and number each container directly below its
    // members.  The resulting `local_renumber` is used everywhere downstream;
    // when there are no ObjStm batches it is byte-identical to the input map
    // (the relocation early-returns), so the Disable / non-ObjStm path is
    // completely unchanged.
    // ------------------------------------------------------------------
    let resolved_batch_plan = ObjStmLayout::resolve_batches(plan, pdf, options)?;
    let flat_batches = ObjStmLayout::flat_batches(&resolved_batch_plan);
    let mut local_renumber = renumber.clone();
    let relocation = local_renumber.relocate_objstm_members(&flat_batches);
    let container_numbers = relocation.container_numbers.clone();
    let renumber: &RenumberMap = &local_renumber;

    let eff_version = effective_pdf_version(pdf.version(), options, true);
    let part1 = Part1Bytes::build(plan, renumber, eff_version);
    let part1_placeholders = part1.placeholders.clone();
    let part1_dict_region = part1.dict_writable_region.clone();

    let catalog_orig = plan.root_ref.ok_or_else(|| {
        crate::Error::Unsupported(
            "linearization writer: plan.root_ref is None — \
             cannot determine catalog reference for the trailer"
                .to_string(),
        )
    })?;
    let catalog_new_ref: ObjectRef = renumber.new_for_original(catalog_orig).ok_or_else(|| {
        crate::Error::Unsupported(format!(
            "linearization writer: catalog {catalog_orig} is not in RenumberMap \
             (planner / renumber inconsistency)"
        ))
    })?;

    let hint_stream_new_num: u32 = renumber.hint_stream_slot();

    // ------------------------------------------------------------------
    // Build the ObjStm layout from the relocated map (stable across the
    // convergence loop).  Container + member numbers now live INSIDE the
    // renumber map (relocation appended them), so the pair tables never
    // shift between iterations — only the surrounding byte offsets do.
    // ------------------------------------------------------------------
    let objstm_layout =
        ObjStmLayout::build_from_batches(&resolved_batch_plan, &container_numbers, renumber)?;

    // Highest object number actually used in the output.  After relocation
    // the renumber map already counts every plain object, every ObjStm
    // container, every member, AND both split xref-stream objects (the two
    // reserved slots), so `len()` is the highest slot.  Adding 1 yields the
    // /Size value (numbering is 1-based; Size counts the free entry at
    // object 0).  No extra object number is consumed for the xref stream(s)
    // on the ObjStm path — they live in their pre-reserved slots.
    let total_count: u32 = renumber
        .len()
        .checked_add(1)
        .and_then(|n| u32::try_from(n).ok())
        .ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization writer: /Size overflows u32 (too many objects / \
                 ObjStm containers)"
                    .to_string(),
            )
        })?;

    let info_new_ref: Option<ObjectRef> = pdf
        .trailer()
        .get_ref("Info")
        .and_then(|orig| renumber.new_for_original(orig));

    let first_page_object_new_num: u32 = {
        let first_page_hint = plan.page_hints.first().ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization plan has no page hints (empty document?)".to_string(),
            )
        })?;
        renumber
            .new_for_original(first_page_hint.page_ref)
            .ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "first-page page_ref {} has no renumber entry",
                    first_page_hint.page_ref,
                ))
            })?
            .number
    };

    // ------------------------------------------------------------------
    // Build initial placeholder hint tables (all lengths = 0).
    // ------------------------------------------------------------------
    let po_table_initial = PageOffsetHintTable::from_plan(plan, renumber);
    let so_table_initial = SharedObjectHintTable::from_plan(plan, renumber);
    let hint_bytes_initial = encode_hint_stream(&po_table_initial, &so_table_initial)?;
    let mut current_hint_compressed = hint_bytes_initial.compressed;
    let mut current_hint_shared_s = hint_bytes_initial.shared_section_offset_in_uncompressed;

    // Capture the source trailer once; it does not change across iterations.
    //
    // Finalize the file identifier exactly once here (before the convergence
    // loop) and store it back on the working trailer.  The Part-1 trailer and
    // every split xref/trailer then read this single value, so one linearized
    // output carries one consistent /ID — and it also stays stable across the
    // up-to-3 convergence iterations.
    let mut source_trailer = pdf.trailer().clone();
    let finalized_id = finalize_linearized_id(options, &source_trailer);
    source_trailer.insert("ID", finalized_id);
    let source_trailer = source_trailer;

    // ------------------------------------------------------------------
    // Convergence loop (max 3 iterations).
    // ------------------------------------------------------------------
    let max_iters = 3;
    let mut final_bytes: Vec<u8> = Vec::new();
    let mut final_xref_offsets: BTreeMap<u32, usize> = BTreeMap::new();
    let mut final_hint_stream_offset: usize = 0;
    let mut final_hint_stream_obj_total_len: usize = 0;
    let mut final_end_of_first_page_offset: usize = 0;
    let mut final_last_xref_keyword_offset: usize = 0;
    let mut final_last_xref_first_entry_offset: usize = 0;
    let mut final_first_trailer_prev_range: std::ops::Range<usize> = 0..0;

    for iter in 0..max_iters {
        let (
            bytes,
            xref_offsets,
            hint_stream_offset,
            hint_stream_obj_total_len,
            end_of_first_page_offset,
            last_xref_offset,
            last_xref_first_entry_offset,
            _probe_prev_range,
        ) = do_write_pass(
            plan,
            renumber,
            pdf,
            &part1,
            catalog_new_ref,
            hint_stream_new_num,
            total_count,
            info_new_ref,
            first_page_object_new_num,
            &current_hint_compressed,
            current_hint_shared_s,
            &source_trailer,
            &objstm_layout,
            &relocation,
        )?;

        // ------------------------------------------------------------------
        // Compute per-object byte lengths from this probe pass.
        // Use the xref keyword offset (not first_entry_offset) for length computation.
        // ------------------------------------------------------------------
        let byte_lengths = compute_byte_lengths(
            &xref_offsets,
            last_xref_offset,
            hint_stream_new_num,
            renumber.param_dict_ref().number,
        );

        // ------------------------------------------------------------------
        // Per-page byte lengths.
        //
        // Page 0 owns the shared objects physically (they sit before /E),
        // so its byte_length includes Part 2 + Part 3.  Pages 1..N use only
        // their own private objects.
        // ------------------------------------------------------------------
        // Members routed into a Part-3 ObjStm have no standalone bytes (they
        // live inside the container); their physical contribution is the
        // container object itself, which IS in `byte_lengths`.  Sum the
        // still-plain part3 objects, then add every Part-3 container's bytes.
        let part3_plain_len: u64 = plan
            .part3_objects
            .iter()
            .filter(|orig| !objstm_layout.member_to_container.contains_key(orig))
            .map(|orig| {
                renumber
                    .new_for_original(*orig)
                    .and_then(|new_ref| byte_lengths.get(&new_ref.number).copied())
                    .unwrap_or(0) as u64
            })
            .sum();
        let part3_container_len: u64 = objstm_layout
            .part3
            .iter()
            .map(|c| byte_lengths.get(&c.container_new_num).copied().unwrap_or(0) as u64)
            .sum();
        let part3_byte_len: u64 = part3_plain_len + part3_container_len;

        // Manually-constructed plans must keep `per_page_private_objects`
        // aligned with `page_hints` (one entry per page).  A shorter list
        // would silently leave some page-length hint fields unpatched —
        // fail fast instead.
        if plan.per_page_private_objects.len() != plan.page_hints.len() {
            return Err(crate::Error::Unsupported(format!(
                "linearization writer: per_page_private_objects length ({}) does not \
                 match page_hints length ({}) — plan invariant violated",
                plan.per_page_private_objects.len(),
                plan.page_hints.len()
            )));
        }

        let per_page_byte_lengths: Vec<u64> = plan
            .per_page_private_objects
            .iter()
            .enumerate()
            .map(|(page_idx, privates)| {
                let private_len: u64 = privates
                    .iter()
                    .map(|orig| {
                        renumber
                            .new_for_original(*orig)
                            .and_then(|new_ref| byte_lengths.get(&new_ref.number).copied())
                            .unwrap_or(0) as u64
                    })
                    .sum();
                if page_idx == 0 {
                    private_len + part3_byte_len
                } else {
                    private_len
                }
            })
            .collect();

        // ------------------------------------------------------------------
        // Patch hint tables.
        // ------------------------------------------------------------------
        let mut po_table = PageOffsetHintTable::from_plan(plan, renumber);
        let mut so_table = SharedObjectHintTable::from_plan(plan, renumber);

        // location_of_first_page = byte offset of the hint stream object itself.
        //
        // Per PDF Annex F and qpdf's implementation, this field stores the absolute
        // byte offset of the hint stream object (the start of the first-page section).
        // qpdf interprets it as: actual_page_object_offset = location_of_first_page + H_length,
        // where H_length is the full byte span of the hint stream object (stored as /H[1]).
        //
        // Since the hint stream always starts immediately after Part 1, and Part 1 length
        // is constant across all convergence iterations, hint_stream_offset is stable.
        po_table.header.location_of_first_page = hint_stream_offset as u64;

        // Page length fields.
        //
        // Content-stream fields (items 6-9 of header, items 6-7 of each per-page
        // entry) follow qpdf's heuristic from QPDF_linearization.cc:1786-1808:
        // since the page objects are not interleaved with the content stream,
        // qpdf reuses the page-length values for the content-length fields and
        // leaves the content-offset fields at 0 (matching Adobe implementation
        // note 127).  Mirroring this gives readers a usable initial-rendering
        // hint and keeps us on the path toward bytes-identical hint streams.
        if !per_page_byte_lengths.is_empty() {
            let least_pl = per_page_byte_lengths.iter().copied().min().unwrap_or(0);
            let max_pl = per_page_byte_lengths.iter().copied().max().unwrap_or(0);
            let bits_delta_pl = bits_needed(max_pl.saturating_sub(least_pl));
            po_table.header.least_page_length = least_pl;
            po_table.header.bits_page_length_delta = bits_delta_pl;
            po_table.header.least_content_length = least_pl;
            po_table.header.bits_content_length_delta = bits_delta_pl;
            // `per_page_byte_lengths.len() == page_hints.len() ==
            // po_table.entries.len()` is enforced by the length check at the
            // top of this block, so zip is bounds-check-free.
            for (entry, &bl) in po_table
                .entries
                .iter_mut()
                .zip(per_page_byte_lengths.iter())
            {
                let delta = bl.saturating_sub(least_pl);
                entry.page_length_minus_least = delta;
                entry.content_stream_length = delta;
            }
        }

        // Shared object table fields.
        //
        // The shared hint table covers all plan.shared_hints entries (part2
        // entries first, then part3 entries).  Per qpdf's checkHSharedObject,
        // the table starts at the first-page section's first object (part2[0] =
        // page dict), so we use shared_hints[0] for the location field.
        if !plan.shared_hints.is_empty() {
            // Collect byte lengths for all shared hint entries in plan order.
            //
            // Resolve renumber + probe-pass byte-length lookups strictly:
            // a missing entry indicates a planner / renumber inconsistency or
            // a probe-pass coverage bug, both of which would silently produce
            // a hint table with `least_length = 0` / `header.location = 0` if
            // we substituted zeros.  Bubble Err so the writer fails loudly
            // and the caller can surface the broken plan.
            let shared_section_lens: Vec<u64> = plan
                .shared_hints
                .iter()
                .map(|h| -> Result<u64> {
                    // Shared objects packed into an ObjStm have no standalone
                    // bytes — they are serialised inside their container.  We
                    // attribute 0 to such members here: it is a known
                    // approximation of the Annex F.4 shared-object length
                    // field, which qpdf validates leniently (the contained
                    // objects are still reachable via the type-2 xref and the
                    // container's own bytes are accounted for in the page
                    // section length).  The strict missing-entry error is
                    // still raised for *non-member* objects, where an absent
                    // probe length really does signal a planner / renumber
                    // or probe-coverage bug.
                    if objstm_layout
                        .member_to_container
                        .contains_key(&h.object_ref)
                    {
                        return Ok(0);
                    }
                    let new_ref = renumber.new_for_original(h.object_ref).ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "shared hint object {} has no renumber entry",
                            h.object_ref
                        ))
                    })?;
                    let len = byte_lengths.get(&new_ref.number).copied().ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "shared hint object {} (new #{}) has no probed byte length",
                            h.object_ref, new_ref.number
                        ))
                    })?;
                    Ok(len as u64)
                })
                .collect::<Result<Vec<_>>>()?;

            let least = shared_section_lens.iter().copied().min().unwrap_or(0);
            let max = shared_section_lens.iter().copied().max().unwrap_or(0);
            so_table.header.least_length = least;
            so_table.header.bits_length_delta = bits_needed(max.saturating_sub(least));

            // Location (item 2): "virtual" byte offset of the first Part-8
            // shared object, WITHOUT the hint stream object bytes.
            //
            // Per qpdf's checkHSharedObject (QPDF_linearization.cc lines 782-788),
            // the stored value `so.first_shared_offset` is fed through
            // `adjusted_offset(x)` which adds `H_length` (= /H[1] = full hint
            // stream object byte length) to any offset that is >= H_offset.
            // The resulting value is compared to the actual file offset.
            //
            // Since all offsets in our probe-pass xref_offsets ALREADY include
            // the hint stream object (it is written inline in do_write_pass),
            // we must subtract `hint_stream_obj_total_len` from the probe
            // offset so that `adjusted_offset(location) == actual_offset`.
            //
            //   adjusted_offset(location)
            //     = location + H_length             (since location >= H_offset)
            //     = (actual - H_length) + H_length
            //     = actual                           ✓
            //
            // This is only meaningful when nshared_total > nshared_first_page
            // (i.e., there are Part-8 objects).  When part4_other_pages_shared
            // is empty the location value is ignored (qpdf Implementation Note 131).
            if !plan.part4_other_pages_shared.is_empty() {
                let first_part8_orig = plan.part4_other_pages_shared[0];
                // When the first Part-8 shared object is packed into an
                // ObjStm it has no standalone offset; its physical location
                // is the container object that holds it (qpdf's
                // adjusted_offset() math works the same on the container's
                // offset — readers seek to the container, then the ObjStm
                // /First + pair table locates the member).
                let first_part8_lookup_num = if let Some(&(container_num, _idx)) =
                    objstm_layout.member_to_container.get(&first_part8_orig)
                {
                    container_num
                } else {
                    renumber
                        .new_for_original(first_part8_orig)
                        .ok_or_else(|| {
                            crate::Error::Unsupported(format!(
                                "first Part-8 shared object {} has no renumber entry",
                                first_part8_orig
                            ))
                        })?
                        .number
                };
                let first_part8_off = xref_offsets
                    .get(&first_part8_lookup_num)
                    .copied()
                    .ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "first Part-8 shared object (lookup #{}) has no probed offset",
                            first_part8_lookup_num
                        ))
                    })?;
                // Subtract hint stream total length so that qpdf's
                // adjusted_offset() reconstructs the correct file offset.
                so_table.header.location = first_part8_off
                    .checked_sub(hint_stream_obj_total_len)
                    .ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "linearization layout mismatch: first Part-8 shared object offset \
                             ({first_part8_off}) is less than hint stream length \
                             ({hint_stream_obj_total_len}); cannot compute shared-hint location"
                        ))
                    })? as u64;

                // first_object_number (item 1): object number of the first Part-8
                // shared object.  When that object is packed into an ObjStm we use
                // the *container's* new object number (already resolved above as
                // `first_part8_lookup_num`), because the xref points readers to the
                // container — not to a standalone object.
                //
                // `from_plan` computes this from `renumber.new_for_original`, which
                // returns the member's own renumber slot — incorrect when the member
                // lives inside an ObjStm container.  We patch it here alongside the
                // `location` field so both fields agree on which object number to
                // announce as the first Part-8 entry.
                so_table.header.first_object_number = first_part8_lookup_num;
            }

            // Per-object length_minus_least.  group_offset is no longer a
            // per-entry field (see hint_stream::encode_shared_object_entries:
            // it does not match Annex F.4.5 / qpdf's HSharedObjectEntry layout
            // and was previously emitting an extra 32 bits per entry that
            // qpdf misinterpreted as the next entry's length delta).
            // `nobjects_minus_one` stays at 0 from `from_plan`.
            for (i, _hint) in plan.shared_hints.iter().enumerate() {
                if i < so_table.objects.len() {
                    so_table.objects[i].length_minus_least =
                        (shared_section_lens[i].saturating_sub(least)) as u32;
                }
            }
        }

        // Re-encode hint stream with patched tables.
        let new_hint_bytes = encode_hint_stream(&po_table, &so_table)?;
        let new_compressed = new_hint_bytes.compressed;
        let new_shared_s = new_hint_bytes.shared_section_offset_in_uncompressed;

        // Save this pass's structural metadata (offsets, byte length).  The
        // bytes themselves are *not* yet final — they were written using the
        // previous iteration's hint stream.  We always do one more pass
        // below with the freshly-patched stream so the saved bytes contain
        // it; this is required even when the encoded length is identical
        // (the bit content still changes per-iteration).
        final_xref_offsets = xref_offsets.clone();
        final_hint_stream_offset = hint_stream_offset;
        final_hint_stream_obj_total_len = hint_stream_obj_total_len;
        final_end_of_first_page_offset = end_of_first_page_offset;
        final_last_xref_keyword_offset = last_xref_offset;
        final_last_xref_first_entry_offset = last_xref_first_entry_offset;
        final_bytes = bytes; // overwritten below if we do a final pass

        let converged = new_compressed.len() == current_hint_compressed.len();

        // Promote the freshly-patched stream as the next iteration input.
        current_hint_compressed = new_compressed;
        current_hint_shared_s = new_shared_s;

        // Risk 1 (convergence): the ObjStm container FlateDecode lengths are
        // *stable* across iterations (the contained, renumbered objects do
        // not change and the container numbers are pre-allocated), so only
        // the hint stream's own compressed length can still oscillate — the
        // same single degree of freedom the non-ObjStm path already had.  If
        // it has not stabilised by the final iteration we must not silently
        // emit a file whose Page-Offset Hint Table was computed against a
        // different layout: fail loudly instead of looping forever or
        // shipping a subtly wrong hint table.
        if !converged && iter == max_iters - 1 {
            return Err(crate::Error::Unsupported(format!(
                "linearization writer: hint stream length did not converge \
                 within {max_iters} iterations (ObjStm-bearing layout = {}); \
                 refusing to emit a file with an inconsistent Page Offset \
                 Hint Table",
                !objstm_layout.is_empty()
            )));
        }

        if converged || iter == max_iters - 1 {
            // One last pass so the emitted hint stream object actually
            // contains the patched bit-stream (not the previous iteration's).
            let (
                bytes_final,
                xref_offsets_final,
                hint_off_final,
                hint_len_final,
                efp_final,
                lxr_final,
                lxr_first_final,
                prev_range_final,
            ) = do_write_pass(
                plan,
                renumber,
                pdf,
                &part1,
                catalog_new_ref,
                hint_stream_new_num,
                total_count,
                info_new_ref,
                first_page_object_new_num,
                &current_hint_compressed,
                current_hint_shared_s,
                &source_trailer,
                &objstm_layout,
                &relocation,
            )?;
            final_bytes = bytes_final;
            final_xref_offsets = xref_offsets_final;
            final_hint_stream_offset = hint_off_final;
            final_hint_stream_obj_total_len = hint_len_final;
            final_end_of_first_page_offset = efp_final;
            final_last_xref_keyword_offset = lxr_final;
            final_last_xref_first_entry_offset = lxr_first_final;
            final_first_trailer_prev_range = prev_range_final;
            break;
        }
    }

    // ------------------------------------------------------------------
    // Assemble offsets
    // ------------------------------------------------------------------
    let file_length = final_bytes.len();
    let page_count = plan.page_hints.len() as u32;

    let offsets = LinearizedOffsets {
        file_length,
        hint_stream_offset: final_hint_stream_offset,
        hint_stream_length: final_hint_stream_obj_total_len,
        first_page_object_new_num,
        end_of_first_page_offset: final_end_of_first_page_offset,
        last_xref_keyword_offset: final_last_xref_keyword_offset,
        // /T = first_entry_pos - 1, matching qpdf's convention.
        // qpdf's check validates: file_T == first_entry_pos - 1.
        last_xref_offset: final_last_xref_first_entry_offset.saturating_sub(1),
        page_count,
        part1_placeholders,
        xref_offsets: final_xref_offsets,
        first_trailer_prev_range: final_first_trailer_prev_range,
        dict_writable_region: part1_dict_region,
    };

    Ok(LinearizedDocument {
        bytes: final_bytes,
        offsets,
    })
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::linearization::plan::LinearizationPlan;
    use crate::writer::WriteOptions;
    use crate::Pdf;
    use std::io::Cursor;

    // -----------------------------------------------------------------------
    // Fixture: minimal single-page PDF
    //
    // Object layout:
    //   1 0 obj – Catalog  (/Root)
    //   2 0 obj – Pages node
    //   3 0 obj – Page dict (Kids[0])
    // -----------------------------------------------------------------------
    fn tiny_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

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

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

    fn build_linearized() -> LinearizedDocument {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf).expect("plan");
        let renumber = RenumberMap::from_plan(&plan);
        let mut pdf2 = open_tiny_pdf();
        write_linearized(&plan, &renumber, &mut pdf2, &WriteOptions::default())
            .expect("write_linearized")
    }

    // -----------------------------------------------------------------------
    // 1. write_linearized succeeds on a valid fixture
    // -----------------------------------------------------------------------
    #[test]
    fn write_linearized_succeeds() {
        let _doc = build_linearized();
    }

    // -----------------------------------------------------------------------
    // 2. Output starts with %PDF-
    // -----------------------------------------------------------------------
    #[test]
    fn output_starts_with_pdf_header() {
        let doc = build_linearized();
        assert!(
            doc.bytes.starts_with(b"%PDF-"),
            "linearized output must start with %PDF-"
        );
    }

    // -----------------------------------------------------------------------
    // 3. Output contains /Linearized 1
    // -----------------------------------------------------------------------
    #[test]
    fn output_contains_linearized_marker() {
        let doc = build_linearized();
        let needle = b"/Linearized 1";
        assert!(
            doc.bytes.windows(needle.len()).any(|w| w == needle),
            "output must contain '/Linearized 1'"
        );
    }

    // -----------------------------------------------------------------------
    // 4. Output contains xref at least twice (Part 1 xref + Part 6 xref)
    // -----------------------------------------------------------------------
    #[test]
    fn output_contains_xref_twice() {
        let doc = build_linearized();
        let needle = b"xref";
        let count = doc
            .bytes
            .windows(needle.len())
            .filter(|w| *w == needle)
            .count();
        assert!(
            count >= 2,
            "linearized PDF must have at least 2 xref sections, found {count}"
        );
    }

    // -----------------------------------------------------------------------
    // 5. file_length matches bytes.len()
    // -----------------------------------------------------------------------
    #[test]
    fn file_length_matches_bytes_len() {
        let doc = build_linearized();
        assert_eq!(
            doc.offsets.file_length,
            doc.bytes.len(),
            "file_length must equal bytes.len()"
        );
    }

    // -----------------------------------------------------------------------
    // 6. hint_stream_offset is after Part 1 bytes
    // -----------------------------------------------------------------------
    #[test]
    fn hint_stream_offset_after_part1() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf).expect("plan");
        let renumber = RenumberMap::from_plan(&plan);
        let part1_len = Part1Bytes::build(&plan, &renumber, "1.4").byte_length();

        let mut pdf2 = open_tiny_pdf();
        let doc =
            write_linearized(&plan, &renumber, &mut pdf2, &WriteOptions::default()).expect("write");

        assert!(
            doc.offsets.hint_stream_offset >= part1_len,
            "hint stream must come after Part 1 (Part 1 len={part1_len}, hint offset={})",
            doc.offsets.hint_stream_offset
        );
    }

    // -----------------------------------------------------------------------
    // 7. end_of_first_page_offset > hint_stream_offset
    // -----------------------------------------------------------------------
    #[test]
    fn end_of_first_page_after_hint_stream() {
        let doc = build_linearized();
        assert!(
            doc.offsets.end_of_first_page_offset > doc.offsets.hint_stream_offset,
            "/E must be after the hint stream"
        );
    }

    // -----------------------------------------------------------------------
    // 8. last_xref_offset is after all body objects
    // -----------------------------------------------------------------------
    #[test]
    fn last_xref_offset_after_body() {
        let doc = build_linearized();
        assert!(
            doc.offsets.last_xref_offset > doc.offsets.end_of_first_page_offset,
            "/T (last xref) must be after the first-page section"
        );
        assert!(
            doc.offsets.last_xref_offset < doc.offsets.file_length,
            "/T must be within the file"
        );
    }

    // -----------------------------------------------------------------------
    // 9. page_count matches the fixture (1 page)
    // -----------------------------------------------------------------------
    #[test]
    fn page_count_is_one() {
        let doc = build_linearized();
        assert_eq!(
            doc.offsets.page_count, 1,
            "single-page fixture must report page_count = 1"
        );
    }

    // -----------------------------------------------------------------------
    // 10. xref_offsets[param_dict_obj_number] equals byte 15 (after the two
    //     header lines: %PDF-1.7 + binary marker).
    // -----------------------------------------------------------------------
    #[test]
    fn xref_offsets_param_dict_is_at_byte_fifteen() {
        let doc = build_linearized();
        // Whatever number the renumber map assigned the param dict, its
        // xref offset is the position of the `N 0 obj` token immediately
        // after the file header.
        let param_dict_off = doc
            .offsets
            .xref_offsets
            .values()
            .copied()
            .min()
            .unwrap_or(usize::MAX);
        assert_eq!(
            param_dict_off, 15,
            "the param dict (first object physically) must start at byte 15 \
             (after %PDF-1.x and the binary marker)"
        );
    }

    // -----------------------------------------------------------------------
    // 11. xref_offsets contains hint stream entry
    // -----------------------------------------------------------------------
    #[test]
    fn xref_offsets_contains_hint_stream() {
        let doc = build_linearized();
        let hint_num = doc.offsets.xref_offsets.keys().copied().max().unwrap_or(0);
        // hint stream has the highest new object number
        assert!(
            hint_num >= 2,
            "hint stream new number must be at least 2, got {hint_num}"
        );
        assert!(
            doc.offsets.xref_offsets.contains_key(&hint_num),
            "xref_offsets must contain hint stream entry"
        );
    }

    // -----------------------------------------------------------------------
    // 12. part1_placeholders are valid (width=10, disjoint)
    // -----------------------------------------------------------------------
    #[test]
    fn part1_placeholders_valid() {
        let doc = build_linearized();
        assert!(
            doc.offsets.part1_placeholders.all_valid(),
            "part1_placeholders must all be width-10 and disjoint"
        );
    }

    // -----------------------------------------------------------------------
    // 13. Bytes at xref_offsets[N] start with "<N> 0 obj"
    // -----------------------------------------------------------------------
    #[test]
    fn xref_offsets_point_to_obj_headers() {
        let doc = build_linearized();
        for (num, &offset) in &doc.offsets.xref_offsets {
            let expected = format!("{num} 0 obj");
            let window = &doc.bytes[offset..offset + expected.len()];
            assert_eq!(
                window,
                expected.as_bytes(),
                "offset for object {num} does not point to '{expected}'"
            );
        }
    }

    // -----------------------------------------------------------------------
    // 14. Part 1 (first trailer) startxref value must be 0 (qpdf linearized
    //     PDF convention, ISO 32000-1 Annex F).  The Part 6 (main) startxref
    //     at the end of the file must be the real xref keyword offset.
    //
    //     qpdf always emits `startxref\n0\n%%EOF` in the first trailer to
    //     signal "linearized first trailer".  The main xref at the file tail
    //     carries the actual byte offset for readers that seek to the end.
    // -----------------------------------------------------------------------
    #[test]
    fn part1_startxref_is_zero_and_main_startxref_is_real_offset() {
        let doc = build_linearized();
        let bytes = &doc.bytes;

        // Helper: parse the decimal value immediately after "startxref\n".
        let parse_startxref_value = |pos: usize| -> usize {
            let needle = b"startxref\n";
            let value_start = pos + needle.len();
            let value_end = bytes[value_start..]
                .iter()
                .position(|&b| b == b'\n')
                .map(|p| value_start + p)
                .expect("startxref value must be terminated by newline");
            let s = std::str::from_utf8(&bytes[value_start..value_end])
                .expect("startxref value is UTF-8");
            s.trim().parse().expect("startxref value must be decimal")
        };

        let needle = b"startxref\n";

        // Find first startxref (Part 1 first trailer).
        let first_sxref_pos = bytes
            .windows(needle.len())
            .position(|w| w == needle)
            .expect("linearized output must contain at least one startxref");
        let part1_value: usize = parse_startxref_value(first_sxref_pos);

        assert_eq!(
            part1_value, 0,
            "Part 1 first trailer startxref must be 0 (qpdf linearized convention), \
             got {part1_value}"
        );

        // Find last startxref (Part 6 main trailer).
        let last_sxref_pos = bytes
            .windows(needle.len())
            .rposition(|w| w == needle)
            .expect("linearized output must contain at least two startxref");
        let main_value: usize = parse_startxref_value(last_sxref_pos);

        // The main startxref must point to the last standalone `xref` keyword
        // token (not the `xref` that appears inside `startxref`).
        // A standalone `xref` is preceded by whitespace or the start of the
        // buffer, and followed by whitespace or the end of the buffer.
        let last_xref_pos = (0..bytes.len().saturating_sub(3))
            .rev()
            .find(|&i| {
                &bytes[i..i + 4] == b"xref"
                    && (i == 0 || bytes[i - 1].is_ascii_whitespace())
                    && (i + 4 >= bytes.len() || bytes[i + 4].is_ascii_whitespace())
            })
            .expect("linearized output must contain at least one standalone xref keyword");

        assert_eq!(
            main_value, last_xref_pos,
            "Part 6 main startxref ({main_value}) must equal the last xref keyword \
             offset ({last_xref_pos})"
        );
    }

    // -----------------------------------------------------------------------
    // 15. HIGH fix: Pdf::open can re-parse the linearized output (regression).
    //
    //     Although the main xref at Part 6 is what most parsers use, this
    //     confirms the overall file structure is well-formed enough to round-trip.
    // -----------------------------------------------------------------------
    #[test]
    fn linearized_output_is_parseable() {
        let doc = build_linearized();
        Pdf::open(Cursor::new(doc.bytes))
            .expect("linearized output must be parseable by Pdf::open");
    }

    // -----------------------------------------------------------------------
    // 16. MEDIUM fix: first_page_object_new_num is derived from renumber map,
    //     not hardcoded to 2.
    //
    //     For the single-page fixture (page 0 → obj 3 0 R), RenumberMap assigns
    //     new number 2 to that page ref (first Part-2 object).  The derived value
    //     must match the xref_offsets entry for that new number.
    // -----------------------------------------------------------------------
    #[test]
    fn first_page_object_new_num_matches_xref_offsets() {
        let doc = build_linearized();
        let num = doc.offsets.first_page_object_new_num;
        // The new number must appear in xref_offsets.
        assert!(
            doc.offsets.xref_offsets.contains_key(&num),
            "first_page_object_new_num ({num}) must be present in xref_offsets"
        );
        // Bytes at that offset must start with "<num> 0 obj".
        let offset = doc.offsets.xref_offsets[&num];
        let expected = format!("{num} 0 obj");
        let window = &doc.bytes[offset..offset + expected.len()];
        assert_eq!(
            window,
            expected.as_bytes(),
            "offset for first_page_object_new_num ({num}) must point to '{expected}'"
        );
    }

    // -----------------------------------------------------------------------
    // 17. MEDIUM fix: first_page_object_new_num equals renumber.new_for_original
    //     applied to page_hints[0].page_ref.
    //
    //     Verifies that the derive logic is consistent with the renumber map
    //     even when the page object is not trivially the first part2 object.
    // -----------------------------------------------------------------------
    #[test]
    fn first_page_object_new_num_equals_renumber_of_page_ref() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf).expect("plan");
        let renumber = RenumberMap::from_plan(&plan);

        let expected_num = renumber
            .new_for_original(plan.page_hints[0].page_ref)
            .expect("page_hints[0].page_ref must have a renumber entry")
            .number;

        let mut pdf2 = open_tiny_pdf();
        let doc = write_linearized(&plan, &renumber, &mut pdf2, &WriteOptions::default())
            .expect("write_linearized");

        assert_eq!(
            doc.offsets.first_page_object_new_num,
            expected_num,
            "first_page_object_new_num must equal renumber.new_for_original(page_hints[0].page_ref)"
        );
    }

    // -----------------------------------------------------------------------
    // compute_byte_lengths excludes the param dict by its actual slot
    // -----------------------------------------------------------------------
    //
    // The param dict sits before the hint stream and is not part of the
    // body length budget. With the qpdf-aligned slot allocation the param
    // dict number is dynamic, so the exclusion must be driven by the
    // renumber map rather than the literal `1`.
    #[test]
    fn compute_byte_lengths_uses_dynamic_param_dict_slot() {
        let mut offs: BTreeMap<u32, usize> = BTreeMap::new();
        // Layout: obj 1 lives in the body at offset 100 (e.g. a promoted
        // Pages tree), obj 3 is the param dict at offset 10, obj 5 is the
        // hint stream at offset 50, obj 6 starts the first-page body at 200.
        offs.insert(1, 100);
        offs.insert(3, 10);
        offs.insert(5, 50);
        offs.insert(6, 200);

        let lengths = compute_byte_lengths(&offs, 400, 5, 3);

        // Obj 3 (the real param dict) is excluded.
        assert!(!lengths.contains_key(&3));
        // Obj 1 is NOT excluded any more — it is a regular body object.
        // Its length runs to the next object's offset (obj 6 at 200).
        assert_eq!(lengths.get(&1).copied(), Some(100));
        // Obj 6 runs from offset 200 to last_xref_offset 400.
        assert_eq!(lengths.get(&6).copied(), Some(200));
    }
}