texrs 0.6.8

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

use std::collections::BTreeMap;
use std::fmt::Write as _;

/// A PDF dictionary, in the order its keys were PUT IN.
///
/// §7.3.7 says a dictionary's entries are unordered, so a reader does not care
/// -- but two WRITERS that order them differently produce different bytes for
/// the same dictionary, and that is a difference in every object of every file.
/// This was a `BTreeMap`, which sorts: measured on `Hello world.`, LuaTeX writes
/// `<< /Type /Page /Contents 3 0 R /Resources 1 0 R /MediaBox [ 0 0 612 792 ]
/// /Parent 5 0 R >>` and texrs wrote `<< /Contents 2 0 R /MediaBox [ 0 0 612
/// 792 ] /Parent 1 0 R /Resources << ... >> /Type /Page >>`. The two say the
/// same thing and share no run of bytes, so the parity ladder's BYTES rung
/// could never be reached however close the drawing came.
///
/// A dictionary is a handful of entries -- the largest one here is a font's
/// nine -- so a lookup is a scan and there is no index to keep.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Dict(Vec<(String, Object)>);

impl Dict {
    pub fn new() -> Dict {
        Dict(Vec::new())
    }

    /// Put `value` under `key`, keeping the place a key already there was put
    /// in. Replacing in place rather than moving the entry to the end is what
    /// makes a dictionary built by several `insert` calls independent of
    /// whether one of them overwrote an earlier one.
    pub fn insert(&mut self, key: impl Into<String>, value: Object) {
        let key = key.into();
        match self.0.iter_mut().find(|(seen, _)| *seen == key) {
            Some((_, slot)) => *slot = value,
            None => self.0.push((key, value)),
        }
    }

    pub fn get(&self, key: &str) -> Option<&Object> {
        self.0
            .iter()
            .find(|(seen, _)| seen == key)
            .map(|(_, value)| value)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &Object)> {
        self.0.iter().map(|(key, value)| (key, value))
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl<K: Into<String>, const N: usize> From<[(K, Object); N]> for Dict {
    fn from(pairs: [(K, Object); N]) -> Dict {
        let mut dict = Dict::new();
        for (key, value) in pairs {
            dict.insert(key, value);
        }
        dict
    }
}

impl<K: Into<String>> FromIterator<(K, Object)> for Dict {
    fn from_iter<I: IntoIterator<Item = (K, Object)>>(pairs: I) -> Dict {
        let mut dict = Dict::new();
        for (key, value) in pairs {
            dict.insert(key, value);
        }
        dict
    }
}

/// One PDF object.
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
    Null,
    Boolean(bool),
    /// PDF has one number type in the file, written with or without a point.
    Integer(i64),
    Real(f64),
    /// PDF source written through verbatim, for a dictionary a caller has
    /// already spelled. `tikz`'s shadings are built this way: a shading is a
    /// dictionary of a dictionary of functions, and the caller that knows the
    /// ramp is the one that can write it.
    Raw(String),
    /// A string, written in parentheses with what must be escaped escaped.
    Str(String),
    /// A string written as hexadecimal between angle brackets, which is what
    /// the trailer's `/ID` is: two byte strings that are not text.
    Hex(Vec<u8>),
    /// `/Name`.
    Name(String),
    Array(Vec<Object>),
    Dict(Dict),
    /// A dictionary with bytes after it. `Length` is filled in by the writer,
    /// because it is the length of what was written and not of what was meant.
    Stream {
        dict: Dict,
        data: Vec<u8>,
    },
    /// `12 0 R`: a reference to an object written elsewhere in the file.
    Reference(u32),
}

impl Object {
    /// A dictionary from pairs, which is most of what building a PDF is.
    pub fn dict(pairs: impl IntoIterator<Item = (&'static str, Object)>) -> Object {
        Object::Dict(
            pairs
                .into_iter()
                .map(|(key, value)| (key.to_string(), value))
                .collect(),
        )
    }

    pub fn name(text: &str) -> Object {
        Object::Name(text.to_string())
    }

    pub fn string(text: &str) -> Object {
        Object::Str(text.to_string())
    }

    /// Write this object into `out`, as the writers in `crate::pdfdoc` spell
    /// a packed object's body.
    pub(crate) fn write_into(&self, out: &mut Vec<u8>) {
        self.write(out)
    }

    /// Write this object into `out`.
    fn write(&self, out: &mut Vec<u8>) {
        match self {
            Object::Null => out.extend(b"null"),
            Object::Boolean(true) => out.extend(b"true"),
            Object::Boolean(false) => out.extend(b"false"),
            Object::Integer(value) => out.extend(value.to_string().as_bytes()),
            Object::Real(value) => {
                // PDF has no exponent notation, and a reader is entitled to
                // refuse `1e-7`. Six places is what xdvipdfmx writes.
                let mut text = format!("{value:.6}");
                while text.contains('.') && (text.ends_with('0') || text.ends_with('.')) {
                    text.pop();
                }
                out.extend(
                    match text.is_empty() || text == "-0" {
                        true => "0".to_string(),
                        false => text,
                    }
                    .as_bytes(),
                )
            }
            Object::Str(text) => {
                out.push(b'(');
                for byte in text.bytes() {
                    // A parenthesis or a backslash inside a string has to be
                    // escaped or the string ends early.
                    match byte {
                        b'(' | b')' | b'\\' => {
                            out.push(b'\\');
                            out.push(byte);
                        }
                        b'\n' => out.extend(b"\\n"),
                        b'\r' => out.extend(b"\\r"),
                        b'\t' => out.extend(b"\\t"),
                        other => out.push(other),
                    }
                }
                out.push(b')');
            }
            Object::Raw(text) => out.extend(text.as_bytes()),
            Object::Hex(bytes) => {
                out.push(b'<');
                for byte in bytes {
                    out.extend(format!("{byte:02X}").as_bytes());
                }
                out.push(b'>');
            }
            Object::Name(text) => {
                out.push(b'/');
                for byte in text.bytes() {
                    // §7.3.5: a name carries its bytes as they are except for
                    // the delimiters, whitespace, `#` itself, and anything
                    // outside the graphic range, which go as `#` and two
                    // hexadecimal digits. Escaping more than that is not
                    // wrong for a reader, but it is not what the file should
                    // say: `@` is a graphic character and PGF names a
                    // graphics state `/pgf@CA0.5`, which this wrote as
                    // `/pgf#40CA0.5` -- measured against the same picture set
                    // by lualatex, whose content stream has the `@`.
                    const DELIMITERS: &[u8] = b"()<>[]{}/%#";
                    match byte.is_ascii_graphic() && !DELIMITERS.contains(&byte) {
                        true => out.push(byte),
                        false => out.extend(format!("#{byte:02X}").as_bytes()),
                    }
                }
            }
            Object::Array(items) => {
                // `[ a b c ]`, spaced the way LuaTeX spaces it and for the same
                // reason `write_dict` is: measured on `Hello world.`, LuaTeX
                // writes `/MediaBox [ 0 0 612 792 ]`, `/W [ 1 2 1 ]` and
                // `/Index [ 0 13 ]`. The spec asks only for whitespace between
                // the items (§7.3.6), so which whitespace is a writer's habit
                // -- and two habits are a difference in every array in the file
                // for a comparison that is about bytes.
                //
                // An empty array stays `[]`: LuaTeX writes no `[  ]`.
                out.push(b'[');
                for item in items {
                    out.push(b' ');
                    item.write(out);
                }
                if !items.is_empty() {
                    out.push(b' ');
                }
                out.push(b']');
            }
            Object::Dict(pairs) => write_dict(pairs, out),
            Object::Stream { dict, data } => {
                write_stream_head(dict, data.len(), out);
                out.extend(data);
                out.extend(b"\nendstream");
            }
            Object::Reference(number) => out.extend(format!("{number} 0 R").as_bytes()),
        }
    }
}

/// A stream's dictionary, with the `Length` of the data after it, and the
/// keyword its data follows.
fn write_stream_head(dict: &Dict, length: usize, out: &mut Vec<u8>) {
    let mut dict = dict.clone();
    // The length is what was written, so it is set here rather than trusted
    // from the caller.
    dict.insert("Length", Object::Integer(length as i64));
    write_dict(&dict, out);
    out.extend(b"\nstream\n");
}

fn write_dict(pairs: &Dict, out: &mut Vec<u8>) {
    // `<< /Key value >>`, spaced the way LuaTeX spaces it. The spec allows any
    // whitespace at all between the brackets and the first key, so this is a
    // writer's habit rather than a rule -- and two writers with different
    // habits produce different bytes for identical content, which is the
    // difference the parity ladder's BYTES rung would otherwise report forever.
    out.extend(b"<<");
    for (key, value) in pairs.iter() {
        out.push(b' ');
        Object::Name(key.clone()).write(out);
        out.push(b' ');
        value.write(out);
    }
    out.extend(b" >>");
}

/// Where an object ended up once the file was written.
#[derive(Clone, Copy)]
enum Where {
    /// At this byte offset in the file.
    File(usize),
    /// At this index inside the object stream.
    Packed(usize),
    /// A number `reserve` handed out that nothing was ever filled into. It
    /// still needs an entry: the table is indexed by object number, so a gap
    /// in it would move every object after the gap.
    Nowhere,
}

/// Deflate, which is how a PDF compresses anything that is not a picture.
fn deflate(data: &[u8]) -> Vec<u8> {
    use std::io::Write as _;
    let mut out = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
    out.write_all(data).expect("deflate into a vector");
    out.finish().expect("deflate into a vector")
}

/// A name for these bytes: the first sixteen of their SHA-256, which is what
/// goes in the trailer's `/ID`, from a digest that has
/// been fed them.
///
/// The spec suggests MD5 (§14.4) and MD5 is not in the tree; the digest's
/// algorithm is not part of the format -- what a reader does with an `/ID` is
/// compare it with another one -- and `sha2` is already a dependency for the
/// input digests in `io.rs`. Sixteen bytes because that is the length every
/// writer uses and the length a reader's field is sized for.
fn file_identifier(digest: sha2::Sha256) -> Vec<u8> {
    use sha2::Digest as _;
    digest.finalize()[..16].to_vec()
}

/// The moment a document is stamped with: `SOURCE_DATE_EPOCH` when the
/// environment sets it, and the wall clock otherwise.
///
/// A PDF carries the time it was written, so two runs of the same document
/// differ in the two dates and nothing else -- measured on LuaTeX, 60 bytes.
/// `SOURCE_DATE_EPOCH` (reproducible-builds.org's specification) is how every
/// engine that cares is told to use a fixed one instead, LuaTeX included, and
/// texrs honours it here for the same reason: it is what makes byte equality
/// with LuaTeX a question that can be asked at all.
pub(crate) fn stamp() -> i64 {
    std::env::var("SOURCE_DATE_EPOCH")
        .ok()
        .and_then(|text| text.trim().parse::<i64>().ok())
        .unwrap_or_else(|| {
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0)
        })
}

/// A Unix time as §7.9.4 spells a date.
///
/// "A date shall be a text string of the form `(D:YYYYMMDDHHmmSSOHH'mm)`",
/// where `O` is the relationship of local time to UT and may be `Z` for a
/// time that IS UT. This writes UT: the alternative is the local zone, which
/// is what LuaTeX writes -- `D:19691231190000-05'00'` for epoch zero on a
/// machine five hours west -- and which makes the same document build to
/// different bytes on two machines. A stamp that a reproducible build can rely
/// on is worth more here than one more matching key.
pub(crate) fn pdf_date(epoch: i64) -> String {
    let (days, seconds) = (epoch.div_euclid(86_400), epoch.rem_euclid(86_400));
    let (year, month, day) = civil_from_days(days);
    let (hour, minute, second) = (seconds / 3600, (seconds / 60) % 60, seconds % 60);
    format!("D:{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}Z")
}

/// The civil date `days` after 1970-01-01, by Howard Hinnant's algorithm.
///
/// The calendar is not a division: months are of four lengths and February is
/// of two. This is the standard closed form for it -- shift the era to start
/// in March so the leap day falls at the end of a year, count eras of 400
/// years, and undo the shift at the end.
/// [`civil_from_days`], for `crate::pdfdoc`'s identifier.
pub(crate) fn civil(days: i64) -> (i64, i64, i64) {
    civil_from_days(days)
}

fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let day_of_era = z - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let year = year_of_era + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * shifted + 2) / 5 + 1;
    let month = match shifted < 10 {
        true => shifted + 3,
        false => shifted - 9,
    };
    (year + i64::from(month <= 2), month, day)
}

/// How many bytes it takes to write `value`, at least one.
fn bytes_for(value: usize) -> usize {
    ((usize::BITS - value.leading_zeros()) as usize)
        .div_ceil(8)
        .max(1)
}

/// Append `value` as `width` bytes, most significant first, dropping anything
/// that does not fit -- which is what turns the free entry's 65535 into the
/// 255 LuaTeX writes when the field is one byte wide.
fn put(out: &mut Vec<u8>, value: usize, width: usize) {
    for shift in (0..width).rev() {
        out.push((value >> (shift * 8)) as u8);
    }
}

/// Inflate every deflated `stream ... endstream` in a PDF, leaving the rest.
///
/// PDF 1.5 puts a document's structure inside compressed object streams, so
/// anything that wants to READ what a file says -- how many pages it declares,
/// which fonts it carries, what a test asserts about a dictionary -- has to
/// come through here first. `pdf_parity` needs the same thing for LuaTeX's
/// output and calls this.
pub fn inflate_streams(pdf: &[u8]) -> Vec<u8> {
    use std::io::Read;
    let mut out = Vec::with_capacity(pdf.len());
    let mut i = 0;
    while i < pdf.len() {
        let Some(at) = find(&pdf[i..], b"stream").map(|a| i + a) else {
            out.extend_from_slice(&pdf[i..]);
            break;
        };
        let mut data = at + b"stream".len();
        if pdf.get(data) == Some(&b'\r') {
            data += 1;
        }
        if pdf.get(data) == Some(&b'\n') {
            data += 1;
        }
        let Some(end) = find(&pdf[data..], b"endstream").map(|e| data + e) else {
            out.extend_from_slice(&pdf[i..]);
            break;
        };
        out.extend_from_slice(&pdf[i..data]);
        let raw = &pdf[data..end];
        let mut plain = Vec::new();
        match flate2::read::ZlibDecoder::new(raw).read_to_end(&mut plain) {
            Ok(_) => out.extend_from_slice(&plain),
            // Not deflated, or deflated in a way this cannot read: the bytes as
            // they stand are what the engine wrote, and stand in for themselves.
            Err(_) => out.extend_from_slice(raw),
        }
        out.extend_from_slice(b"endstream");
        i = end + b"endstream".len();
    }
    out
}

fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
    hay.windows(needle.len()).position(|w| w == needle)
}

/// A PDF's objects as they would read if none of them had been packed.
///
/// `inflate_streams` is enough to FIND a key -- the packed bodies are in the
/// inflated data -- but not to read the file as a graph, because a packed
/// object has no `N 0 obj` header any more: it is a body at an offset named by
/// its object stream's own header. This puts the headers back, so a reader that
/// walks `N 0 obj ... endobj` and follows references between them sees the same
/// document a PDF reader does.
///
/// What comes out is not a valid PDF -- every offset in it is wrong and the
/// table still names the object stream that is no longer there. It is for
/// reading, and the tests that assert on what a document SAYS use it.
pub fn unpacked(pdf: &[u8]) -> Vec<u8> {
    let plain = inflate_streams(pdf);
    let mut out = Vec::with_capacity(plain.len());
    let mut i = 0;
    while i < plain.len() {
        let Some(key) = find(&plain[i..], b"/Type /ObjStm").map(|at| i + at) else {
            out.extend_from_slice(&plain[i..]);
            break;
        };
        // The object this key is in: back to its `N 0 obj` header, forward to
        // the data `inflate_streams` left between `stream` and `endstream`.
        let head = find_last(&plain[i..key], b" 0 obj").map(|at| i + at);
        let data = find(&plain[key..], b"stream\n").map(|at| key + at + 7);
        let (Some(head), Some(data)) = (head, data) else {
            out.extend_from_slice(&plain[i..]);
            break;
        };
        let Some(end) = find(&plain[data..], b"endstream").map(|at| data + at) else {
            out.extend_from_slice(&plain[i..]);
            break;
        };
        let start = find_last(&plain[i..head], b"\n")
            .map(|at| i + at + 1)
            .unwrap_or(head);
        out.extend_from_slice(&plain[i..start]);

        // `First` says where the pairs stop; the pairs say where each object
        // begins, measured from there.
        let dict = String::from_utf8_lossy(&plain[head..data]).into_owned();
        let first: usize = match number_after(&dict, "/First ") {
            Some(first) => first,
            None => {
                out.extend_from_slice(&plain[start..]);
                break;
            }
        };
        let body = &plain[data..end];
        let pairs: Vec<usize> = String::from_utf8_lossy(&body[..first.min(body.len())])
            .split_whitespace()
            .filter_map(|word| word.parse().ok())
            .collect();
        for (index, pair) in pairs.chunks(2).enumerate() {
            let [number, at] = pair else { continue };
            let from = first + at;
            let to = match pairs.get(index * 2 + 3) {
                Some(next) => first + next,
                None => body.len(),
            };
            if from > to || to > body.len() {
                continue;
            }
            out.extend(format!("{number} 0 obj\n").as_bytes());
            out.extend_from_slice(trim_end(&body[from..to]));
            out.extend(b"\nendobj\n");
        }
        // Past the object stream's own `endobj`, which is now redundant.
        i = match find(&plain[end..], b"endobj") {
            Some(at) => end + at + b"endobj".len(),
            None => plain.len(),
        };
    }
    out
}

fn find_last(hay: &[u8], needle: &[u8]) -> Option<usize> {
    hay.windows(needle.len()).rposition(|w| w == needle)
}

fn trim_end(body: &[u8]) -> &[u8] {
    let mut end = body.len();
    while end > 0 && body[end - 1].is_ascii_whitespace() {
        end -= 1;
    }
    &body[..end]
}

/// The number written straight after `key`, if there is one.
fn number_after(text: &str, key: &str) -> Option<usize> {
    text.split_once(key)?
        .1
        .chars()
        .take_while(char::is_ascii_digit)
        .collect::<String>()
        .parse()
        .ok()
}

/// A PDF being written.
pub struct Pdf {
    objects: Vec<Object>,
    /// What the trailer's `Root` points at.
    catalog: Option<u32>,
    /// The document information dictionary, when there is one (§14.3.3).
    info: Option<u32>,
}

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

impl Pdf {
    pub fn new() -> Pdf {
        Pdf {
            objects: Vec::new(),
            catalog: None,
            info: None,
        }
    }

    /// Take an object and hand back the reference to it. Objects are numbered
    /// from one, because zero is the head of the free list and always has been.
    pub fn add(&mut self, object: Object) -> Object {
        self.objects.push(object);
        Object::Reference(self.objects.len() as u32)
    }

    /// Reserve a number for an object not yet built -- a page has to name the
    /// page tree that has to list the page.
    pub fn reserve(&mut self) -> u32 {
        self.objects.push(Object::Null);
        self.objects.len() as u32
    }

    /// Fill in what `reserve` promised.
    pub fn fill(&mut self, number: u32, object: Object) {
        if let Some(slot) = self.objects.get_mut(number as usize - 1) {
            *slot = object;
        }
    }

    /// Say which object is the catalogue, which is where a reader starts.
    pub fn set_catalog(&mut self, number: u32) {
        self.catalog = Some(number);
    }

    /// Name the information dictionary the trailer points at.
    pub fn set_info(&mut self, number: u32) {
        self.info = Some(number);
    }

    /// Serialise the file, in the PDF 1.5 form LuaTeX writes.
    ///
    /// The cross-reference table is why this cannot be done a piece at a time:
    /// it says where every object is, so where each one landed has to be
    /// recorded while writing and the table written after everything else.
    ///
    /// Two structures rather than one, because §7.5.7 and §7.5.8 are one
    /// decision. The objects that MAY be packed -- everything that is not
    /// itself a stream -- go into a single `/Type /ObjStm` whose data is one
    /// deflated run, and the table that says where they are cannot then be a
    /// table of byte offsets, because they no longer have any: it becomes a
    /// `/Type /XRef` stream, whose entries say either "at this offset" or "at
    /// this index of that object stream". The trailer goes with the table, its
    /// keys moving into the stream's own dictionary.
    ///
    /// Measured on `Hello world.` through `luatex`: seven objects packed into
    /// one `/ObjStm`, three standing alone (two streams and the document
    /// information), and a `/Type /XRef /W [1 2 1]` object last. What is NOT
    /// reachable this way is LuaTeX's object NUMBERING -- 3, 9, 11, 6, 12 for
    /// that file, which is the order its own allocator handed numbers out in
    /// -- and that is why a document is written by `crate::pdfdoc` instead.
    pub fn finish(&self) -> Vec<u8> {
        let mut out = Vec::new();
        // §7.5.2: the header, and a comment of high bytes that tells anything
        // moving the file about that it is binary and must not be translated.
        // The spec asks only for four bytes over 127; WHICH four is the
        // writer's own. These are LuaTeX's, so that a document both engines set
        // the same way is the same file here too rather than differing in its
        // second line -- the parity ladder's BYTES rung compares what was drawn,
        // and a header comment is not a difference in drawing.
        out.extend(b"%PDF-1.7\n");
        out.extend([
            b'%', 0xcc, 0xd5, 0xc1, 0xd4, 0xc5, 0xd8, 0xd0, 0xc4, 0xc6, b'\n',
        ]);

        // §7.5.7: a stream may not be packed. A reader finds a stream's data
        // by the `Length` in its dictionary and then reads that many bytes of
        // the FILE, and there are no such bytes for an object that lives
        // inside somebody else's compressed data.
        let packable: Vec<bool> = self
            .objects
            .iter()
            .map(|object| !matches!(object, Object::Stream { .. }))
            .collect();
        let objects = self.objects.len() as u32;
        let objstm = packable.iter().any(|&yes| yes).then_some(objects + 1);
        let table_number = objstm.unwrap_or(objects) + 1;

        // Each stream as the file holds it: what comes before its data, the
        // data, and what comes after. The data is most of the file -- every
        // page's content, every font program -- so it is read where it lies,
        // once to be copied into the file and once to be digested, and those
        // two reads run side by side.
        const STREAM_TAIL: &[u8] = b"\nendstream\nendobj\n";
        let streams: Vec<(usize, Vec<u8>, &[u8])> = self
            .objects
            .iter()
            .enumerate()
            .filter_map(|(i, object)| match object {
                Object::Stream { dict, data } => {
                    let mut head = format!("{} 0 obj\n", i + 1).into_bytes();
                    write_stream_head(dict, data.len(), &mut head);
                    Some((i, head, data.as_slice()))
                }
                _ => None,
            })
            .collect();

        // Where each object ends up, which is what the table has to say: a
        // stream at the offset the ones before it reach, anything else at its
        // index in the object stream.
        let mut located: Vec<Where> = vec![Where::Nowhere; self.objects.len()];
        let mut at = out.len();
        for (i, head, data) in &streams {
            located[*i] = Where::File(at);
            at += head.len() + data.len() + STREAM_TAIL.len();
        }
        let mut in_objstm = 0usize;
        for (i, place) in located.iter_mut().enumerate() {
            if packable[i] {
                *place = Where::Packed(in_objstm);
                in_objstm += 1;
            }
        }

        // The object stream: `N` pairs of object number and offset, then the
        // objects themselves, one after another. `First` is where the pairs
        // stop -- the offsets are measured from there and not from the start
        // of the data, so a reader adds the two.
        let pack = || -> Vec<u8> {
            let Some(number) = objstm else {
                return Vec::new();
            };
            let mut head = String::new();
            let mut body = Vec::new();
            for (i, object) in self.objects.iter().enumerate() {
                if !packable[i] {
                    continue;
                }
                let space = match body.is_empty() {
                    true => "",
                    false => " ",
                };
                let _ = write!(head, "{space}{} {}", i + 1, body.len());
                object.write(&mut body);
                body.push(b'\n');
            }
            head.push('\n');
            let first = head.len();
            let mut data = head.into_bytes();
            data.append(&mut body);
            let mut written = format!("{number} 0 obj\n").into_bytes();
            Object::Stream {
                dict: Dict::from([
                    ("Type".to_string(), Object::name("ObjStm")),
                    ("N".to_string(), Object::Integer(in_objstm as i64)),
                    ("First".to_string(), Object::Integer(first as i64)),
                    ("Filter".to_string(), Object::name("FlateDecode")),
                ]),
                data: deflate(&data),
            }
            .write(&mut written);
            written.extend(b"\nendobj\n");
            written
        };

        // The identifier below digests everything written before the table:
        // the header, the streams and then the object stream, the same bytes
        // in the same order. The streams are digested while they are copied
        // into the file and while the object stream is packed and deflated.
        let mut digest = <sha2::Sha256 as sha2::Digest>::new();
        sha2::Digest::update(&mut digest, &out);
        let ((mut digest, ()), packed) = rayon::join(
            || {
                rayon::join(
                    || {
                        for (_, head, data) in &streams {
                            sha2::Digest::update(&mut digest, head);
                            sha2::Digest::update(&mut digest, data);
                            sha2::Digest::update(&mut digest, STREAM_TAIL);
                        }
                        digest
                    },
                    || {
                        out.reserve(at - out.len());
                        for (_, head, data) in &streams {
                            out.extend(head);
                            out.extend(*data);
                            out.extend(STREAM_TAIL);
                        }
                    },
                )
            },
            pack,
        );
        let objstm_offset = out.len();
        out.extend(&packed);
        sha2::Digest::update(&mut digest, &packed);

        // §7.5.8: the table, as one row an object of three fields -- what kind
        // of entry it is, and two fields meaning different things per kind.
        // Object zero heads the free list, as it does in a classic table.
        let mut rows: Vec<(u8, usize, usize)> = vec![(0, 0, 0xffff)];
        for place in &located {
            rows.push(match place {
                Where::File(offset) => (1, *offset, 0),
                Where::Packed(index) => (2, objstm.unwrap_or(0) as usize, *index),
                // Nothing reaches this today -- an unfilled `reserve` is a
                // `Null`, which packs like anything else. A free entry is what
                // an object number that is not in use is spelled as, and it is
                // the one answer here that cannot send a reader somewhere
                // wrong.
                Where::Nowhere => (0, 0, 0xffff),
            });
        }
        if objstm.is_some() {
            rows.push((1, objstm_offset, 0));
        }
        let table_offset = out.len();
        rows.push((1, table_offset, 0));

        // How wide each field has to be. The second holds a byte offset, so it
        // grows with the file -- LuaTeX's `[1 2 1]` is what a file under 64 kB
        // needs and a book needs more. The third is an index into an object
        // stream, and the free entry's 65535 is truncated to it rather than
        // widening it, which is what LuaTeX writes too.
        let widest = |field: fn(&(u8, usize, usize)) -> Option<usize>| {
            rows.iter().filter_map(field).max().unwrap_or(0)
        };
        let second = widest(|row| (row.0 != 0).then_some(row.1)).max(0xffff);
        let third = widest(|row| (row.0 == 2).then_some(row.2));
        let (second, third) = (bytes_for(second), bytes_for(third));
        let mut data = Vec::with_capacity(rows.len() * (1 + second + third));
        for (kind, one, two) in &rows {
            data.push(*kind);
            put(&mut data, *one, second);
            put(&mut data, *two, third);
        }

        // The trailer's keys, in the table's own dictionary: this IS the
        // trailer now, and `startxref` points at the object holding it.
        //
        // In LuaTeX's order, which is `/Type /Index /Size /W /Root /Info /ID
        // /Filter /Length` -- measured on `Hello world.` -- because the keys of
        // a dictionary go into the file in the order they were put in and two
        // orders are a difference in every byte of the object.
        let mut dict = Dict::from([
            ("Type".to_string(), Object::name("XRef")),
            (
                "Index".to_string(),
                Object::Array(vec![Object::Integer(0), Object::Integer(rows.len() as i64)]),
            ),
            ("Size".to_string(), Object::Integer(rows.len() as i64)),
            (
                "W".to_string(),
                Object::Array(vec![
                    Object::Integer(1),
                    Object::Integer(second as i64),
                    Object::Integer(third as i64),
                ]),
            ),
        ]);
        if let Some(catalog) = self.catalog {
            dict.insert("Root".to_string(), Object::Reference(catalog));
        }
        if let Some(info) = self.info {
            dict.insert("Info".to_string(), Object::Reference(info));
        }
        // §14.4: "The value of this entry shall be an array of two byte
        // strings. The first byte string shall be a permanent identifier based
        // on the contents of the file at the time it was originally created
        // ... When a file is first written, both identifiers shall be set to
        // the same value."
        //
        // The spec's own recipe is a digest of "the current time", the file's
        // pathname and its size, which is three ways of making the same
        // document twice give two different files. This digests the CONTENTS
        // instead -- everything written above this table -- so the identifier
        // is what the spec says it is, a name for these bytes, and a
        // reproducible build stays reproducible.
        let id = file_identifier(digest);
        dict.insert(
            "ID".to_string(),
            Object::Array(vec![Object::Hex(id.clone()), Object::Hex(id)]),
        );
        dict.insert("Filter".to_string(), Object::name("FlateDecode"));
        out.extend(format!("{table_number} 0 obj\n").as_bytes());
        Object::Stream {
            dict,
            data: deflate(&data),
        }
        .write(&mut out);
        out.extend(b"\nendobj\n");
        let mut tail = String::new();
        let _ = write!(tail, "startxref\n{table_offset}\n%%EOF\n");
        out.extend(tail.as_bytes());
        out
    }

    pub fn len(&self) -> usize {
        self.objects.len()
    }

    pub fn is_empty(&self) -> bool {
        self.objects.is_empty()
    }
}

/// Where a font's or a picture's objects go as they are built: the plain
/// [`Pdf`] model, or LuaTeX's layout in `crate::pdfdoc::Writer`.
pub(crate) trait Sink {
    fn add(&mut self, object: Object) -> Object;
}

impl Sink for Pdf {
    fn add(&mut self, object: Object) -> Object {
        Pdf::add(self, object)
    }
}

/// A TeX font as LuaTeX's backend embeds it: the metrics out of its `.tfm`,
/// which say what each code is and how wide, and the Type 1 program a map line
/// names for it (`pdftex.map`'s `cmr10 CMR10 <cmr10.pfb`).
///
/// The widths in the file and the descriptor's heights are the TFM's, as
/// `write_charwidth_array` and `preset_fontmetrics` take them; the bounding
/// box, the italic angle, the stem and the name are the program's, as
/// `writet1` reads them over the preset.
#[derive(Debug, Clone, PartialEq)]
pub struct TexFont {
    /// The TFM's name, which orders the font dictionaries (`fo_tree`).
    pub tfm_name: String,
    /// The program's file name, which orders the descriptors (`fd_tree`).
    pub program_file: String,
    pub program: crate::type1::Type1,
    /// The design size, in scaled points.
    pub size: i64,
    /// Each code's width at the design size, `None` where the TFM has no
    /// character.
    pub widths: Vec<Option<i64>>,
    /// `preset_fontmetrics`, in thousandths: the height of `h`, of `H`, the
    /// depth of `y` (negated), a third of the width of `.`, and the x-height.
    pub ascent: i64,
    pub cap_height: i64,
    pub descent: i64,
    pub stem_v: i64,
    pub x_height: i64,
}

impl TexFont {
    /// The TFM `tfm_name` and the program in `program_file`, both found by
    /// `kpsewhich`.
    pub fn open(tfm_name: &str, program_file: &str) -> Option<TexFont> {
        let tfm = crate::tfm::Tfm::open(crate::kpse::locate(&format!("{tfm_name}.tfm"))?).ok()?;
        let program = crate::type1::Type1::open(crate::type1::installed(program_file)?).ok()?;
        let (size, widths, [ascent, cap_height, descent, stem_v, x_height]) =
            crate::pdfdoc::tex_metrics(&tfm);
        Some(TexFont {
            tfm_name: tfm_name.to_string(),
            program_file: program_file.to_string(),
            program,
            size,
            widths,
            ascent,
            cap_height,
            descent,
            stem_v,
            x_height,
        })
    }

    /// The glyph code `code` draws: see `glyph_for_code`.
    pub fn glyph_for(&self, code: u8) -> Option<String> {
        glyph_for_code(&self.program, code)
    }

    /// Whether the program draws `code` as the TFM describes it -- the glyph
    /// its own encoding puts there -- rather than as a driver re-encoded it.
    fn tfm_speaks_for(&self, code: u8) -> bool {
        self.widths[usize::from(code)].is_some()
            && self.program.encoded(code).map(|g| &g.name) == self.glyph_for(code).as_ref()
    }

    /// Whether anything can be drawn at `code`.
    pub fn exists(&self, code: u8) -> bool {
        match self.tfm_speaks_for(code) {
            true => true,
            false => self
                .glyph_for(code)
                .is_some_and(|g| self.program.glyph(&g).is_some()),
        }
    }

    /// `pdf_char_width` at `cw.e` = 1: a code's width in ten-thousandths of
    /// the size, rounded -- printed with one decimal, `277.8`. A code a driver
    /// re-encoded is not the TFM's character, and has its glyph's own width.
    pub fn char_width_e1(&self, code: u8) -> i64 {
        if self.tfm_speaks_for(code) {
            let w = self.widths[usize::from(code)].unwrap_or(0);
            return (w as f64 / self.size as f64 * 10_000.0).round() as i64;
        }
        self.glyph_for(code)
            .and_then(|g| {
                self.program
                    .glyph(&g)
                    .map(|g| (g.width * 10.0).round() as i64)
            })
            .unwrap_or(0)
    }
}

/// Which glyph of a Type 1 program a driver's code asks for.
///
/// §9.3.3 gives word spacing to the single-byte code 32 and to nothing else,
/// and `Page::text_set` writes a `Tw` for it, so this driver has already told
/// every reader that 32 is the space. A TeX font's own encoding says otherwise
/// -- cmr10 puts `suppress`, the Polish suppressed-l, in that slot -- and
/// believing it draws a small stroke in the middle of every word gap on the
/// page: measured, `Hello world.` came out as `Hello`, a stroke, `world.`.
///
/// Past that the program's own encoding answers, and a code it leaves empty is
/// one the driver used in WinAnsi: `emdash` is at 124 in CMR10 and at 151 in
/// WinAnsi, so a page that drew an em dash asked CMR10 for code 151 and got an
/// unfilled slot. §9.6.6 is exactly this case: `/Differences` remaps a code to
/// a glyph by NAME, so the code the driver used is pointed at the glyph the
/// font calls it. The join is through what a glyph MEANS rather than what it is
/// called, because the two vocabularies do not agree by name either:
/// `agl::unicode` turns each of the font's glyph names into the characters it
/// draws, and the code's character comes from WinAnsi.
pub(crate) fn glyph_for_code(font: &crate::type1::Type1, code: u8) -> Option<String> {
    if code == b' ' {
        if let Some(glyph) = font.glyph("space") {
            return Some(glyph.name.clone());
        }
    }
    if let Some(glyph) = font.encoded(code) {
        return Some(glyph.name.clone());
    }
    let character = crate::typeset::winansi_unicode(code)?.to_string();
    font.glyph_names()
        .into_iter()
        .find(|name| crate::agl::unicode(name).as_deref() == Some(character.as_str()))
        .map(str::to_string)
}

/// A font a page sets text in.
#[derive(Debug, Clone, PartialEq)]
pub enum Font {
    /// One of the fourteen every reader has, named rather than embedded --
    /// which is what makes a file like that three kilobytes instead of three
    /// hundred.
    Base14(String),
    /// A Type 1 font carried in the file, so the document reads the same
    /// wherever it is opened. This is what a TeX document needs: nobody has
    /// Computer Modern installed.
    Embedded(Box<crate::type1::Type1>),
    /// A TeX font, written as LuaTeX's backend writes one: see [`TexFont`].
    Tex(Box<TexFont>),
    /// A TrueType or OpenType font carried in the file.
    ///
    /// What `\setmainfont{Arimo}` actually asks for. Naming one of the
    /// fourteen gets the right WIDTHS -- Arimo's are Arial's are Helvetica's --
    /// and the wrong shapes; this is the font itself, so the page is set in the
    /// face the document named.
    TrueType {
        /// The name the file calls it by.
        name: String,
        /// The whole font file, embedded as `FontFile2`.
        bytes: Vec<u8>,
        /// Advance widths for codes 32..=255, in 1/1000 em.
        widths: Vec<i64>,
        /// `[xMin, yMin, xMax, yMax]`, in the same units.
        bbox: [i64; 4],
        /// From `hhea`, for the descriptor a reader needs.
        ascent: i64,
        /// From `hhea`. Negative, the way the table stores it.
        descent: i64,
    },
    /// A face carried in the file and addressed by GLYPH rather than by code.
    ///
    /// This is what a per-glyph fallback needs and a simple font cannot give:
    /// `\setmainfont{Arimo}` embeds Arimo whole, WinAnsi addresses 224 of its
    /// glyphs, and no code in that encoding means U+2500. A face that HAS the
    /// box drawing is written here instead as a composite font -- `/Type0` with
    /// `/Identity-H`, where a code is two bytes and is the glyph id itself --
    /// so any glyph in the file can be drawn, whatever Unicode calls it.
    Glyphs {
        /// The name the file calls it by.
        name: String,
        /// The font program, embedded as `FontFile2` -- subsetted to the glyphs
        /// below, since a broad face is tens of megabytes and a document
        /// borrows a handful of glyphs from it.
        bytes: Vec<u8>,
        /// The glyphs the document actually asks this face for: the glyph id,
        /// the character it stands for, and its advance in 1/1000 em. Only
        /// these, because a broad face has fifty thousand glyphs and a `/W`
        /// array of all of them is a quarter of a megabyte of widths for a
        /// document that drew nine of them.
        glyphs: Vec<(u16, char, i64)>,
        /// `[xMin, yMin, xMax, yMax]`, in the same units.
        bbox: [i64; 4],
        /// From `hhea`, for the descriptor a reader needs.
        ascent: i64,
        /// From `hhea`. Negative, the way the table stores it.
        descent: i64,
    },
}

impl Font {
    /// What the font calls itself.
    pub fn name(&self) -> String {
        match self {
            Font::Base14(name) => name.clone(),
            Font::Embedded(font) => font.font_name.clone(),
            Font::Tex(font) => font.program.font_name.clone(),
            Font::TrueType { name, .. } | Font::Glyphs { name, .. } => name.clone(),
        }
    }

    /// Whether a code in this font is two bytes rather than one.
    ///
    /// PDF's word spacing (S9.3.3) applies to the single-byte code 32 and to
    /// nothing else, so a `Tw` written for a composite font is ignored by the
    /// reader while the driver goes on advancing by it. Nothing here sets a
    /// two-byte run to a width, and this is what says so.
    pub fn is_composite(&self) -> bool {
        matches!(self, Font::Glyphs { .. })
    }

    /// The face a document that named none is set in: Computer Modern Roman at
    /// ten point, embedded.
    ///
    /// This is what TeX means by "the font", and it is what luatex puts in the
    /// file -- measured, `pdffonts` reports a subsetted `CMR10` for every one of
    /// the ten corpus documents where texrs reported a base-14 `Helvetica`. The
    /// widths were already cmr10's, because `typeset::to_pdf` measures out of
    /// `cmr10.tfm` whenever the face carries no widths of its own, so this
    /// changes the shapes drawn and not where the lines break.
    ///
    /// `None` when `cmr10.pfb` is not installed, and the caller then names one
    /// of the fourteen instead: a document that cannot be set in Computer
    /// Modern is still better set than refused.
    pub fn computer_modern() -> Option<Font> {
        // Read once. The file is a quarter of a megabyte and `Type1::parse`
        // decrypts every charstring in it; a book of a hundred pages asks for
        // the face once per `to_pdf` call and there is no reason to pay twice.
        static FACE: std::sync::OnceLock<Option<Font>> = std::sync::OnceLock::new();
        FACE.get_or_init(|| {
            let font = TexFont::open("cmr10", "cmr10.pfb")?;
            Some(Font::Tex(Box::new(font)))
        })
        .clone()
    }
}

/// What a run of text is set at: what its glyphs come to, and what it is to
/// occupy.
///
/// One argument rather than two because it is one decision, and because two
/// bare widths side by side at a call site are two things to get the wrong way
/// round. `natural` is what the caller measured this same text at, in the same
/// font at the same size; the difference between the two is what is shared out
/// over the spaces.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Set {
    pub natural: f64,
    pub width: f64,
}

/// One page: how big it is, and what is drawn on it.
#[derive(Debug, Clone)]
pub struct Page {
    /// The page's size in PDF points, which are 1/72 of an inch and not TeX's.
    pub width: f64,
    pub height: f64,
    /// The content stream: the operators that draw the page.
    pub content: String,
    /// The pictures the content names, as `(name in the content, picture)`.
    pub images: Vec<(String, std::sync::Arc<crate::image::Image>)>,
    /// The fonts the content names, as `(name in the content, font)` --
    /// `("F1", Helvetica)`.
    pub fonts: Vec<(String, std::sync::Arc<Font>)>,
    /// Which codes each of those fonts was actually asked to draw, as
    /// `("F1", {'H', 'e', 'l', 'o'})`.
    ///
    /// A face has thousands of glyphs and a book draws perhaps two hundred of
    /// them, so embedding the file whole puts a megabyte of outlines nobody
    /// looks at into every document; this is the record of which ones were
    /// looked at, kept as the page is drawn because that is the only moment
    /// that knows. It is per resource NAME rather than per font because the
    /// name is what the content stream says; `document` joins the two back
    /// together across the pages, since a font is written once for the file.
    pub used: BTreeMap<String, std::collections::BTreeSet<u8>>,
    /// The graphics-state dictionaries the content names, as `(name, key,
    /// value)` -- `("pgf@CA0.5", "CA", 0.5)`.
    ///
    /// Constant alpha is the one drawing parameter PDF gives no operator for:
    /// §11.6.4.4 puts it in a dictionary, and `gs` (§8.4.4, Table 57) sets it
    /// by NAME out of the page's `/ExtGState`. So `0.5 CA` does not exist and
    /// `/pgf@CA0.5 gs` is the whole of how a half-transparent stroke is asked
    /// for -- which means a page emitting that operator and carrying no such
    /// resource is a page whose transparency a reader silently drops, the name
    /// resolving to nothing.
    pub ext_gstates: Vec<(String, String, f64)>,
    /// The shading dictionaries the content names, as `(name, dictionary)` --
    /// `("pgfsh0", "<< /ShadingType 2 ... >>")`.
    ///
    /// `sh` (§8.7.4.5) names an entry in the page's `/Shading` exactly as `gs`
    /// names one in `/ExtGState`, so a page emitting the operator and carrying
    /// no such resource paints nothing at all.
    pub shadings: Vec<(String, String)>,
}

impl Page {
    /// A page of the size TeX defaults to: 8.5 by 11 inches.
    pub fn letter() -> Page {
        Page {
            width: 612.0,
            height: 792.0,
            content: String::new(),
            fonts: Vec::new(),
            images: Vec::new(),
            used: BTreeMap::new(),
            ext_gstates: Vec::new(),
            shadings: Vec::new(),
        }
    }

    /// Name a graphics-state dictionary this page's content stream uses, so
    /// the page's `/Resources` carries it.
    ///
    /// Naming the same one twice is what a picture with two half-transparent
    /// paths does, and the second is dropped rather than written again: the
    /// resource dictionary is keyed by the name, so a duplicate is at best a
    /// wasted entry and at worst two entries a reader may pick between.
    pub fn ext_gstate(&mut self, name: &str, key: &str, value: f64) {
        if self.ext_gstates.iter().any(|(used, _, _)| used == name) {
            return;
        }
        self.ext_gstates
            .push((name.to_string(), key.to_string(), value));
    }

    /// Name a shading dictionary this page's content stream uses, so the
    /// page's `/Resources` carries it. `dictionary` is PDF source, written
    /// through as it stands.
    ///
    /// Naming the same one twice is dropped, as for `ext_gstate` and for the
    /// same reason: the resource dictionary is keyed by the name.
    pub fn shading(&mut self, name: &str, dictionary: &str) {
        if self.shadings.iter().any(|(used, _)| used == name) {
            return;
        }
        self.shadings
            .push((name.to_string(), dictionary.to_string()));
    }

    /// Draw `text` at `(x, y)` in `size` points of `font`, where `y` is
    /// measured up from the bottom of the page -- PDF's axis, which points the
    /// other way from DVI's.
    pub fn text(&mut self, font: &str, size: f64, x: f64, y: f64, text: &str) {
        self.text_in(Font::Base14(font.to_string()), size, x, y, text);
    }

    /// The same, in a font carried in the file.
    ///
    /// The text is bytes rather than characters: a code in a TeX font means
    /// whatever the font's own encoding says, and 11 is an `ff` ligature and
    /// not a vertical tab.
    pub fn text_in(
        &mut self,
        font: impl Into<std::sync::Arc<Font>>,
        size: f64,
        x: f64,
        y: f64,
        text: &str,
    ) {
        self.draw(font, size, x, y, text, 0.0);
    }

    /// The same, set to occupy exactly the width asked for rather than whatever
    /// the glyphs happen to come to.
    ///
    /// Without this the renderer could only draw a run at its natural width,
    /// and a line breaker that prices a line over glue -- every one of them
    /// does -- had nothing to hand its answer to: a line it chose to shrink was
    /// still drawn at its natural width, out past the measure into the margin.
    ///
    /// PDF spells it `Tw` (S9.3.3): a number of unscaled text-space units added
    /// to the advance of every code 32 in a simple font, which all three of the
    /// fonts here are. Text with no space in it cannot be set to a width at
    /// all, and is drawn where it stands rather than drawn wrong.
    pub fn text_set(
        &mut self,
        font: impl Into<std::sync::Arc<Font>>,
        size: f64,
        x: f64,
        y: f64,
        text: &str,
        set: Set,
    ) {
        let font = font.into();
        // A composite font's codes are two bytes and none of them is the
        // single-byte 32 that `Tw` widens, so there is no space here to share
        // the room between: 0x20 inside a glyph id is half a glyph id.
        let spaces = match font.is_composite() {
            true => 0,
            false => text.chars().filter(|c| *c == ' ').count(),
        };
        let word_space = match spaces {
            0 => 0.0,
            n => (set.width - set.natural) / n as f64,
        };
        self.draw(font, size, x, y, text, word_space);
    }

    /// One `BT ... ET`, with `word_space` added to every space in it.
    fn draw(
        &mut self,
        font: impl Into<std::sync::Arc<Font>>,
        size: f64,
        x: f64,
        y: f64,
        text: &str,
        word_space: f64,
    ) {
        let font = font.into();
        let name = format!("F{}", self.fonts.len() + 1);
        let name = match self
            .fonts
            .iter()
            .find(|(_, used)| std::sync::Arc::ptr_eq(used, &font) || **used == *font)
        {
            Some((existing, _)) => existing.clone(),
            None => {
                self.fonts.push((name.clone(), font));
                name
            }
        };
        // What this font is asked for, so the file can carry those glyphs and
        // leave the rest of the face behind. A code is one byte -- the same
        // byte the escape below writes -- and a two-byte code of a composite
        // font is recorded as its two halves, which is what a `/CIDToGIDMap
        // /Identity` font's own glyph list already says more exactly.
        self.used
            .entry(name.clone())
            .or_default()
            .extend(text.chars().map(|c| (c as u32 & 0xFF) as u8));
        // A code above 126 is written as its octal escape, because a content
        // stream is BYTES and a `char` pushed into a Rust string is written as
        // UTF-8: the arrow at code 0xAE went into the file as three bytes, a
        // reader drew the three letters that font has at 0xE2, 0x86 and 0x92,
        // and `pdftotext` read the line back with three wrong characters in it.
        // `\256` is the one byte the font's encoding was asked for.
        let escaped: String = text
            .chars()
            .flat_map(|c| match c {
                '(' | ')' | '\\' => vec!['\\', c],
                c if (c as u32) < 32 || (c as u32) > 126 => {
                    format!("\\{:03o}", (c as u32) & 0xFF).chars().collect()
                }
                other => vec![other],
            })
            .collect();
        // Word spacing is TEXT STATE and outlives the `BT ... ET` it was set in
        // (S9.3.1), so a line set to the measure would go on stretching every
        // line drawn after it. It is set inside the block and put back before
        // the block closes, which leaves a run drawn at its natural width byte
        // for byte the operators it was before.
        //
        // It goes AFTER the `Tm` and not before it, which is the same to a
        // reader and not the same to everything that reads this stream back:
        // `Tm`'s six operands are found by counting from the `Tf`, so a `Tw`
        // between the two moves the position a line was drawn at by two words.
        let (open, close) = match word_space == 0.0 {
            true => (String::new(), String::new()),
            false => (format!("{word_space} Tw "), " 0 Tw".to_string()),
        };
        let _ = writeln!(
            self.content,
            "BT /{name} {size} Tf 1 0 0 1 {x} {y} Tm {open}({escaped}) Tj{close} ET"
        );
    }

    /// Draw a picture, with its bottom left corner at `(x, y)` and the size
    /// given in points.
    ///
    /// A picture is drawn by a matrix rather than by coordinates: PDF puts an
    /// image in the unit square and the matrix says where that square lands,
    /// which is why the width and the height go into the matrix and the
    /// drawing is one operator.
    pub fn image(
        &mut self,
        image: impl Into<std::sync::Arc<crate::image::Image>>,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) {
        let image = image.into();
        let name = match self.images.iter().find(|(_, used)| same(&**used, &*image)) {
            Some((existing, _)) => existing.clone(),
            None => {
                let name = format!("I{}", self.images.len() + 1);
                self.images.push((name.clone(), image));
                name
            }
        };
        // Saved and restored, so the matrix does not follow the picture into
        // whatever is drawn next.
        let _ = writeln!(
            self.content,
            "q {width} 0 0 {height} {x} {y} cm /{name} Do Q"
        );
    }

    /// A filled rectangle, which is what a rule is.
    pub fn rule(&mut self, x: f64, y: f64, width: f64, height: f64) {
        let _ = writeln!(self.content, "{x} {y} {width} {height} re f");
    }
}

/// Whether two references name the same value, the address first.
///
/// A font or picture used on every page is one allocation shared by all of
/// them, and comparing it with itself by value reads the whole font program or
/// the whole pixel buffer once per page per resource.
pub(crate) fn same<T: PartialEq>(a: &T, b: &T) -> bool {
    std::ptr::eq(a, b) || a == b
}

/// Fewer pages, or pictures, than this are built and compared on the calling
/// thread: fanning out costs more than a handful of them are worth.
pub(crate) const PARALLEL_PAGES: usize = 8;

/// Which distinct picture each of each page's pictures is, the classes
/// numbered in the order they are first used: what a walk over the pages
/// asking `same` of every picture written so far answers.
///
/// Asked that way it is the whole pixel buffer compared, on one thread, for
/// every use of a picture after its first -- a document that repeats its
/// figures spends its time there. So the walk matches pictures by what is
/// cheap to read -- size, depth, how long the data are -- and the comparisons
/// that confirm those matches are made in parallel. Equal pictures always
/// match, so a confirmed walk is the one the slow walk makes; two that match
/// and still differ send it the slow way, which is what it always was.
pub(crate) fn picture_classes(pages: &[Page]) -> Vec<Vec<usize>> {
    use crate::image::Image;
    use rayon::prelude::*;
    let key = |image: &Image| {
        (
            image.width,
            image.height,
            image.bits,
            image.data.len(),
            image.alpha.as_ref().map(Vec::len),
            image.palette.as_ref().map(Vec::len),
        )
    };
    let mut firsts: Vec<&Image> = Vec::new();
    let mut by_key = std::collections::HashMap::new();
    let classes: Vec<Vec<usize>> = pages
        .iter()
        .map(|page| {
            page.images
                .iter()
                .map(|(_, image)| {
                    *by_key.entry(key(image)).or_insert_with(|| {
                        firsts.push(image);
                        firsts.len() - 1
                    })
                })
                .collect()
        })
        .collect();
    let uses: Vec<(&Image, usize)> = pages
        .iter()
        .zip(&classes)
        .flat_map(|(page, classes)| {
            page.images
                .iter()
                .map(|(_, image)| &**image)
                .zip(classes.iter().copied())
        })
        .collect();
    let confirmed = match uses.len() >= PARALLEL_PAGES {
        true => uses
            .par_iter()
            .all(|&(image, class)| same(firsts[class], image)),
        false => uses
            .iter()
            .all(|&(image, class)| same(firsts[class], image)),
    };
    if confirmed {
        return classes;
    }
    let mut firsts: Vec<&Image> = Vec::new();
    pages
        .iter()
        .map(|page| {
            page.images
                .iter()
                .map(
                    |(_, image)| match firsts.iter().position(|seen| same(*seen, image)) {
                        Some(class) => class,
                        None => {
                            firsts.push(image);
                            firsts.len() - 1
                        }
                    },
                )
                .collect()
        })
        .collect()
}

/// Write a document of `pages`.
///
/// This is `pdfdoc.c`'s shape: a catalogue naming a page tree, a page tree
/// listing pages, and each page naming its own content and resources. The page
/// tree has to be numbered before the pages so a page can point at its parent
/// and the tree at its children.
pub fn document(pages: &[Page]) -> Vec<u8> {
    let contents = pages.iter().map(|page| page.content.clone()).collect();
    assemble(pages, contents)
}

/// [`document`], taking the pages: each page's content moves into its stream
/// object instead of being copied there, and on a long document the content is
/// most of the file.
pub fn document_from(mut pages: Vec<Page>) -> Vec<u8> {
    let contents = pages
        .iter_mut()
        .map(|page| std::mem::take(&mut page.content))
        .collect();
    assemble(&pages, contents)
}

/// The file for `pages`, whose content streams are `contents`, one a page:
/// LuaTeX's layout, numbering and spelling (`crate::pdfdoc`), with what the run
/// that lowered the document gave the backend (`crate::pdfdoc::prepare`), or
/// the `\pdfvariable`s LuaTeX's own format sets when nothing did.
fn assemble(pages: &[Page], contents: Vec<String>) -> Vec<u8> {
    let prepared = crate::pdfdoc::take_prepared().unwrap_or_default();
    crate::pdfdoc::write(pages, contents, prepared)
}

/// What a page's resources carry beside its fonts and pictures: the
/// graphics-state and shading dictionaries its content names, which a picture
/// asks for through the page resources (`pdf_page_resources`), so they come
/// first in LuaTeX's resource dictionary.
pub(crate) fn extra_resources(page: &Page) -> Dict {
    let mut resources = Dict::new();
    // The graphics states the content named. Built up rather than matched on,
    // because a page may have either or both.
    if !page.ext_gstates.is_empty() {
        let states: Dict = page
            .ext_gstates
            .iter()
            .map(|(name, key, value)| {
                (
                    name.clone(),
                    Object::Dict(Dict::from([(key.clone(), Object::Real(*value))])),
                )
            })
            .collect();
        resources.insert("ExtGState".to_string(), Object::Dict(states));
    }
    if !page.shadings.is_empty() {
        let shades: Dict = page
            .shadings
            .iter()
            .map(|(name, dictionary)| (name.clone(), Object::Raw(dictionary.clone())))
            .collect();
        resources.insert("Shading".to_string(), Object::Dict(shades));
    }
    resources
}

/// A picture written under the number it was given when it was first used,
/// as LuaTeX writes a pending image when the page that uses it ends.
pub(crate) fn write_image_as(
    w: &mut crate::pdfdoc::Writer,
    number: u32,
    image: &crate::image::Image,
) {
    let Object::Stream { dict, data } = image_object(w, image) else {
        return;
    };
    let own_filter = dict.get("Filter").is_some();
    let keys: String = {
        let mut body = Vec::new();
        Object::Dict(dict).write(&mut body);
        String::from_utf8_lossy(&body)
            .trim_start_matches("<<")
            .trim_end_matches(">>")
            .trim()
            .to_string()
    };
    w.stream(number, &keys, &data, !own_filter);
}

/// A font that is not a TeX font -- one of the fourteen, or a TrueType or
/// OpenType face -- written with its dictionary under the number it was given
/// when first used, and whatever it needs beside it added as it is built.
pub(crate) fn write_font_as(
    w: &mut crate::pdfdoc::Writer,
    number: u32,
    font: &Font,
    codes: &std::collections::BTreeSet<u8>,
) {
    let dict = build_font(w, font, codes);
    let mut body = Vec::new();
    dict.write(&mut body);
    w.object(number, 1, &body);
}

/// Add a picture to the file, as `pdf_ximage_load_image` does.
///
/// The pixels are not decoded and not recompressed: PDF's own compressions are
/// PNG's and JPEG's, so a JPEG becomes a `/DCTDecode` stream and a PNG's data
/// becomes a `/FlateDecode` stream with the predictor PNG filtered its rows
/// with. What the dictionary says is what the header said.
fn image_object(pdf: &mut impl Sink, image: &crate::image::Image) -> Object {
    use crate::image::{Colours, Compression};

    let space = match (image.colours, &image.palette) {
        (Colours::Indexed, Some(palette)) => Object::Array(vec![
            Object::name("Indexed"),
            Object::name("DeviceRGB"),
            // The highest index the palette defines, which is one less than
            // the number of colours in it.
            Object::Integer(palette.len() as i64 / 3 - 1),
            Object::Str(palette.iter().map(|&b| b as char).collect()),
        ]),
        (Colours::Gray, _) => Object::name("DeviceGray"),
        (Colours::Cmyk, _) => Object::name("DeviceCMYK"),
        _ => Object::name("DeviceRGB"),
    };

    let mut dict = Dict::from([
        ("Type".to_string(), Object::name("XObject")),
        ("Subtype".to_string(), Object::name("Image")),
        ("Width".to_string(), Object::Integer(image.width as i64)),
        ("Height".to_string(), Object::Integer(image.height as i64)),
        (
            "BitsPerComponent".to_string(),
            Object::Integer(image.bits as i64),
        ),
        ("ColorSpace".to_string(), space),
    ]);
    match image.compression {
        Compression::Dct => {
            dict.insert("Filter".to_string(), Object::name("DCTDecode"));
        }
        Compression::Flate => {
            dict.insert("Filter".to_string(), Object::name("FlateDecode"));
            // §7.4.4: predictor 15 is PNG's row filters, which is what is
            // inside a PNG's data and the reason it can be copied.
            dict.insert(
                "DecodeParms".to_string(),
                Object::dict([
                    ("Predictor", Object::Integer(15)),
                    ("Colors", Object::Integer(image.colours.components() as i64)),
                    ("BitsPerComponent", Object::Integer(image.bits as i64)),
                    ("Columns", Object::Integer(image.width as i64)),
                ]),
            );
        }
    }
    // A picture that carried an alpha channel carries it here as a picture of
    // its own, in grey, the same size: §8.9.5.4, which is how PDF says
    // transparency for an image.
    if let Some(alpha) = &image.alpha {
        let mask = pdf.add(Object::Stream {
            dict: Dict::from([
                ("Type".to_string(), Object::name("XObject")),
                ("Subtype".to_string(), Object::name("Image")),
                ("Width".to_string(), Object::Integer(image.width as i64)),
                ("Height".to_string(), Object::Integer(image.height as i64)),
                (
                    "BitsPerComponent".to_string(),
                    Object::Integer(image.bits as i64),
                ),
                ("ColorSpace".to_string(), Object::name("DeviceGray")),
                ("Filter".to_string(), Object::name("FlateDecode")),
                (
                    "DecodeParms".to_string(),
                    Object::dict([
                        ("Predictor", Object::Integer(15)),
                        ("Colors", Object::Integer(1)),
                        ("BitsPerComponent", Object::Integer(image.bits as i64)),
                        ("Columns", Object::Integer(image.width as i64)),
                    ]),
                ),
            ]),
            data: alpha.clone(),
        });
        dict.insert("SMask".to_string(), mask);
    }

    Object::Stream {
        dict,
        data: image.data.clone(),
    }
}

/// The six letters a subsetted font's name begins with (S9.6.4).
///
/// "The tag shall consist of exactly six uppercase letters; the choice of
/// letters is arbitrary, but different subsets in the same PDF file shall have
/// different tags." So it is a hash of what the subset HOLDS: two subsets of
/// the same face with the same glyphs are the same font and may share a tag,
/// and two that differ in one glyph differ in their tags. FNV-1a, because a
/// hash whose value is fixed by the standard is one that gives the same file
/// twice for the same document.
fn subset_tag(name: &str, glyphs: impl IntoIterator<Item = u16>) -> String {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    let mut eat = |byte: u8| {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    };
    for byte in name.bytes() {
        eat(byte);
    }
    for glyph in glyphs {
        eat((glyph >> 8) as u8);
        eat((glyph & 0xFF) as u8);
    }
    (0..6)
        .map(|i| (b'A' + ((hash >> (i * 5)) % 26) as u8) as char)
        .collect()
}

/// A TrueType program cut down to the codes a document drew, and the tag to
/// name it by.
///
/// The codes are WinAnsi -- that is the encoding these fonts are written with
/// -- and the face's `cmap` is indexed by Unicode, so the two are joined by
/// what a code MEANS, exactly as `embed_file` joined them to find the widths.
///
/// `None` when the font cannot be cut: a face whose `glyf` or `loca` will not
/// read is one to embed whole rather than to embed wrongly.
fn cut_to_codes(
    name: &str,
    bytes: &[u8],
    codes: &std::collections::BTreeSet<u8>,
) -> Option<(String, Vec<u8>)> {
    let sfnt = crate::sfnt::Sfnt::parse(bytes.to_vec()).ok()?;
    let cmap = sfnt.cmap().ok()?;
    let keep: std::collections::BTreeSet<u16> = codes
        .iter()
        .filter_map(|code| crate::typeset::winansi_unicode(*code))
        .filter_map(|ch| cmap.get(&(ch as u32)).copied())
        .collect();
    // A font nothing was drawn in is one this cannot measure the use of, and
    // carrying it whole is what it did before there was a subset at all.
    if keep.is_empty() {
        return None;
    }
    let cut = sfnt.subset_encoded(&keep).ok()?;
    Some((subset_tag(name, keep.iter().copied()), cut))
}

/// One of the fourteen, named rather than embedded.
fn base14_font(pdf: &mut impl Sink, font: &Font) -> Object {
    let name = font.name();
    // Symbol and ZapfDingbats are the two of the fourteen that are NOT in
    // any standard encoding: their codes mean what their own built-in
    // encoding says, and overlaying WinAnsi on one of them tells a reader
    // that code 174 is a guillemot where the font draws a right arrow.
    // Every other one of the fourteen is written with WinAnsi, which is the
    // encoding this driver addresses them in.
    let built_in = name == "Symbol" || name == "ZapfDingbats";
    let mut entries = vec![
        ("Type", Object::name("Font")),
        ("Subtype", Object::name("Type1")),
        ("BaseFont", Object::name(&name)),
    ];
    if !built_in {
        entries.push(("Encoding", Object::name("WinAnsiEncoding")));
    }
    // What each of the fallback font's codes MEANS, as against which glyph
    // it draws. Without it a page that draws an arrow is a page nobody can
    // search for one -- `pdftotext` read the first of these back with the
    // arrows simply absent from the text. The same thing is written beside
    // an embedded Type 1 below, out of the same `agl`; only the table of
    // what the codes mean is the font's own, and it lives beside the
    // metrics it was read from.
    if name == "Symbol" {
        let meanings: Vec<(u8, String)> = (0u8..=255)
            .filter_map(|code| Some((code, crate::typeset::symbol_unicode(code)?.to_string())))
            .collect();
        let map = pdf.add(Object::Stream {
            dict: Dict::new(),
            data: crate::agl::to_unicode(&name, &meanings).into_bytes(),
        });
        entries.push(("ToUnicode", map));
    }
    Object::dict(entries)
}

/// Add a font to the file, embedding it when it is not one of the fourteen.
///
/// Ported from `pdf_font_load_type1`. Embedding is four objects that have to
/// agree: the font dictionary, an encoding saying what each code means, a
/// descriptor with the measurements a reader needs to substitute or lay out
/// the font, and the file itself as a stream. The stream is the font exactly as
/// it was read, because a Type 1 font that was rebuilt would no longer
/// decrypt, and `Length1`, `Length2` and `Length3` say where its three parts
/// end.
///
/// `codes` is what the document actually drew in this font, which is what says
/// how much of it has to go into the file.
fn build_font(pdf: &mut impl Sink, font: &Font, codes: &std::collections::BTreeSet<u8>) -> Object {
    if let Font::Glyphs {
        name,
        bytes,
        glyphs,
        bbox,
        ascent,
        descent,
    } = font
    {
        // This program was cut down to `glyphs` when it was loaded, so the
        // name it goes into the file under is a subset's name: the tag says so,
        // and says which subset, so a reader never takes two different cuts of
        // one face for the same font.
        let name = &format!(
            "{}+{name}",
            subset_tag(name, glyphs.iter().map(|(gid, _, _)| *gid))
        );
        let file = pdf.add(Object::Stream {
            dict: Dict::from([("Length1".to_string(), Object::Integer(bytes.len() as i64))]),
            data: bytes.clone(),
        });
        let descriptor = pdf.add(Object::dict([
            ("Type", Object::name("FontDescriptor")),
            ("FontName", Object::name(name)),
            // 4 is the symbolic flag: a code here is a glyph id and not a
            // character in any standard encoding, which is what symbolic means.
            ("Flags", Object::Integer(4)),
            (
                "FontBBox",
                Object::Array(bbox.iter().map(|v| Object::Integer(*v)).collect()),
            ),
            ("ItalicAngle", Object::Integer(0)),
            ("Ascent", Object::Integer(*ascent)),
            ("Descent", Object::Integer(*descent)),
            ("CapHeight", Object::Integer(*ascent)),
            ("StemV", Object::Integer(80)),
            ("FontFile2", file),
        ]));
        // `/W` (S9.7.4.3): a CID, then the widths of the CIDs running from it.
        // Written one CID to an entry rather than in runs, because the glyphs a
        // document borrows from a fallback are scattered across the face and a
        // run of consecutive ids is the exception.
        let widths: Vec<Object> = glyphs
            .iter()
            .flat_map(|(gid, _, w)| {
                [
                    Object::Integer(i64::from(*gid)),
                    Object::Array(vec![Object::Integer(*w)]),
                ]
            })
            .collect();
        let descendant = pdf.add(Object::dict([
            ("Type", Object::name("Font")),
            ("Subtype", Object::name("CIDFontType2")),
            ("BaseFont", Object::name(name)),
            (
                "CIDSystemInfo",
                Object::dict([
                    ("Registry", Object::string("Adobe")),
                    ("Ordering", Object::string("Identity")),
                    ("Supplement", Object::Integer(0)),
                ]),
            ),
            ("FontDescriptor", descriptor),
            ("DW", Object::Integer(1000)),
            ("W", Object::Array(widths)),
            // Identity: the CID a code names IS the glyph to draw, which is
            // what makes the two-byte code above a glyph id.
            ("CIDToGIDMap", Object::name("Identity")),
        ]));
        let meanings: Vec<(u16, String)> = glyphs
            .iter()
            .map(|(gid, ch, _)| (*gid, ch.to_string()))
            .collect();
        let to_unicode = pdf.add(Object::Stream {
            dict: Dict::new(),
            data: crate::agl::to_unicode_wide(name, &meanings).into_bytes(),
        });
        return Object::dict([
            ("Type", Object::name("Font")),
            ("Subtype", Object::name("Type0")),
            ("BaseFont", Object::name(name)),
            ("Encoding", Object::name("Identity-H")),
            ("DescendantFonts", Object::Array(vec![descendant])),
            ("ToUnicode", to_unicode),
        ]);
    }
    if let Font::TrueType {
        name,
        bytes,
        widths,
        bbox,
        ascent,
        descent,
    } = font
    {
        // The font program, cut to the glyphs the document set. A book sets
        // perhaps two hundred of a face's several thousand, and carrying the
        // rest is half a megabyte a face of outlines nothing ever draws: what
        // `lualatex` writes for these same books is a third the size, and this
        // is most of the difference. A face that will not cut goes in whole,
        // which is what every face did before.
        let (tag, program) = match cut_to_codes(name, bytes, codes) {
            Some((tag, cut)) => (format!("{tag}+"), cut),
            None => (String::new(), bytes.clone()),
        };
        // S9.6.4: a subsetted font is named for its subset, so a reader does
        // not take one cut of a face for another.
        let name = &format!("{tag}{name}");
        let file = pdf.add(Object::Stream {
            dict: Dict::from([("Length1".to_string(), Object::Integer(program.len() as i64))]),
            data: program,
        });
        let descriptor = pdf.add(Object::dict([
            ("Type", Object::name("FontDescriptor")),
            ("FontName", Object::name(name)),
            // 32 is the non-symbolic flag: the font uses a standard encoding,
            // which is what the WinAnsi below makes true.
            ("Flags", Object::Integer(32)),
            (
                "FontBBox",
                Object::Array(bbox.iter().map(|v| Object::Integer(*v)).collect()),
            ),
            ("ItalicAngle", Object::Integer(0)),
            ("Ascent", Object::Integer(*ascent)),
            ("Descent", Object::Integer(*descent)),
            ("CapHeight", Object::Integer(*ascent)),
            ("StemV", Object::Integer(80)),
            ("FontFile2", file),
        ]));
        return Object::dict([
            ("Type", Object::name("Font")),
            ("Subtype", Object::name("TrueType")),
            ("BaseFont", Object::name(name)),
            ("FirstChar", Object::Integer(32)),
            ("LastChar", Object::Integer(255)),
            (
                "Widths",
                Object::Array(widths.iter().map(|w| Object::Integer(*w)).collect()),
            ),
            ("Encoding", Object::name("WinAnsiEncoding")),
            ("FontDescriptor", descriptor),
        ]);
    }
    let type1: &crate::type1::Type1 = match font {
        Font::Embedded(type1) => type1,
        // `crate::pdfdoc` writes a TeX font itself; asked here, its program is
        // written as a Type 1 program on its own.
        Font::Tex(tex) => &tex.program,
        _ => return base14_font(pdf, font),
    };

    // Which glyph of the WHOLE font each code the driver drew asks for. That is
    // what says how much of the font has to go into the file, so it is worked
    // out before the program is written rather than after.
    let wanted = |font: &crate::type1::Type1, code: u8| glyph_for_code(font, code);

    // The font cut down to those glyphs, under a subset name. A font nothing
    // was drawn in cannot be measured for use and goes in whole, which is what
    // every Type 1 font did before there was a subset at all.
    let keep: std::collections::BTreeSet<String> = codes
        .iter()
        .filter_map(|&code| wanted(type1, code))
        .collect();
    let cut = match keep.is_empty() {
        true => None,
        false => {
            let tag = subset_tag(&type1.font_name, codes.iter().map(|&c| u16::from(c)));
            type1.subset(&keep, &tag)
        }
    };
    // Everything below reads the font that is actually going into the file:
    // its name carries the subset tag, its `/CharSet` names what it carries,
    // and its encoding is the cut one.
    let subsetted = cut.is_some();
    let type1 = cut.as_ref().unwrap_or(type1);

    let (bytes, clear, binary, trailer) = type1.embeddable();
    let file = pdf.add(Object::Stream {
        dict: Dict::from([
            ("Length1".to_string(), Object::Integer(clear as i64)),
            ("Length2".to_string(), Object::Integer(binary as i64)),
            ("Length3".to_string(), Object::Integer(trailer as i64)),
        ]),
        data: bytes,
    });

    // The measurements a reader needs. A TeX font is not in any of the
    // standard encodings, so `Symbolic` is set: that is what tells a reader to
    // believe the font's own encoding rather than overlay a standard one.
    let bbox = type1.font_bbox;
    // What the font says about itself, where it says anything. `/ItalicAngle`
    // is in the cleartext header and `/StdVW` in the Private DICT, and both
    // were written as constants here before they were read.
    //
    // Ascent, descent, cap height and x-height are asked for and are in NONE of
    // a Type 1 font: they are in the `.afm` beside it, which `Type1::open`
    // reads. Measured, that is where LuaTeX gets them -- for CMR10 it writes
    // `/Ascent 694 /CapHeight 683 /Descent -194 /XHeight 431`, which is
    // cmr10.afm's `Ascender`, `CapHeight`, `Descender` and `XHeight` to the
    // digit and none of which is anywhere in cmr10.pfb.
    //
    // Without the metrics the bounding box is what there is to say, and it says
    // something else: the box's top and bottom are the extremes of the OUTLINES
    // -- 750 and -250 for CMR10, where the letters reach 694 and -194.
    let heights = type1.afm_metrics;
    let mut entries = vec![
        ("Type", Object::name("FontDescriptor")),
        ("FontName", Object::name(&type1.font_name)),
        ("Flags", Object::Integer(4)),
        (
            "FontBBox",
            Object::Array(bbox.iter().map(|&n| Object::Real(n)).collect()),
        ),
        // The keys from here down are in LuaTeX's order -- measured, it writes
        // `/Ascent 694 /CapHeight 683 /Descent -194 /ItalicAngle 0 /StemV 69
        // /XHeight 431 /CharSet(...) /FontFile 9 0 R` -- so the two say the
        // same thing in the same bytes rather than only in the same words.
        (
            "Ascent",
            Object::Real(heights.map(|m| m.ascender).unwrap_or(bbox[3])),
        ),
        (
            "CapHeight",
            Object::Real(heights.map(|m| m.cap_height).unwrap_or(bbox[3])),
        ),
        (
            "Descent",
            Object::Real(heights.map(|m| m.descender).unwrap_or(bbox[1])),
        ),
        ("ItalicAngle", Object::Real(type1.italic_angle)),
        // The font's own dominant stem width when it states one. LuaTeX writes
        // 69 whatever the face, which is a default rather than an answer.
        ("StemV", Object::Real(type1.stem_v.unwrap_or(80.0))),
        // §9.8.1: the glyphs the file actually carries, as a string of names.
        // Spelled the way LuaTeX spells it -- `/CharSet( /H /d /e /l /o /one
        // /period /r /w)`, a space before each name -- and a reader uses it to
        // tell a subset from a whole font without decrypting the font program.
        // These are what the program carries: the cut's glyphs when it was cut,
        // and all of the font's when it went in whole.
    ];
    // Only when it is known: §9.8.1 marks `/XHeight` optional, and a face whose
    // metrics could not be found has nothing to say about it. Before the two
    // below, which is where LuaTeX writes it.
    if let Some(metrics) = heights {
        entries.push(("XHeight", Object::Real(metrics.x_height)));
    }
    entries.push((
        "CharSet",
        Object::string(
            &type1
                .glyph_names()
                .iter()
                .map(|name| format!(" /{name}"))
                .collect::<String>(),
        ),
    ));
    entries.push(("FontFile", file));
    let descriptor = pdf.add(Object::dict(entries));

    // Which glyph each code draws, in the font that is going into the file.
    //
    // A CUT font carries the glyphs the document drew and nothing else, so the
    // codes are the ones it drew: `/FirstChar 46 /LastChar 119` for
    // `Hello world.`, which is what LuaTeX writes for the same page. A font
    // that went in whole is addressed over its own encoding as it always was,
    // since a code it can draw may be drawn by a later edit of the document
    // and the whole program is there for it.
    let addressed: Vec<u8> = match subsetted {
        true => codes.iter().copied().collect(),
        false => (0..=255u8).collect(),
    };
    let encoded: BTreeMap<u8, &crate::type1::Glyph> = addressed
        .into_iter()
        .filter_map(|code| Some((code, type1.glyph(&wanted(type1, code)?)?)))
        .collect();

    let first = encoded.keys().next().copied().unwrap_or(0) as usize;
    let last = encoded.keys().next_back().copied().unwrap_or(0) as usize;

    let mut differences = Vec::new();
    let mut expected = usize::MAX;
    for code in first..=last {
        let Some(glyph) = encoded.get(&(code as u8)) else {
            continue;
        };
        // A run of consecutive codes is written once with its first code, so
        // the array is `1 /a /b /c 40 /x` rather than a code per name.
        if code != expected {
            differences.push(Object::Integer(code as i64));
        }
        differences.push(Object::name(&glyph.name));
        expected = code + 1;
    }
    let encoding = pdf.add(Object::dict([
        ("Type", Object::name("Encoding")),
        ("Differences", Object::Array(differences)),
    ]));

    // The widths, in thousandths of an em, which is what the font is drawn in.
    let widths: Vec<Object> = (first..=last)
        .map(|code| {
            Object::Real(
                encoded
                    .get(&(code as u8))
                    .map(|glyph| glyph.width)
                    .unwrap_or(0.0),
            )
        })
        .collect();

    // What each code MEANS, as against which glyph it draws. A PDF says only
    // the second, so a reader asked to copy a paragraph out has a glyph called
    // `ff` and no idea it is two f's. Some readers guess from the name; this
    // says, which is what `xdvipdfmx` writes and what makes a TeX document's
    // text searchable rather than nearly searchable.
    let meanings: Vec<(u8, String)> = (first..=last)
        .filter_map(|code| {
            let glyph = encoded.get(&(code as u8))?;
            Some((code as u8, crate::agl::unicode(&glyph.name)?))
        })
        .collect();
    let to_unicode = pdf.add(Object::Stream {
        dict: Dict::new(),
        data: crate::agl::to_unicode(&type1.font_name, &meanings).into_bytes(),
    });

    // In LuaTeX's order as far as the two write the same keys: measured, it
    // writes `<< /Type /Font /Subtype /Type1 /BaseFont /KJJYRX+CMR10
    // /FontDescriptor 8 0 R /FirstChar 46 /LastChar 119 /Widths 7 0 R >>`. The
    // last two are texrs's own and go at the end -- LuaTeX writes NEITHER, and
    // that is a difference in what the file says rather than in how it is
    // spelled: it leaves the subset's own built-in encoding to say what a code
    // means, and says nothing at all about what a code MEANS in Unicode, so a
    // reader copying a ligature out of its file is guessing from the glyph
    // name where a reader of this one is told.
    Object::dict([
        ("Type", Object::name("Font")),
        ("Subtype", Object::name("Type1")),
        ("BaseFont", Object::name(&type1.font_name)),
        ("FontDescriptor", descriptor),
        ("FirstChar", Object::Integer(first as i64)),
        ("LastChar", Object::Integer(last as i64)),
        ("Widths", Object::Array(widths)),
        ("Encoding", encoding),
        ("ToUnicode", to_unicode),
    ])
}

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

    fn written(object: Object) -> String {
        let mut out = Vec::new();
        object.write(&mut out);
        String::from_utf8_lossy(&out).into_owned()
    }

    /// Every kind of object, written the way §7.3 says.
    #[test]
    fn an_object_is_written_the_way_the_specification_says() {
        assert_eq!(written(Object::Null), "null");
        assert_eq!(written(Object::Boolean(true)), "true");
        assert_eq!(written(Object::Integer(-42)), "-42");
        assert_eq!(written(Object::Reference(12)), "12 0 R");

        // A real is written without an exponent, because a reader is entitled
        // to refuse one, and without trailing zeros.
        assert_eq!(written(Object::Real(1.5)), "1.5");
        assert_eq!(written(Object::Real(612.0)), "612");
        assert_eq!(written(Object::Real(0.0000001)), "0");
        assert_eq!(written(Object::Real(-0.25)), "-0.25");

        // A string ends at its closing parenthesis unless the parenthesis is
        // escaped, which is the classic way to write a broken PDF.
        assert_eq!(written(Object::string("plain")), "(plain)");
        assert_eq!(written(Object::string("a (b) c")), "(a \\(b\\) c)");
        assert_eq!(written(Object::string("back\\slash")), "(back\\\\slash)");
        assert_eq!(written(Object::string("two\nlines")), "(two\\nlines)");

        // A name escapes anything unusual as #xx.
        assert_eq!(written(Object::name("Helvetica")), "/Helvetica");
        assert_eq!(written(Object::name("a b")), "/a#20b");
        assert_eq!(written(Object::name("A#B")), "/A#23B");

        assert_eq!(
            written(Object::Array(vec![Object::Integer(1), Object::name("x")])),
            // Spaced inside the brackets, which is LuaTeX's habit and now this
            // writer's: measured, luatex writes `/W [ 1 2 1 ]` and
            // `/Index [ 0 13 ]`. §7.3.6 asks only for whitespace between the
            // items, so the spacing is a writer's choice, and matching it is
            // one fewer difference in every array in the file.
            "[ 1 /x ]"
        );
        assert_eq!(
            written(Object::dict([
                ("Type", Object::name("Page")),
                ("Count", Object::Integer(2))
            ])),
            // In the order the keys were PUT IN, not sorted: a dictionary is
            // unordered to a reader (§7.3.7) and so the order is the writer's
            // habit, and luatex's habit is insertion order. Matching it is what
            // lets the page, the font and the descriptor agree with luatex key
            // for key rather than only in content.
            "<< /Type /Page /Count 2 >>"
        );
        // Spaced the way LuaTeX spaces a dictionary. The spec allows any
        // whitespace here, so this pins a writer's habit -- and pinning it is
        // the point: two writers with different habits give different bytes for
        // identical content, which the parity ladder would report forever.
        assert_eq!(written(Object::Dict(Dict::new())), "<< >>");
    }

    /// A stream's `Length` is what was written, not what was claimed.
    #[test]
    fn a_stream_carries_the_length_of_what_it_holds() {
        let text = written(Object::Stream {
            dict: Dict::from([("Length".to_string(), Object::Integer(9999))]),
            data: b"12345".to_vec(),
        });
        assert!(text.starts_with("<< /Length 5 >>"), "{text}");
        assert!(text.contains("\nstream\n12345\nendstream"), "{text}");
    }

    /// The cross-reference table is the file's index, and every entry in it
    /// must land where it says -- at a byte offset, or at an index inside the
    /// object stream.
    ///
    /// The three objects here are all packable, so all three go into the
    /// `/ObjStm` and NONE of them has a byte offset any more. What is checked
    /// is the pair of indirections that replaced the one: the table says
    /// "index 2 of object 4", object 4's own header says where index 2 starts,
    /// and the object is there.
    #[test]
    fn every_entry_in_the_table_lands_where_it_says() {
        let mut pdf = Pdf::new();
        pdf.add(Object::Integer(1));
        pdf.add(Object::string(
            "a longer object, to move the next one along",
        ));
        let third = pdf.add(Object::dict([("Type", Object::name("Catalog"))]));
        if let Object::Reference(number) = third {
            pdf.set_catalog(number);
        }
        let bytes = pdf.finish();
        // The offsets in the table are byte offsets, and the header's binary
        // comment is not UTF-8 -- so all of this is done on the bytes. Doing
        // it on a lossy string moves every offset along by two per replaced
        // byte, which is a mistake worth making once.
        let text = String::from_utf8_lossy(&bytes);

        assert!(bytes.starts_with(b"%PDF-1.7\n"), "{text}");
        assert!(bytes.ends_with(b"%%EOF\n"), "{text}");
        assert!(text.contains("/Root 3 0 R"), "{text}");
        // Object zero, the three that were added, the object stream holding
        // them and the table itself.
        assert!(text.contains("/Size 6"), "{text}");
        // Nothing is written as a numbered object of its own except those two.
        assert_eq!(text.matches(" 0 obj\n").count(), 2, "{text}");

        // Read the table the way a reader does.
        let at = text.rfind("startxref\n").expect("a startxref");
        let start: usize = text[at + 10..]
            .lines()
            .next()
            .expect("an offset")
            .trim()
            .parse()
            .expect("a number");
        assert!(bytes[start..].starts_with(b"5 0 obj\n"), "{text}");
        let dict =
            String::from_utf8_lossy(&bytes[start..(start + 200).min(bytes.len())]).into_owned();
        assert!(dict.contains("/Type /XRef"), "{dict}");
        assert!(dict.contains("/W [ 1 2 1 ]"), "{dict}");

        let table = inflated_stream(&bytes, start);
        assert_eq!(table.len(), 6 * 4, "six entries of four bytes");
        let entry = |number: usize| {
            let row = &table[number * 4..number * 4 + 4];
            (
                row[0] as usize,
                (row[1] as usize) << 8 | row[2] as usize,
                row[3] as usize,
            )
        };
        assert_eq!(entry(0), (0, 0, 255), "object zero heads the free list");
        for number in 1..=3 {
            assert_eq!(
                entry(number),
                (2, 4, number - 1),
                "object {number} is not packed where the table says"
            );
        }
        assert_eq!(entry(5), (1, start, 0), "the table's own entry");

        // Object 4 is the object stream, at the offset the table gives, and
        // its header locates each packed object inside it.
        let (kind, offset, _) = entry(4);
        assert_eq!(kind, 1, "an object stream cannot be inside one");
        assert!(bytes[offset..].starts_with(b"4 0 obj\n"), "{text}");
        let head =
            String::from_utf8_lossy(&bytes[offset..(offset + 200).min(bytes.len())]).into_owned();
        assert!(head.contains("/Type /ObjStm"), "{head}");
        assert!(head.contains("/N 3"), "{head}");
        let data = inflated_stream(&bytes, offset);
        let first: usize = head
            .split("/First ")
            .nth(1)
            .expect("a /First")
            .chars()
            .take_while(char::is_ascii_digit)
            .collect::<String>()
            .parse()
            .expect("a number");
        let plain = String::from_utf8_lossy(&data).into_owned();
        let pairs: Vec<usize> = plain[..first]
            .split_whitespace()
            .map(|word| word.parse().expect("a number"))
            .collect();
        assert_eq!(pairs.len(), 6, "three objects, each a number and an offset");
        for (i, want) in ["1", "(a longer", "<< /Type /Catalog >>"]
            .iter()
            .enumerate()
        {
            assert_eq!(pairs[i * 2], i + 1, "the objects are in order");
            let at = first + pairs[i * 2 + 1];
            assert!(
                plain[at..].starts_with(want),
                "object {} is not at {at}: {:?}",
                i + 1,
                &plain[at..(at + 24).min(plain.len())]
            );
        }
    }

    /// The inflated data of the stream object beginning at `start`.
    fn inflated_stream(pdf: &[u8], start: usize) -> Vec<u8> {
        let at = find(&pdf[start..], b"stream\n").expect("a stream") + start + 7;
        let end = find(&pdf[at..], b"\nendstream").expect("an endstream") + at;
        let mut out = Vec::new();
        std::io::Read::read_to_end(&mut flate2::read::ZlibDecoder::new(&pdf[at..end]), &mut out)
            .expect("the stream inflates");
        out
    }

    /// A page carries what was drawn on it.
    #[test]
    fn a_page_holds_its_text_and_its_fonts() {
        let mut page = Page::letter();
        page.text("Helvetica", 12.0, 72.0, 700.0, "Hello (world)");
        page.text("Helvetica", 12.0, 72.0, 680.0, "again");
        page.text("Times-Roman", 10.0, 72.0, 660.0, "and again");
        page.rule(72.0, 650.0, 100.0, 1.0);

        // A font is named once however often it is used.
        assert_eq!(page.fonts.len(), 2);
        assert_eq!(
            page.fonts[0],
            (
                "F1".to_string(),
                Font::Base14("Helvetica".to_string()).into()
            )
        );
        assert_eq!(page.content.matches("/F1").count(), 2);
        // The parentheses in the text are escaped, or the stream ends early.
        assert!(
            page.content.contains("(Hello \\(world\\)) Tj"),
            "{}",
            page.content
        );
        assert!(
            page.content.contains("72 650 100 1 re f"),
            "{}",
            page.content
        );
    }

    /// `unpacked` gives back every object the file holds, header and all.
    ///
    /// The point of it is that a reader which walks `N 0 obj ... endobj` and
    /// follows the references between them sees the whole document -- so this
    /// checks the count, and then that a reference INTO the object stream
    /// resolves: the catalogue names the page tree, and the page tree is one of
    /// the objects that came back.
    #[test]
    fn unpacking_gives_back_every_object_the_file_holds() {
        let mut first = Page::letter();
        first.text("Helvetica", 12.0, 72.0, 700.0, "one");
        let mut second = Page::letter();
        second.text("Times-Roman", 12.0, 72.0, 700.0, "two");
        let bytes = document(&[first, second]);

        // Numbered as LuaTeX numbers them (`crate::pdfdoc`): each page's
        // resources, page and content as it begins (1-3 and 7-9), its font
        // when first drawn (4, 10), the page tree as the first page ends (5),
        // the object stream when the first object went into it (6), then the
        // catalogue, the information dictionary and the table (11-13).
        // Unpacked, every one comes back but the object stream, because what
        // it held stands in its place.
        let plain = String::from_utf8_lossy(&unpacked(&bytes)).into_owned();
        let numbers: Vec<u32> = plain
            .match_indices(" 0 obj\n")
            .filter_map(|(at, _)| plain[..at].rsplit('\n').next()?.parse().ok())
            .collect();
        let mut sorted = numbers.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), numbers.len(), "an object came back twice");
        assert_eq!(
            sorted,
            vec![1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13],
            "{plain}"
        );

        // The object stream itself is gone: what it held is what stands in its
        // place.
        assert!(!plain.contains("/Type /ObjStm"), "{plain}");
        assert_eq!(plain.matches("/Type /Page ").count(), 2, "{plain}");
        assert_eq!(plain.matches("/Type /Pages").count(), 1, "{plain}");

        // And a reference resolves: the catalogue's /Pages names an object that
        // came back, and that object is the page tree.
        let catalog = plain
            .split("endobj")
            .find(|body| body.contains("/Type /Catalog"))
            .expect("a catalogue");
        let tree = number_after(catalog, "/Pages ").expect("a reference");
        let body = plain
            .split("endobj")
            .find(|body| body.contains(&format!("\n{tree} 0 obj\n")))
            .unwrap_or_else(|| panic!("object {tree} did not come back: {plain}"));
        assert!(body.contains("/Type /Pages"), "{body}");
    }
}