f-office-docx 0.3.0

DOCX model and Word's layout rules.
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
//! The glyph steps that every device under [`Advances::RightEdge`] shares, and the one match
//! that chooses the device's segment rule ([`rule`]).

use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Length, div_round_i128, lowest_terms};

use super::from_line_start::FromLineStart;
use super::from_restart::FromRestart;
use super::{Advances, Device, Rounding};
use crate::params;
use crate::quirks::{AlignedTabEnd, GlyphEdgeCheck, NoteMarkPlace, NoteStartSteps};

/// The segment of a line that the next glyph lies in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Segment {
    /// The exact place that the segment counts from.
    pub first: Length,
    /// The end of the segment, counted from `first`.
    pub end: Length,
    /// `first` as the restarts count it: scaled from the line's first glyph.
    pub counted: Length,
}

impl Segment {
    /// The exact place `x` as the edge check counts it in this segment: from the segment's first
    /// glyph at the device's rounded dots per point ([`Device::exact_scale`]), from that glyph's
    /// own place as the restarts count it.
    #[must_use]
    pub fn counted_place(self, device: &Device, x: Length) -> Length {
        let (numerator, denominator) = device.exact_scale();
        self.counted + ((x - self.first) * numerator).div_round(denominator)
    }
}

/// A distance at the drawn size of `scale`, the nominal and the drawn size of a glyph when they
/// differ.
fn drawn_distance(scale: Option<(Length, Length)>, distance: Length) -> Length {
    match scale {
        Some((size, drawn)) => (distance * drawn.units()).div_round(size.units()),
        None => distance,
    }
}

/// A glyph that starts the steps again at the end of a segment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Restart {
    /// The glyph's exact place, that it goes to the nearest dot of.
    pub place: Length,
    /// The segment from this glyph on.
    pub segment: Segment,
    /// What the glyph adds to its exact place before it goes to the nearest dot, when it
    /// starts a segment that hands its own rounding on, as the first glyph of a line that
    /// starts at its indent does.
    pub carried: Option<Length>,
    /// Whether `place` is the glyph's counted place rounded up to the nearest half-EMU, which
    /// `RestartCount::EdgeCheckPlaces` counts: a fraction of a half-EMU below a half dot, the
    /// glyph then goes to the dot below.
    pub rounded_up: bool,
}

/// A segment rule: where a segment of a line's glyph steps ends, and where the glyph that
/// starts the next segment goes. Each variant of the quirk `GlyphSegments` is one module that
/// implements it.
pub(super) trait SegmentRule {
    /// The restart of the next glyph, whose exact place and advance are `glyph`, when it
    /// starts the next segment after `segment`. `length` is the length of a segment, and
    /// `start` the dot of the current segment's first glyph less its exact place.
    fn next(
        &self,
        device: &Device,
        segment: Segment,
        glyph: (Length, Length),
        length: Length,
        start: Length,
    ) -> Option<Restart>;

    /// The segment that the glyph after a gap with a width that is neither a tab nor a list
    /// label's gap counts in, after `segment`; `None` starts a segment as the line's first glyph
    /// does.
    fn after_gap(&self, segment: Option<Segment>) -> Option<Segment>;

    /// Whether an inline object keeps the active segment and edge-check anchor (shifted by the
    /// object's whole-dot width) and places the next glyph at the nearest dot of its counted exact
    /// place instead of restarting as a gap.
    fn continues_after_inline_object(&self) -> bool {
        false
    }
}

/// The segment rule of `device`: the variant of the quirk `GlyphSegments` that its quirks
/// hold. A device without edge steps takes the rule of `FromLineStart`. This match is the only
/// place that names a segment rule.
fn rule(device: &Device) -> &'static dyn SegmentRule {
    // quirk: GlyphSegments (src/quirks.rs), which the device keeps with the target's quirks.
    match (device.advances(), device.quirks.glyph_segments) {
        (Advances::RightEdge { .. }, crate::quirks::GlyphSegments::FromRestart) => &FromRestart,
        _ => &FromLineStart,
    }
}

/// The places of the glyphs of a line on the device under [`Advances::RightEdge`], from its
/// first glyph or from the last piece with a width that is not a glyph.
///
/// The first glyph goes to the nearest dot of its exact place. Each later glyph goes one step
/// after the glyph before, where the step is the exact distance between the two glyphs plus
/// `bias`, rounded to the nearest dot, half up. It then moves one dot left when its right edge,
/// its place plus its own advance's step, would end more than `limit` past its exact right
/// edge, and one dot right when it would end `limit` or more short of it. The exact places
/// count from the first glyph's dot.
///
/// The line is cut into segments of `segment`, as the device's segment rule says (`rule`): a
/// whole number of segments from the exact place of the line's first glyph (`FromLineStart`),
/// or each from the exact place of its own first glyph (`FromRestart`). Under both, the first
/// glyph after a tab or a list label's gap starts a segment as the line's first glyph does
/// ([`Self::tab`]); after another gap with a width the segment rule says whether it does
/// ([`Self::gap`]).
/// The glyph that the rule says starts a segment starts the steps again as the line's first
/// glyph does: it goes to the nearest dot of the exact place that the rule gives it, and the
/// exact places after it count from that dot.
///
/// A glyph can carry an extra: the share of a justified line's free space in a space, or the
/// character spacing of its run. The glyph after it takes the step of the distance without the
/// extra, and then the extra rounded to whole dots on its own ([`Self::after_extra`]). The
/// glyph's own edge check reads the same two parts: its width's step and its extra in whole
/// dots ([`Self::with_extra`]). The exact places that the edge check compares with keep the
/// exact extra. How the extra rounds to whole dots depends on what it holds ([`GlyphExtra`]).
///
/// Where the text is drawn at a size off the device's grid ([`Self::at_size`]), the steps and
/// the glyph's own step count the distances at the drawn size, and the exact places stay at
/// the nominal size.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EdgeSteps {
    /// The nominal and the drawn size of the text, when they differ.
    scale: Option<(Length, Length)>,
    /// The nominal and the drawn size of the glyph placed last, when they differ.
    before_scale: Option<(Length, Length)>,
    /// The exact place and the dot of the glyph before.
    previous: Option<(Length, Length)>,
    /// The first glyph's dot less its exact place, as the edge check
    /// `GlyphEdgeCheck::RoundedWithTie` counts that place.
    shift: Length,
    /// The exact place and the dot of the glyph that started the steps: the line's first
    /// glyph, the first after a tab or a gap, or the first of a segment.
    anchor: (Length, Length),
    /// What rounding took from the advances of the glyphs since the one that started the
    /// steps, in half-EMUs: the exact places less the rounded ones.
    drift: Exact,
    /// What rounding took from the next glyph's own advance, in half-EMUs.
    rounding: Exact,
    /// The segment of the next glyph, from the line's first glyph on.
    segment: Option<Segment>,
    /// The extra of the glyph right before the next glyph.
    extra: GlyphExtra,
    /// The dot of the current segment's first glyph less its exact place.
    start: Length,
    /// Whether the line's first glyph hands its dot less its exact place on, as the first
    /// glyph of a later segment does.
    line_hands_on: bool,
    /// The measured device width of the next glyph in dots with its advance, where the
    /// target's width is not the advance rounded.
    measured: Option<(i64, Length)>,
    /// What the measured device width of the glyph before adds to its advance rounded.
    widened: Length,
    /// The extra in the next glyph's advance.
    stretched: GlyphExtra,
    /// Whether the next glyph's own step rounds its advance without the bias.
    without_bias: bool,
    /// Whether the step out of the glyph before rounds its distance without the bias.
    before_without_bias: bool,
    /// How far the next glyph's exact place moves before it goes to its dot
    /// ([`Self::with_stop_nudge`]).
    nudge: Length,
    /// How many glyphs the steps have placed since the glyph that started them, which counts
    /// none ([`Self::started`]).
    stepped: u32,
    /// What the edge check found at the glyph placed last ([`Self::take_checked`]).
    checked: Option<EdgeCheck>,
    /// The place that the steps rounded to the dot of the glyph placed last, when they started
    /// again at it ([`Self::take_start_place`]).
    start_place: Option<Length>,
    /// Where the next glyph goes ([`Self::at_nearest_exact`]).
    next_place: NextPlace,
    /// The character spacing of the next glyph ([`Self::with_character_spacing`]).
    spacing: Length,
    /// What the edge check and the segment rule count beside the next glyph's advance and its
    /// character spacing ([`Self::with_counted_extra`]).
    counted_extra: Exact,
    /// How much nearer than the limit the next glyph's right edge, when it ends short of its
    /// exact edge, makes the edge check move it one dot right ([`Self::with_short_ease`]).
    short_ease: Length,
    /// What the glyphs of the current segment, from its first glyph to the one placed last,
    /// add to their exact advances by how the edge check counts their parts, such as their
    /// character spacing (`CharacterSpacingCount`), in half-EMUs.
    counted_excess: Exact,
    /// What the edge check counts beside the next glyph's share of a justified line's free
    /// space, when the glyph is a stretched space ([`Self::with_counted_share`]).
    share: Option<Exact>,
    /// Whether the edge check still counts the shares that [`Self::with_counted_share`] gives.
    share_count: ShareCount,
    /// What rounding to whole half-EMUs took from the advances of the current segment's
    /// glyphs, from its first glyph to the one placed last, in half-EMUs.
    segment_rounding: Exact,
    /// What the edge check counted beside the shares of the current segment's stretched
    /// spaces, from its first glyph to the one placed last ([`Self::counted_share`]).
    segment_share: Exact,
}

/// Whether the edge check of right-edge steps counts the shares of a justified line's free space
/// that [`EdgeSteps::with_counted_share`] gives, in the steps' first count.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum ShareCount {
    /// No stretched space was placed since the line's first glyph.
    #[default]
    Before,
    /// A stretched space was placed, and no tab or other gap came since.
    Counting,
    /// A tab or another gap came after a stretched space: from there on, the check counts the
    /// shares that the line spreads.
    Ended,
}

impl ShareCount {
    /// The state after a tab or another gap.
    const fn restarted(self) -> Self {
        match self {
            Self::Before => Self::Before,
            Self::Counting | Self::Ended => Self::Ended,
        }
    }
}

/// Where the right-edge steps put the next glyph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum NextPlace {
    /// Stepped from the glyph before and moved by the edge check.
    #[default]
    Stepped,
    /// At the dot nearest to its exact place as the edge check counts it.
    NearestExact,
    /// First glyph of an auto-numbered endnote reference: placed at the dot nearest to its exact
    /// place as the edge check counts it, and counted by its device width without adding edge
    /// drift.
    EndnoteStart,
    /// Later glyph of an auto-numbered endnote reference or any glyph of an endnote's own mark:
    /// stepped from the glyph before without the edge check's move, and counted by its device
    /// width without adding edge drift.
    EndnoteStep,
    /// Stepped from the glyph before without the edge check's move; the edge check counts the
    /// exact places after it from its dot, as from a glyph that started the steps.
    Restepped,
}

/// What the edge check of the right-edge steps found at a glyph that the steps placed from the
/// glyph before, for the tools that compare it with the target's places.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EdgeCheck {
    /// How far the glyph's right edge on the device, before the check moves it, ends past its
    /// exact right edge as the check counts it, in whole half-EMUs; below 0 when it ends short.
    pub edge: Length,
    /// The same edge in thousandths of a half-EMU, to the nearest thousandth: the check
    /// `GlyphEdgeCheck::Exact` counts it in fractions of a half-EMU.
    pub edge_thousandths: i64,
    /// What rounding to whole half-EMUs took from the glyph's own advance, with what its
    /// character spacing adds to the check, in thousandths of a half-EMU to the nearest one.
    pub rounding_thousandths: i64,
    /// The dots by which the check moves the glyph: -1, 0 or 1.
    pub moves: i64,
}

impl EdgeSteps {
    /// The step from a glyph to the glyph after it when the edge check moves neither: the
    /// glyph's device width `measured` in whole dots, where the target's face gives one, or else
    /// its `advance` at the size that the device draws for its `size`, with the bias `bias`, to
    /// the nearest dot.
    #[must_use]
    pub fn alone_step(
        device: &Device,
        (size, advance): (Length, Length),
        measured: Option<i64>,
        bias: Length,
    ) -> Length {
        measured.map_or_else(
            || {
                let drawn = device.snap(size);
                let scale = (size > Length::ZERO && drawn != size).then_some((size, drawn));
                device.snap(drawn_distance(scale, advance) + bias)
            },
            |dots| device.dots(dots),
        )
    }

    /// Says what rounding to whole half-EMUs took from the next glyph's own advance, as a
    /// numerator over a positive denominator in half-EMUs (`Shaper::advance_rounding`), or
    /// nothing with `None`. The edge check `GlyphEdgeCheck::Exact` adds it to the glyph's
    /// exact advance, and to the exact places of the glyphs after it.
    pub fn with_advance_rounding(&mut self, rounding: Option<(i64, i64)>) {
        self.rounding = rounding.map_or(Exact::ZERO, |(lost, per)| Exact::new(lost, per));
    }

    /// Says that the device steps the next glyph by the measured `width` in dots, where its
    /// advance alone is `advance`, or by its advance rounded with `None`. The width counts in
    /// the glyph's own edge check and in the step to the glyph after it.
    pub fn with_device_width(&mut self, measured: Option<(i64, Length)>) {
        self.measured = measured;
    }

    /// Says whether the device rounds the next glyph's distances without the bias: its own
    /// step in the edge check, and the step to the glyph after it. A glyph of a kerned run of
    /// a target with `KernedDeviceWidths::Nearest` or `KernedDeviceWidths::NearestOrOwn` steps
    /// so where that variant steps at the nearest dot (`KernedDeviceWidths::in_run`).
    pub const fn without_bias(&mut self, without: bool) {
        self.without_bias = without;
    }

    /// Says that the step from the glyph placed last to the next glyph rounds their distance
    /// to the nearest dot, without the bias and without what the device width of the glyph
    /// placed last adds to its advance rounded.
    pub const fn step_to_nearest_dot(&mut self) {
        self.widened = Length::ZERO;
        self.before_without_bias = true;
    }

    /// Says that the next glyph follows a glyph whose advance holds `extra`, which the next
    /// glyph's step adds in whole dots on its own: a justified space's share of the line's free
    /// space, or a run's character spacing.
    pub fn after_extra(&mut self, extra: GlyphExtra) {
        self.extra = extra;
    }

    /// What the glyph after the last one placed would add in whole dots on its own for the
    /// extra of [`Self::after_extra`]: the share of a stretched space with which the steps end.
    pub fn pending_extra(&self, device: &Device) -> Length {
        extra_dots(device, self.extra)
    }

    /// Says that the next glyph carries the character spacing `spacing`, which the edge check
    /// and the restarts count in its exact advance as the quirk `CharacterSpacingCount` says.
    pub const fn with_character_spacing(&mut self, spacing: Length) {
        self.spacing = spacing;
    }

    /// Says that the edge check and the segment rule count `extra` (a numerator over a positive
    /// denominator in half-EMUs) in the next glyph's exact advance, beside its advance, which
    /// the device's step and the line keep: a synthetic bold's extra under
    /// `SyntheticBoldWidth::CountsAFontUnit`. Nothing with `None`.
    pub fn with_counted_extra(&mut self, extra: Option<(i64, i64)>) {
        self.counted_extra = extra.map_or(Exact::ZERO, |(lost, per)| Exact::new(lost, per));
    }

    /// Says that the next glyph is a stretched space of a justified line, and that the edge
    /// check `GlyphEdgeCheck::Exact` counts `excess` (a numerator over a positive denominator in
    /// half-EMUs) in its exact advance beside the share that the line gives it, and so in the
    /// exact places of the glyphs after it, until the steps start again. From that start on,
    /// the check counts no excess of a later stretched space. The device's steps, the segment
    /// rule and the line keep the share that the line gives. Nothing with `None`.
    pub fn with_counted_share(&mut self, excess: Option<(i128, i128)>) {
        self.share = excess.map(|(lost, per)| {
            if per > 0 {
                Exact::reduced(lost, per)
            } else {
                Exact::ZERO
            }
        });
    }

    /// Says that the edge check moves the next glyph one dot right when its right edge ends
    /// `ease` less than the limit short of its exact edge, or more: a synthetic bold glyph under
    /// `SyntheticBoldWidth::CountsAFontUnit`. Its check on the other side keeps the limit.
    pub const fn with_short_ease(&mut self, ease: Length) {
        self.short_ease = ease;
    }

    /// Says that the next glyph's advance, which it is placed with, holds `extra`, which its
    /// own edge check counts in whole dots on its own.
    pub fn with_extra(&mut self, extra: GlyphExtra) {
        self.stretched = extra;
    }

    /// Says whether the line's first glyph hands its dot less its exact place on to the glyph
    /// that starts the next segment, as it does on a line that starts at its indent.
    pub const fn hands_on_start(&mut self, hands_on: bool) {
        self.line_hands_on = hands_on;
    }

    /// Whether the glyph placed last started the steps, as the line's first glyph, the first
    /// after a tab or a gap, or the first of a segment does: it went to the nearest dot of its
    /// exact place and was not stepped from the glyph before.
    #[must_use]
    pub const fn started(&self) -> bool {
        self.stepped == 0
    }

    /// `by` when the next glyph starts the steps, as the line's first glyph or the first after a
    /// tab or a gap does, and zero when a glyph lies before it to step from.
    #[must_use]
    pub const fn when_starting(&self, by: Length) -> Length {
        if self.previous.is_none() {
            by
        } else {
            Length::ZERO
        }
    }

    /// Moves every exact place that the steps hold by `by`, as if the glyphs placed so far lay
    /// `by` further, and keeps their dots: the steps then go on with exact places counted
    /// from another place.
    pub fn move_exact(&mut self, by: Length) {
        if let Some((x, at)) = self.previous {
            self.previous = Some((x + by, at));
        }
        self.anchor.0 += by;
        if let Some(segment) = self.segment.as_mut() {
            segment.first += by;
            segment.counted += by;
        }
        if let Some(place) = self.start_place.as_mut() {
            *place += by;
        }
        self.start -= by;
        self.shift -= by;
    }

    /// What the edge check found at the glyph that [`Self::place`] placed last, once: `None`
    /// when the steps started again at that glyph, which places it with no check, or when no
    /// glyph was placed since the last call.
    pub const fn take_checked(&mut self) -> Option<EdgeCheck> {
        self.checked.take()
    }

    /// The place that the steps rounded to the dot of the glyph that [`Self::place`] placed
    /// last, once, when they started again at that glyph: its exact place, or for a glyph that
    /// starts a segment the place that the segment rule counts, with what it carries on and a
    /// stop's nudge. `None` when the steps placed that glyph from the glyph before, or when no
    /// glyph was placed since the last call.
    pub const fn take_start_place(&mut self) -> Option<Length> {
        self.start_place.take()
    }

    /// Says that the next glyph, when the steps place it from the glyph before, goes to the dot
    /// nearest to its exact place as the edge check counts that place from the glyph that
    /// started the steps ([`Self::end`]), instead of its step and the edge check's move; the
    /// glyphs after it step from it. The edge check's record of it holds the dots that this
    /// moves it from its step.
    pub const fn at_nearest_exact(&mut self) {
        self.next_place = NextPlace::NearestExact;
    }

    /// Starts again, so that the next glyph goes to the nearest dot of its exact place. The edge
    /// check's count of the shares that [`Self::with_counted_share`] gives goes on past it.
    pub const fn restart(&mut self) {
        self.previous = None;
    }

    /// Starts again at the next glyph's step: the next glyph takes its step from the glyph
    /// before without the edge check's move, starts a new segment, and the edge check counts the
    /// exact places after it from that dot.
    pub const fn restart_at_step(&mut self) {
        self.next_place = NextPlace::Restepped;
        self.segment = None;
    }

    /// Says that the next glyph is the first glyph of a footnote's reference mark: under
    /// `NoteMarkPlace::NearestExact`, it goes to the dot nearest to its exact place
    /// ([`Self::at_nearest_exact`]); under `Stepped`, it steps as any glyph does.
    pub const fn at_note_mark(&mut self, device: &Device) {
        self.at_note_mark_place(device, NextPlace::NearestExact);
    }

    /// Says that the next glyph is the first glyph of an auto-numbered endnote reference: under
    /// `NoteMarkPlace::NearestExact`, it goes to the dot nearest to its exact place and its
    /// device width advances the edge-check anchor without adding drift.
    pub const fn at_endnote_start(&mut self, device: &Device) {
        self.at_note_mark_place(device, NextPlace::EndnoteStart);
    }

    /// Says that the next glyph is a later glyph of an auto-numbered endnote reference or a glyph
    /// of an endnote's own mark: under `NoteMarkPlace::NearestExact`, it steps by its device width
    /// without an edge-check move and advances the edge-check anchor by its device width.
    pub const fn at_endnote_step(&mut self, device: &Device) {
        self.at_note_mark_place(device, NextPlace::EndnoteStep);
    }

    const fn at_note_mark_place(&mut self, device: &Device, place: NextPlace) {
        // quirk: NoteMarkPlace::NearestExact (src/quirks.rs)
        match device.quirks.note_mark_place {
            NoteMarkPlace::Stepped => {}
            NoteMarkPlace::NearestExact => self.next_place = place,
        }
    }

    /// Says that a note's own mark ended: under `NoteStartSteps::SteppedAfterMark`, the steps
    /// start again at the next glyph's step ([`Self::restart_at_step`]); under `Continued`, they
    /// go on.
    pub const fn after_note_mark(&mut self, device: &Device) {
        // quirk: NoteStartSteps::SteppedAfterMark (src/quirks.rs)
        match device.quirks.note_start_steps {
            NoteStartSteps::Continued => {}
            NoteStartSteps::SteppedAfterMark => self.restart_at_step(),
        }
    }

    /// Starts again after a tab (a tab character, a positional tab) or the gap after a list
    /// label (its tab, or the gap of legacy numbering): the next glyph starts a segment as the
    /// line's first glyph does under each segment rule. It goes to the nearest dot of its exact
    /// place, the segments count from its exact place on, and it hands on its rounding when the
    /// line's first glyph does.
    pub const fn tab(&mut self) {
        self.previous = None;
        self.share_count = self.share_count.restarted();
        self.segment = None;
    }

    /// Says that the next glyph, the first after a tab, goes to the dot of its exact place
    /// moved by `nudge`: after a left stop, the difference between the halves of the stop's own
    /// conversion and those of the line's start (`Device::line_start`), so that it takes the
    /// dot of its stop past the column's edge.
    pub const fn with_stop_nudge(&mut self, nudge: Length) {
        self.nudge = nudge;
    }

    /// Starts again after another gap with a width, such as an inline object: the
    /// next glyph goes to the nearest dot of its exact place and counts in the segment that the
    /// device's segment rule gives after such a gap (`SegmentRule::after_gap`). Where the rule
    /// starts a segment there, as the line's first glyph does, the glyph hands on its rounding
    /// when that glyph does.
    pub fn gap(&mut self, device: &Device) {
        self.previous = None;
        self.share_count = self.share_count.restarted();
        self.nudge = Length::ZERO;
        self.segment = rule(device).after_gap(self.segment);
    }

    /// The whole-dot width by which right-edge steps advance across a DrawingML inline object of
    /// `width`: `Some(device.floor(width.toward_zero_whole(UNITS_PER_TWIP)))` where the device's
    /// segment rule continues across inline objects (`GlyphSegments::FromRestart`), else `None`.
    #[must_use]
    pub fn inline_object_step(device: &Device, width: Length) -> Option<Length> {
        rule(device)
            .continues_after_inline_object()
            .then(|| device.floor(width.toward_zero_whole(Length::UNITS_PER_TWIP)))
    }

    /// Continues after a DrawingML inline object of whole-dot width `width`: where the device's
    /// segment rule continues across inline objects (`GlyphSegments::FromRestart`), shifts the
    /// active segment and edge-check anchor by `width` (so the object's whole dots neither count
    /// toward the text segment nor scale at the device's rounded dots per point) and places the
    /// next glyph at the dot nearest to its counted exact place ([`Self::at_nearest_exact`]);
    /// otherwise restarts as [`Self::gap`].
    pub fn after_inline_object(&mut self, device: &Device, width: Length) {
        if rule(device).continues_after_inline_object() {
            if let Some(segment) = &mut self.segment {
                segment.first += width;
                segment.counted += width;
                self.anchor.0 += width;
                self.anchor.1 += width;
            }
            self.at_nearest_exact();
        } else {
            self.gap(device);
        }
    }

    /// Says that the next glyphs have the nominal size `size` and are drawn at `drawn`, so
    /// that their steps count at the drawn size.
    pub fn at_size(&mut self, size: Length, drawn: Length) {
        self.scale = (size > Length::ZERO && drawn != size).then_some((size, drawn));
    }

    /// The dot where the line's written text ends, whose exact end is `x`: the
    /// nearest dot of the exact place as the edge check counts it at the device's rounded dots
    /// per point: from the dot of the current segment's first glyph
    /// (`GlyphEdgeCheck::RoundedWithTie`), or from the dot of the glyph that started the steps,
    /// with what rounding took from the advances since that glyph (`GlyphEdgeCheck::Exact`).
    ///
    /// `None` when the line has placed no glyph. Under `GlyphEdgeCheck::Exact`, `None` also
    /// stands for a place beyond the range of an `i64`, which cannot come for a line whose
    /// lengths lie within `Length::FILE_LIMIT`: the place counts `x` from the glyph that started
    /// the steps at a scale near 1 ([`Device::exact_scale`], such as 12,801/12,800), with the
    /// parts of a half-EMU that rounding took from the advances, so it lies near `x`.
    #[must_use]
    pub fn end(&self, device: &Device, x: Length) -> Option<Length> {
        let first = self.segment?.first;
        // quirk: GlyphEdgeCheck (src/quirks.rs), whose variant the device carries.
        match device.glyph_edge_check() {
            GlyphEdgeCheck::RoundedWithTie => {
                Some(device.snap(tied_place(device, first, x) + self.shift))
            }
            GlyphEdgeCheck::Exact => {
                // The exact place counts in fractions of a half-EMU with more than 64 bits.
                let (anchor, at) = self.anchor;
                let (counted, per) = self.drift.counted(x - anchor, device.exact_scale());
                let place = i128::from(at.units()) * per + counted;
                device.count_exact(place, per).map(|dots| device.dots(dots))
            }
        }
    }

    /// The dot where a glyph whose exact place is `x` would lie as the first glyph after a tab:
    /// the nearest dot of that place moved by the stop's nudge ([`Self::with_stop_nudge`]).
    #[must_use]
    pub fn stop_end(&self, device: &Device, x: Length) -> Length {
        device.snap(x + self.nudge)
    }

    /// The end of a line's written text whose exact end is `written` and that ends with a tab
    /// or a list label's gap that no glyph follows: the dot where a glyph after it would lie
    /// ([`Self::stop_end`]), under `AlignedTabEnd::StopDot`; `None` under `Unended`.
    #[must_use]
    pub fn tab_end(&self, device: &Device, written: Length) -> Option<Length> {
        // quirk: AlignedTabEnd::StopDot (src/quirks.rs)
        match device.quirks.aligned_tab_end {
            AlignedTabEnd::StopDot => Some(self.stop_end(device, written)),
            AlignedTabEnd::Unended => None,
        }
    }

    /// The segment of the next glyph, whose exact place is `x` and whose advance is `advance`,
    /// with the segment width `segment`: the restart when the device's segment rule starts the
    /// next segment at the glyph, the exact place of the first glyph of the glyph's segment, and
    /// what the way the edge check counts the glyph's parts adds to its exact advance.
    fn next_segment(
        &mut self,
        device: &Device,
        (x, advance): (Length, Length),
        segment: Length,
    ) -> (Option<Restart>, Length, Exact) {
        if self.segment.is_none() {
            self.counted_excess = Exact::ZERO;
            self.segment_rounding = Exact::ZERO;
            self.segment_share = Exact::ZERO;
        }
        let current = *self.segment.get_or_insert(Segment {
            first: x,
            end: segment,
            counted: x,
        });
        // What the way the edge check counts the glyph's parts adds to its exact advance (its
        // character spacing), and what the glyphs of the segment before it added, which the
        // segment rule counts in the glyph's exact place.
        // quirk: CharacterSpacingCount (src/quirks.rs)
        let own_excess = spacing_excess(device, std::mem::take(&mut self.spacing))
            .plus(std::mem::take(&mut self.counted_extra));
        let excess_before = self.counted_excess.rounded();
        let excess_after = self.counted_excess.plus(own_excess).rounded();
        // The device's segment rule says whether the glyph starts the next segment, at which
        // exact place, and what it hands on.
        let restarted = rule(device)
            .next(
                device,
                current,
                (x + excess_before, advance + excess_after - excess_before),
                segment,
                self.start,
            )
            .map(|mut restart| {
                // The next segment counts from the glyph's own exact place.
                restart.segment.first -= excess_before;
                // quirk: RestartCount (src/quirks.rs)
                if device.quirks.restart_count == crate::quirks::RestartCount::EdgeCheckPlaces {
                    let added = self.segment_rounding.plus(self.segment_share);
                    let (place, rounded_up) =
                        exact_restart_place(device, current, x + excess_before, added)
                            .unwrap_or((restart.place, false));
                    restart.place = place;
                    restart.rounded_up = rounded_up;
                    restart.segment.counted = place;
                }
                restart
            });
        let first = restarted.map_or(current.first, |restart| restart.segment.first);
        if let Some(restart) = restarted {
            self.segment = Some(restart.segment);
            self.restart();
            self.counted_excess = own_excess;
            self.segment_rounding = Exact::ZERO;
            self.segment_share = Exact::ZERO;
        } else {
            self.counted_excess = self.counted_excess.plus(own_excess);
        }
        (restarted, first, own_excess)
    }

    /// The place of the next glyph, whose exact place is `x` and whose advance is `advance`, on
    /// `device` with the numbers `(bias, limit, segment)`.
    pub fn place(
        &mut self,
        device: &Device,
        (bias, limit, segment): (Length, Length, Length),
        x: Length,
        advance: Length,
    ) -> Length {
        // Whether the glyph is the first of a line that starts at its indent, which hands its
        // dot less its exact place on as a glyph that starts a segment and carries does
        // (`Restart::carried`). A centered or a right-aligned line of this target starts on
        // a dot (`Device::aligned_shift`), so its first glyph has nothing to hand on.
        let starts_line = self.segment.is_none() && self.line_hands_on;
        let (restarted, first, own_excess) = self.next_segment(device, (x, advance), segment);
        // A distance at the drawn size.
        let scale = self.scale;
        let at_drawn_size = move |distance: Length| drawn_distance(scale, distance);
        // The step from the glyph before counts at the drawn size of that glyph on a target
        // whose profile says so.
        // quirk: DeviceAdvance (src/quirks.rs)
        let before_scale = std::mem::replace(&mut self.before_scale, scale);
        let out_scale = match device.quirks.device_advance {
            crate::quirks::DeviceAdvance::ExactAdvances => scale,
            crate::quirks::DeviceAdvance::ExtrasOnTheirOwn => before_scale,
        };
        let step_with =
            move |distance: Length, bias: Length| device.snap(at_drawn_size(distance) + bias);
        let step = |distance: Length| step_with(distance, bias);
        // A glyph that steps without the bias rounds its own step and the step to the glyph
        // after it so.
        let without_bias = std::mem::take(&mut self.without_bias);
        let before_without_bias = std::mem::replace(&mut self.before_without_bias, without_bias);
        let unbiased = |without: bool| if without { Length::ZERO } else { bias };
        let advance_rounding = std::mem::take(&mut self.rounding);
        self.segment_rounding = self.segment_rounding.plus(advance_rounding);
        let rounding = advance_rounding.plus(own_excess);
        // What the edge check counts in the glyph's exact advance: its rounding, and the excess
        // of a stretched space in the steps' first count.
        let share = self.counted_share();
        self.segment_share = self.segment_share.plus(share);
        let counted = rounding.plus(share);
        let extra = std::mem::take(&mut self.extra);
        let stretched = std::mem::take(&mut self.stretched);
        let widens = std::mem::take(&mut self.measured).map_or(Length::ZERO, |(width, alone)| {
            device.dots(width) - step(alone)
        });
        let widened = std::mem::replace(&mut self.widened, widens);
        let nudge = std::mem::take(&mut self.nudge);
        let next_place = std::mem::take(&mut self.next_place);
        let short_ease = std::mem::take(&mut self.short_ease);
        self.stepped = if self.previous.is_none() {
            0
        } else {
            self.stepped.saturating_add(1)
        };
        // The own step of a glyph with an extra is its width's step and its extra in
        // whole dots, as the step to the glyph after it counts them.
        let own = step_with(advance - stretched.length(), unbiased(without_bias))
            + extra_dots(device, stretched);
        let at = match self.previous {
            None => {
                let exact = restarted.map_or(x, |restart| restart.place);
                let carried = restarted.and_then(|restart| restart.carried);
                let nudge = if restarted.is_none() {
                    nudge
                } else {
                    Length::ZERO
                };
                let start_place = exact + carried.unwrap_or(Length::ZERO) + nudge;
                // A glyph whose counted place was rounded up onto a half dot lies below it, and
                // goes to the dot below: one half-EMU less moves only a place on a half dot.
                let at = if restarted.is_some_and(|restart| restart.rounded_up) {
                    device.snap(start_place - Length::from_units(1))
                } else {
                    device.snap(start_place)
                };
                self.start_place = Some(start_place);
                if carried.is_some() || starts_line {
                    self.start = at - exact;
                }
                self.shift = at - tied_place(device, first, x);
                self.set_first_anchor(next_place, (x, at), (advance, own + widens), counted);
                self.checked = None;
                at
            }
            Some((exact, drawn)) => {
                let justified = extra_dots(device, extra);
                let out = device.snap(
                    drawn_distance(out_scale, x - exact - extra.length())
                        + unbiased(before_without_bias),
                );
                let at = drawn + out + justified + widened;
                match next_place {
                    NextPlace::Restepped => self.restepped(device, first, (x, at), counted),
                    NextPlace::EndnoteStart | NextPlace::EndnoteStep => {
                        self.place_endnote(device, next_place, (x, advance), (own + widens, at))
                    }
                    NextPlace::Stepped | NextPlace::NearestExact => {
                        let right = at + own + widens;
                        let near = next_place == NextPlace::NearestExact;
                        self.checked_place(
                            device,
                            (first, x, advance),
                            (at, right),
                            (limit, short_ease),
                            (counted, rounding, near),
                        )
                    }
                }
            }
        };
        self.previous = Some((x, at));
        at
    }

    /// Sets the anchor and drift for the first glyph of a run of steps; an endnote mark glyph
    /// advances the anchor by its device width without adding drift.
    fn set_first_anchor(
        &mut self,
        next_place: NextPlace,
        (x, at): (Length, Length),
        (advance, device_width): (Length, Length),
        counted: Exact,
    ) {
        if matches!(next_place, NextPlace::EndnoteStart | NextPlace::EndnoteStep) {
            self.anchor = (x + advance, at + device_width);
            self.drift = Exact::ZERO;
        } else {
            self.anchor = (x, at);
            self.drift = counted;
        }
    }

    /// Places a glyph of an auto-numbered endnote reference or own mark: snaps the reference's
    /// first glyph to the nearest exact dot, steps all later glyphs by pure device width without
    /// edge-check moves, and advances the edge-check anchor by the glyph's device width.
    fn place_endnote(
        &mut self,
        device: &Device,
        next_place: NextPlace,
        (x, advance): (Length, Length),
        (device_width, at): (Length, Length),
    ) -> Length {
        let placed = if next_place == NextPlace::EndnoteStart {
            self.end(device, x).unwrap_or(at)
        } else {
            at
        };
        self.anchor.0 += advance;
        self.anchor.1 += device_width;
        self.start_place = None;
        self.checked = None;
        placed
    }

    /// The place of a glyph that the steps placed at `at` from the glyph before, with its right
    /// edge at `right`: moved by the edge check, or to the nearest dot of its exact place when
    /// `near` says so.
    fn checked_place(
        &mut self,
        device: &Device,
        (first, x, advance): (Length, Length, Length),
        (at, right): (Length, Length),
        (limit, short_ease): (Length, Length),
        (counted, rounding, near): (Exact, Exact, bool),
    ) -> Length {
        // The nearest dot of the exact place, before the glyph's own rounding joins what the
        // edge check counts.
        // quirk: NoteMarkPlace::NearestExact (src/quirks.rs)
        let nearest = near.then(|| self.end(device, x)).flatten();
        // quirk: GlyphEdgeCheck (src/quirks.rs), whose variant the device carries.
        let (moves, edge) = match device.glyph_edge_check() {
            GlyphEdgeCheck::RoundedWithTie => {
                self.tied_moves(device, first, (x, advance), (right, limit, short_ease))
            }
            GlyphEdgeCheck::Exact => {
                self.exact_moves(device, (x, advance), counted, (right, limit, short_ease))
            }
        };
        let moves = nearest.map_or(moves, |nearest| {
            device.count(nearest - at, Rounding::HalfUp)
        });
        self.start_place = None;
        self.checked = edge.map(|(edge, edge_thousandths)| EdgeCheck {
            edge,
            edge_thousandths,
            rounding_thousandths: rounding.thousandths(),
            moves,
        });
        at + device.dots(moves)
    }

    /// The place of a glyph, whose exact place is `x`, at its step `at` from the glyph before
    /// without the edge check's move: the edge check counts the exact places after it from that
    /// dot, as from a glyph that started the steps ([`Self::restart_at_step`]).
    fn restepped(
        &mut self,
        device: &Device,
        first: Length,
        (x, at): (Length, Length),
        counted: Exact,
    ) -> Length {
        self.shift = at - tied_place(device, first, x);
        self.anchor = (x, at);
        self.drift = counted;
        self.checked = None;
        self.start_place = None;
        self.stepped = 0;
        at
    }

    /// What the edge check counts beside the share of the glyph that the steps place now: the
    /// excess that [`Self::with_counted_share`] gave, unless the steps started again after a
    /// stretched space, and nothing for a glyph that is no stretched space.
    fn counted_share(&mut self) -> Exact {
        match (self.share.take(), self.share_count) {
            (Some(excess), ShareCount::Before | ShareCount::Counting) => {
                self.share_count = ShareCount::Counting;
                excess
            }
            _ => Exact::ZERO,
        }
    }

    /// The dots by which the edge check `GlyphEdgeCheck::RoundedWithTie` moves the glyph whose
    /// exact place is `x` and whose advance is `advance`, where its right edge on the device is
    /// `right`: -1 when the edge ends more than `limit` past its exact edge, 1 when it ends
    /// `limit` less `ease` or more short of it, else 0, with how far it ends past that exact
    /// edge in half-EMUs and in thousandths of a half-EMU. The exact places count from the
    /// segment's first glyph `first` at the device's rounded dots per point, from the advances
    /// as F-Office keeps them, and an edge within the tie of a limit counts as on it.
    fn tied_moves(
        &self,
        device: &Device,
        first: Length,
        (x, advance): (Length, Length),
        (right, limit, ease): (Length, Length, Length),
    ) -> (i64, Option<(Length, i64)>) {
        let (numerator, denominator) = device.exact_scale();
        let exact = tied_place(device, first, x) + (advance * numerator).div_round(denominator);
        let edge = right - (exact + self.shift);
        // An edge that F-Office's rounded lengths leave just off the limit lies on it in
        // Word's exact arithmetic.
        let moves = moves(
            edge > limit + params::GLYPH_EDGE_TIE,
            edge <= ease - limit + params::GLYPH_EDGE_TIE,
        );
        (
            moves,
            Some((edge, edge.units().saturating_mul(THOUSANDTHS))),
        )
    }

    /// The dots by which the edge check `GlyphEdgeCheck::Exact` moves the glyph whose exact
    /// place is `x`, whose advance is `advance` and whose advance rounding took `rounding`
    /// from, where its right edge on the device is `right`, with the limit `limit` and the ease
    /// `ease` of its short side, as [`Self::tied_moves`] says with no tie, with how far the edge
    /// ends past its exact edge to the nearest half-EMU and to the nearest thousandth of a
    /// half-EMU. The exact places count from the glyph that started the steps, at the device's
    /// rounded dots per point, with what rounding took from the advances since that glyph and
    /// from the glyph's own, and the edge compares with the limits exactly.
    fn exact_moves(
        &mut self,
        device: &Device,
        (x, advance): (Length, Length),
        rounding: Exact,
        (right, limit, ease): (Length, Length, Length),
    ) -> (i64, Option<(Length, i64)>) {
        // The edge and the limits count in fractions of a half-EMU with more than 64 bits.
        let (anchor, from) = self.anchor;
        let lost = self.drift.plus(rounding);
        let (counted, per) = lost.counted(x - anchor + advance, device.exact_scale());
        let edge = i128::from((right - from).units()) * per - counted;
        self.drift = lost;
        let near = i64::try_from(div_round_i128(edge, per))
            .ok()
            .map(Length::from_units);
        let thousandths = i64::try_from(div_round_i128(edge * i128::from(THOUSANDTHS), per)).ok();
        let short = i128::from((limit - ease).units()) * per;
        let limit = i128::from(limit.units()) * per;
        (moves(edge > limit, edge <= -short), near.zip(thousandths))
    }
}

/// The exact place of a glyph at `x` that starts the segment after `segment`, under
/// `RestartCount::EdgeCheckPlaces`: from the counted place of the segment's first glyph, with
/// the distance from that glyph plus what the edge check counted beside the rounded advances of
/// the segment's glyphs before it (`rounding`: what rounding took from those advances and the
/// counted shares of its stretched spaces), at the device's rounded dots per point, to the
/// nearest half-EMU, with whether that rounding went up.
/// `None` for a place beyond the range of an `i64`, which a line within `Length::FILE_LIMIT`
/// cannot reach.
fn exact_restart_place(
    device: &Device,
    segment: Segment,
    x: Length,
    rounding: Exact,
) -> Option<(Length, bool)> {
    let (counted, per) = rounding.counted(x - segment.first, device.exact_scale());
    let distance = div_round_i128(counted, per);
    let rounded_up = counted < distance * per;
    i64::try_from(distance)
        .ok()
        .map(|distance| (segment.counted + Length::from_units(distance), rounded_up))
}

/// A glyph's extra `extra` in whole dots of `device`, as the device steps it apart from the
/// glyph's width: a justified space's share at the scale of the edge check's exact places
/// ([`Device::exact_scale`]) to the nearest dot, a half dot up, a character spacing alone
/// as the quirk `DeviceAdvance` says, and a share with a spacing summed or each on its own as it
/// says.
fn extra_dots(device: &Device, extra: GlyphExtra) -> Length {
    match extra {
        GlyphExtra::Justified(length) => share_dots(device, length),
        // quirk: DeviceAdvance (src/quirks.rs)
        GlyphExtra::SpacedShare { share, spacing } => match device.quirks.device_advance {
            crate::quirks::DeviceAdvance::ExactAdvances => share_dots(device, share + spacing),
            crate::quirks::DeviceAdvance::ExtrasOnTheirOwn => {
                share_dots(device, share) + spacing_dots(device, spacing)
            }
        },
        GlyphExtra::Spacing(length) => spacing_dots(device, length),
    }
}

/// A justified space's share `length` at the edge check's scale, to the nearest dot of
/// `device`, a half dot up.
fn share_dots(device: &Device, length: Length) -> Length {
    let (numerator, denominator) = device.exact_scale();
    device.snap((length * numerator).div_round(denominator))
}

/// A character spacing `length` alone, to whole dots of `device` as the quirk `DeviceAdvance`
/// says: a half dot up, or away from zero.
fn spacing_dots(device: &Device, length: Length) -> Length {
    // quirk: DeviceAdvance (src/quirks.rs)
    match device.quirks.device_advance {
        crate::quirks::DeviceAdvance::ExactAdvances => device.snap(length),
        crate::quirks::DeviceAdvance::ExtrasOnTheirOwn => device.snap_half_away(length),
    }
}

/// What a glyph's extra holds, which the steps add in whole dots apart from the glyph's width
/// ([`EdgeSteps::after_extra`], [`EdgeSteps::with_extra`]): the two round apart. The length is
/// negative when the extra narrows the glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GlyphExtra {
    /// A run's character spacing alone, which steps on its own.
    Spacing(Length),
    /// A justified space's share of the line's free space.
    Justified(Length),
    /// A justified space's share of the line's free space and the character spacing that the
    /// space carries, which round together or apart as the quirk `DeviceAdvance` says.
    SpacedShare {
        /// The share.
        share: Length,
        /// The space's character spacing.
        spacing: Length,
    },
}

impl GlyphExtra {
    /// No extra.
    pub const NONE: Self = Self::Spacing(Length::ZERO);

    /// The extra of a glyph that carries the share `stretch` of a justified line's free space
    /// and the character spacing `spacing`: a justified share when `stretch` is not zero, with
    /// the spacing beside it when that is not zero either.
    #[must_use]
    pub fn of(stretch: Length, spacing: Length) -> Self {
        if stretch == Length::ZERO {
            Self::Spacing(spacing)
        } else if spacing == Length::ZERO {
            Self::Justified(stretch)
        } else {
            Self::SpacedShare {
                share: stretch,
                spacing,
            }
        }
    }

    /// The length of the extra.
    #[must_use]
    pub fn length(self) -> Length {
        match self {
            Self::Spacing(length) | Self::Justified(length) => length,
            Self::SpacedShare { share, spacing } => share + spacing,
        }
    }
}

impl Default for GlyphExtra {
    fn default() -> Self {
        Self::NONE
    }
}

/// What a glyph's character spacing `spacing` adds to its exact advance in the edge check and the
/// restarts of `device`, as the quirk `CharacterSpacingCount` says: nothing under `Exact`, and
/// under `NearestUnit` the nearest whole number of units of
/// `params::CHARACTER_SPACING_UNITS_PER_POINT`, half away from zero, less the spacing.
fn spacing_excess(device: &Device, spacing: Length) -> Exact {
    match device.quirks.character_spacing_count {
        crate::quirks::CharacterSpacingCount::Exact => Exact::ZERO,
        crate::quirks::CharacterSpacingCount::NearestUnit => {
            let per_point = i128::from(Length::UNITS_PER_POINT);
            let units = i128::from(params::CHARACTER_SPACING_UNITS_PER_POINT);
            let scaled = i128::from(spacing.units()) * units;
            let whole = (scaled.abs() * 2 + per_point).div_euclid(per_point * 2);
            let whole = if scaled < 0 { -whole } else { whole };
            Exact::reduced(whole * per_point - scaled, units)
        }
    }
}

/// What the edge check of `device` counts in a glyph's exact advance beside its character
/// spacing `spacing` ([`spacing_excess`]), as a numerator over a positive denominator in
/// half-EMUs.
#[must_use]
pub fn counted_spacing_excess(device: &Device, spacing: Length) -> (i64, i64) {
    let excess = spacing_excess(device, spacing);
    match (i64::try_from(excess.lost), i64::try_from(excess.per)) {
        (Ok(lost), Ok(per)) => (lost, per),
        _ => (0, 1),
    }
}

/// The exact place `x` as the edge check `GlyphEdgeCheck::RoundedWithTie` counts it: from the
/// segment's first glyph `first` at the device's rounded dots per point.
fn tied_place(device: &Device, first: Length, x: Length) -> Length {
    let (numerator, denominator) = device.exact_scale();
    first + ((x - first) * numerator).div_round(denominator)
}

/// The dots by which the edge check moves a glyph: -1 when its edge ends too far past its
/// exact edge (`past`), 1 when it ends too far short of it (`short`), else 0.
const fn moves(past: bool, short: bool) -> i64 {
    if past {
        -1
    } else if short {
        1
    } else {
        0
    }
}

/// A length of the edge check in half-EMUs, kept exact: `lost / per`, with `per` positive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Exact {
    lost: i128,
    per: i128,
}

impl Default for Exact {
    fn default() -> Self {
        Self::ZERO
    }
}

impl Exact {
    const ZERO: Self = Self { lost: 0, per: 1 };

    /// `lost / per`, or zero for a denominator that is not positive.
    fn new(lost: i64, per: i64) -> Self {
        if per <= 0 {
            return Self::ZERO;
        }
        Self::reduced(i128::from(lost), i128::from(per))
    }

    fn reduced(lost: i128, per: i128) -> Self {
        let (lost, per) = lowest_terms(lost, per);
        Self { lost, per }
    }

    /// The length in thousandths of a half-EMU, to the nearest thousandth.
    fn thousandths(self) -> i64 {
        i64::try_from(div_round_i128(
            self.lost * i128::from(THOUSANDTHS),
            self.per,
        ))
        .unwrap_or(0)
    }

    /// The length to the nearest half-EMU.
    fn rounded(self) -> Length {
        Length::from_units(i64::try_from(div_round_i128(self.lost, self.per)).unwrap_or(0))
    }

    /// The sum of two lengths.
    fn plus(self, other: Self) -> Self {
        Self::reduced(
            self.lost * other.per + other.lost * self.per,
            self.per * other.per,
        )
    }

    /// The length `length` plus this one, scaled by `numerator / denominator`, as a numerator
    /// in half-EMUs over the denominator that it returns.
    fn counted(self, length: Length, (numerator, denominator): (i64, i64)) -> (i128, i128) {
        let numerator = i128::from(numerator) * (i128::from(length.units()) * self.per + self.lost);
        (numerator, i128::from(denominator) * self.per)
    }
}

#[cfg(test)]
pub(in crate::grid) mod tests {
    use crate::grid::{Device, EdgeSteps, GlyphExtra};
    use crate::quirks::{CharacterSpacingCount, DeviceAdvance, GlyphEdgeCheck};
    use f_office_units::Length;

    #[test]
    fn ends_a_line_at_its_exact_end_counted_from_the_segments_first_dot() {
        let device = Device::per_inch(600).unwrap();
        let unit = device.dots(1).units();
        let u = Length::from_units;
        let mut edge = EdgeSteps::default();
        // No glyph: no end.
        assert_eq!(edge.end(&device, u(unit * 5)), None);
        // The first glyph lies 0.4 dots past a dot and goes down to it, so the exact end
        // counts from that dot: 52.2 dots from the exact start are dot 52 from the first
        // glyph's dot, where the exact end alone, 62.6 dots, would round to dot 63.
        let start = unit * 10 + unit * 4 / 10;
        let numbers = (u(254), u(9525), u(unit * 1024));
        let at = edge.place(&device, numbers, u(start), u(unit * 20));
        assert_eq!(at, u(unit * 10));
        let end = edge.end(&device, u(start + unit * 52 + unit * 2 / 10));
        assert_eq!(end, Some(u(unit * 62)));
    }

    /// Segments of 256 pt.
    pub(in crate::grid) const SEGMENT: i64 = 256 * Length::UNITS_PER_POINT;

    /// The bias, the limit and the segment of the tests' device of 600 dots per inch: 0.005 pt,
    /// 0.18 pt and 1,024 dots, as [`EdgeSteps::place`] takes them.
    pub(in crate::grid) const NUMBERS_AT_600_DPI: (Length, Length, Length) = (
        Length::from_units(127),
        Length::from_units(4_572),
        Length::from_units(1_024 * 3_048),
    );

    /// A bias of 0.01 pt and a limit of 0.375 pt on a device of 288 dots per inch, with
    /// segments of `segment` half-EMUs, as [`EdgeSteps::place`] takes them.
    pub(in crate::grid) const fn quarter_numbers(segment: i64) -> (Length, Length, Length) {
        (
            Length::from_units(254),
            Length::from_units(9525),
            Length::from_units(segment),
        )
    }

    /// The places of `count` copies of a glyph of `advance` half-EMUs from 72 pt, in hundredths
    /// of a point from the first, on a device of 288 dots per inch with a bias of 0.01 pt and a
    /// limit of 0.375 pt, and segments of `segment` half-EMUs, under the edge check with the tie
    /// (`GlyphEdgeCheck::RoundedWithTie`).
    pub(in crate::grid) fn quarter_places(advance: i64, count: usize, segment: i64) -> Vec<i64> {
        checked_quarter_places(
            GlyphEdgeCheck::RoundedWithTie,
            (advance, None),
            count,
            segment,
        )
    }

    /// [`quarter_places`] under the edge check `check`, of a glyph whose advance rounding took
    /// `rounding` from, as a numerator over a denominator in half-EMUs.
    fn checked_quarter_places(
        check: GlyphEdgeCheck,
        (advance, rounding): (i64, Option<(i64, i64)>),
        count: usize,
        segment: i64,
    ) -> Vec<i64> {
        let device = Device::per_inch_with(288, |p| p.with_variant(check));
        let mut edge = EdgeSteps::default();
        let start = 72 * Length::UNITS_PER_POINT;
        let u = Length::from_units;
        let places: Vec<i64> = (0..count)
            .map(|k| {
                let x = start + i64::try_from(k).unwrap() * advance;
                edge.with_advance_rounding(rounding);
                edge.place(&device, quarter_numbers(segment), u(x), u(advance))
                    .units()
            })
            .collect();
        places
            .iter()
            .map(|p| (p - places[0]) * 100 / Length::UNITS_PER_POINT)
            .collect()
    }

    #[test]
    fn puts_a_told_glyph_on_the_dot_nearest_to_its_exact_place() {
        // Glyphs of 48.4 dots on a device of 600 dots per inch under the exact edge check step
        // 48 dots each. The third lies 96 dots from the first, 0.8 dots short of its exact
        // place and inside the edge check's limit, so the steps keep it there; the edge check
        // moves the fourth, 1.6 dots short, one dot right. Told to, the third goes to dot 97,
        // the nearest to its exact place, and the fourth steps 48 dots from there.
        let device = Device::per_inch_with(600, |p| p.with_variant(GlyphEdgeCheck::Exact));
        let dot = device.dots(1).units();
        let advance = dot * 484 / 10;
        let u = Length::from_units;
        let places = |told: Option<i64>| {
            let mut edge = EdgeSteps::default();
            (0..4)
                .map(|k| {
                    if Some(k) == told {
                        edge.at_nearest_exact();
                    }
                    let at = edge.place(&device, NUMBERS_AT_600_DPI, u(k * advance), u(advance));
                    at.units() / dot
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(places(None), [0, 48, 96, 145]);
        assert_eq!(places(Some(2)), [0, 48, 97, 145]);
    }

    #[test]
    fn counts_a_stretched_spaces_excess_until_a_tab_or_gap() {
        // Glyphs of 48.4 dots on a device of 600 dots per inch under the exact edge check: the
        // fourth's right edge lies 1.6 dots short of its exact edge, and the check moves it one
        // dot right. An excess of -0.25 dots in the exact advance of the second, a stretched
        // space, leaves the fourth 1.35 dots short, and the check keeps it.
        let device = Device::per_inch_with(600, |p| p.with_variant(GlyphEdgeCheck::Exact));
        let dot = device.dots(1).units();
        let advance = dot * 484 / 10;
        let u = Length::from_units;
        // `start` is the glyph before which the steps start again, and whether at a tab.
        let places = |shares: [Option<(i128, i128)>; 4], start: Option<(usize, bool)>| {
            let mut edge = EdgeSteps::default();
            shares
                .iter()
                .enumerate()
                .map(|(k, share)| {
                    match start {
                        Some((at, false)) if at == k => edge.restart(),
                        Some((at, true)) if at == k => edge.tab(),
                        _ => {}
                    }
                    edge.with_counted_share(*share);
                    let x = i64::try_from(k).unwrap() * advance;
                    edge.place(&device, NUMBERS_AT_600_DPI, u(x), u(advance))
                        .units()
                        / dot
                })
                .collect::<Vec<_>>()
        };
        let narrow = Some((-i128::from(dot) / 4, 1));
        assert_eq!(places([None; 4], None), [0, 48, 96, 145]);
        assert_eq!(places([None, narrow, None, None], None), [0, 48, 96, 144]);
        // The steps start again at the third glyph, which goes to dot 97, the nearest to its
        // exact place. The fourth then lies 0.8 dots short of its exact edge, and an excess of
        // 0.8 dots in its own advance makes the check move it: the restart of a segment does not
        // end the count, after a stretched space or not.
        let wide = Some((i128::from(dot) * 4 / 5 + 1, 1));
        assert_eq!(
            places([None, None, None, wide], Some((2, false))),
            [0, 48, 97, 146]
        );
        assert_eq!(
            places([None, narrow, None, wide], Some((2, false))),
            [0, 48, 97, 146]
        );
        // A tab after a stretched space ends it, and the check keeps the fourth glyph.
        assert_eq!(
            places([None, None, None, wide], Some((2, true))),
            [0, 48, 97, 146]
        );
        assert_eq!(
            places([None, narrow, None, wide], Some((2, true))),
            [0, 48, 97, 145]
        );
    }

    #[test]
    fn steps_glyphs_as_word_for_the_web_does() {
        // Carlito's i at 456 of 2,048 units and 8 pt, 1.78125 pt.
        let carried = [
            0, 175, 350, 525, 700, 875, 1050, 1225, 1400, 1575, 1750, 1950, 2125, 2300, 2475, 2650,
            2825, 3000, 3175, 3375, 3550, 3725, 3900, 4075,
        ];
        assert_eq!(quarter_places(45_244, 24, SEGMENT), carried);
        // Calibri's i at 8 pt, 470 of 2,048 units.
        let calibri = [
            0, 175, 350, 525, 725, 900, 1075, 1275, 1450, 1625, 1825, 2000, 2175,
        ];
        assert_eq!(quarter_places(46_633, 13, SEGMENT), calibri);
    }

    #[test]
    fn moves_a_glyph_whose_exact_edge_lies_exactly_on_the_limit() {
        // Calibri's n at 12 pt, 1,076 of 2,048 units, 6.3046875 pt, kept as 160,139 half-EMUs,
        // a sixteenth of a half-EMU less. The drawn glyphs fall
        // behind by 7/32 of a dot per step, and the 16th n's edge lies exactly 1.5 dots short
        // of its exact edge, where Word moves it a quarter point right.
        let places = [
            0, 625, 1250, 1875, 2500, 3125, 3775, 4400, 5025, 5650, 6275, 6925, 7550, 8175, 8800,
            9450, 10075,
        ];
        // The rounded advances leave that edge one half-EMU inside the limit, and the tie
        // counts it as on the limit.
        assert_eq!(quarter_places(160_139, 17, SEGMENT), places);
        // The exact edge check counts the sixteenth of a half-EMU that rounding took.
        let n = (160_139, Some((1, 16)));
        let exact = GlyphEdgeCheck::Exact;
        assert_eq!(checked_quarter_places(exact, n, 17, SEGMENT), places);
        // The tie of the rounded check records the edge one half-EMU inside the limit.
        let tied = GlyphEdgeCheck::RoundedWithTie;
        let mut edge = EdgeSteps::default();
        let device = Device::per_inch_with(288, |p| p.with_variant(tied));
        let numbers = quarter_numbers(SEGMENT);
        let checks: Vec<_> = (0..17)
            .map(|k| {
                let u = Length::from_units;
                edge.place(&device, numbers, u(k * 160_139), u(160_139));
                edge.take_checked()
                    .map(|check| (check.edge.units(), check.moves))
            })
            .collect();
        assert_eq!(checks[0], None);
        assert_eq!(checks[15], Some((-numbers.1.units() + 1, 1)));
        // Without it, the exact comparison keeps the glyph.
        let rounded = checked_quarter_places(exact, (160_139, None), 17, SEGMENT);
        assert_eq!(rounded[..15], places[..15]);
        assert_eq!(rounded[15], 9425);
    }

    #[test]
    fn keeps_a_glyph_whose_exact_edge_lies_just_inside_the_limit() {
        // Fourteen advances of a face of 2,048 units at 12 pt on a device of 600 dots per inch
        // (100 dots per em), drawn at random from seven advances: the last glyph's edge lies
        // 4,436 half-EMUs short of its exact edge in the sums of the rounded advances, and
        // 4,435.08 in exact arithmetic, inside the limit of 4,572 either way, so the exact edge
        // check keeps its step.
        let size = 12 * Length::UNITS_PER_POINT;
        let units = [
            909, 682, 512, 569, 1024, 512, 682, 1024, 1024, 909, 682, 1024, 1366, 682,
        ];
        let device = Device::per_inch_with(600, |p| p.with_variant(GlyphEdgeCheck::Exact));
        let mut edge = EdgeSteps::default();
        let mut x = 0;
        let numbers = NUMBERS_AT_600_DPI;
        let places = units.map(|u| {
            let advance = f_office_units::div_round(u * size, 2048);
            edge.with_advance_rounding(Some((u * size - 2048 * advance, 2048)));
            let at = edge.place(
                &device,
                numbers,
                Length::from_units(x),
                Length::from_units(advance),
            );
            x += advance;
            at.units() / device.dots(1).units()
        });
        assert_eq!(
            places,
            [
                0, 44, 77, 102, 130, 180, 205, 238, 288, 338, 382, 415, 465, 532
            ]
        );
        // The check records how far short of its exact edge the last glyph's edge ends, to the
        // nearest half-EMU, and that it keeps the glyph; the record is read once.
        let checked = edge
            .take_checked()
            .map(|check| (check.edge.units(), check.moves));
        assert_eq!(checked, Some((-4_435, 0)));
        assert_eq!(edge.take_checked(), None);
    }

    #[test]
    fn steps_a_glyph_by_its_measured_device_width() {
        // Times New Roman's I at 11 pt, 682 of 2,048 units, 14.652 dots of a quarter point:
        // the device steps it by 14 dots, and the glyph falls
        // short of its exact edge until it moves a dot right. With the advance rounded, 15
        // dots, it runs ahead until it moves a dot left.
        let device = Device::per_inch(288).unwrap();
        let advance = Length::from_units(93_042);
        let numbers = quarter_numbers(SEGMENT);
        let dots = |measured: Option<(i64, Length)>| -> Vec<i64> {
            let mut edge = EdgeSteps::default();
            (0..6)
                .map(|k| {
                    edge.with_device_width(measured);
                    edge.place(&device, numbers, advance * k, advance).units()
                        / device.dots(1).units()
                })
                .collect()
        };
        assert_eq!(dots(None), [0, 15, 30, 45, 59, 74]);
        assert_eq!(dots(Some((14, advance))), [0, 14, 29, 44, 58, 73]);
        // A measured width counts for its own glyph only.
        let mut edge = EdgeSteps::default();
        edge.with_device_width(Some((14, advance)));
        let first = edge.place(&device, numbers, Length::ZERO, advance);
        let second = edge.place(&device, numbers, advance, advance);
        let third = edge.place(&device, numbers, advance * 2, advance);
        assert_eq!(
            [first, second, third].map(|p| p.units() / device.dots(1).units()),
            [0, 14, 29]
        );
    }

    #[test]
    fn steps_to_the_nearest_dot_without_the_widening_of_the_glyph_before() {
        // Two glyphs of 14.4 dots of a quarter point, the first widened to 15 dots: the second
        // steps 15 dots from it, its advance rounded with the bias and the dot that the first
        // widens. Stepped to the nearest dot, it steps 14 dots, the distance rounded alone.
        let device = Device::per_inch(288).unwrap();
        let advance = Length::from_units(91_440);
        let numbers = quarter_numbers(SEGMENT);
        let second = |nearest: bool| -> i64 {
            let mut edge = EdgeSteps::default();
            edge.with_device_width(Some((15, advance)));
            edge.place(&device, numbers, Length::ZERO, advance);
            if nearest {
                edge.step_to_nearest_dot();
                edge.without_bias(true);
            }
            edge.place(&device, numbers, advance, advance).units() / device.dots(1).units()
        };
        assert_eq!(second(false), 15);
        assert_eq!(second(true), 14);
    }

    #[test]
    fn steps_a_glyph_without_the_bias_by_its_distance_at_the_nearest_dot() {
        // A glyph whose exact advance is 23.461 dots of a quarter point, as Calibri's glyph 18
        // at 11 pt: with the bias of 0.04 dot it steps 24 dots and
        // moves a dot left at every other glyph, and without it 23 dots and a dot right.
        let device = Device::per_inch(288).unwrap();
        let advance = Length::from_units(148_977);
        let dots = |without: &[bool]| -> Vec<i64> {
            let mut edge = EdgeSteps::default();
            (0..)
                .zip(without)
                .map(|(k, &without)| {
                    edge.without_bias(without);
                    edge.place(&device, quarter_numbers(SEGMENT), advance * k, advance)
                        .units()
                        / device.dots(1).units()
                })
                .collect()
        };
        assert_eq!(dots(&[false; 6]), [0, 24, 47, 71, 94, 118]);
        assert_eq!(dots(&[true; 6]), [0, 23, 46, 70, 93, 117]);
        // The step out of a glyph takes that glyph's rounding, and its own step in the edge
        // check takes its own.
        assert_eq!(dots(&[true, false, false]), [0, 23, 47]);
        assert_eq!(dots(&[false, true, true]), [0, 24, 47]);
    }

    #[test]
    fn steps_a_glyph_by_its_distance_at_the_drawn_size() {
        // An advance of 52.40 dots at 11 pt is 52.59 dots at 11.04 pt, the size on a device of
        // 600 dots per inch: with the bias of 0.005 pt, the step is 53 dots at the drawn size and
        // 52 at the nominal one, and the glyph's right edge stays within the limit either way.
        let device = Device::per_inch(600).unwrap();
        let u = Length::from_units;
        let numbers = NUMBERS_AT_600_DPI;
        let dot = device.dots(1).units();
        let x = Length::from_points(72).unwrap();
        let advance = u(159_715);
        let mut nominal = EdgeSteps::default();
        nominal.place(&device, numbers, x, advance);
        let at = nominal.place(&device, numbers, x + advance, advance);
        assert_eq!(at - x, u(52 * dot));
        let mut drawn = EdgeSteps::default();
        drawn.at_size(Length::from_points(11).unwrap(), u(280_416));
        drawn.place(&device, numbers, x, advance);
        let at = drawn.place(&device, numbers, x + advance, advance);
        assert_eq!(at - x, u(53 * dot));
    }

    #[test]
    fn steps_out_of_a_glyph_at_its_own_drawn_size_where_the_profile_says_so() {
        // A glyph at 11 pt, drawn at 11.04 pt, and after it a glyph at 12 pt, on the grid of a
        // device of 600 dots per inch. The distance of 52.40 dots is the first glyph's advance,
        // 52.59 dots at its drawn size: the step is 52 dots at the next glyph's size
        // (`DeviceAdvance::ExactAdvances`) and 53 at the size of the glyph before
        // (`ExtrasOnTheirOwn`).
        let u = Length::from_units;
        let (x, advance) = (Length::from_points(72).unwrap(), u(159_715));
        let step = |form: DeviceAdvance| {
            let device = Device::per_inch_with(600, |p| p.with_variant(form));
            let mut edge = EdgeSteps::default();
            edge.at_size(Length::from_points(11).unwrap(), u(280_416));
            edge.place(&device, NUMBERS_AT_600_DPI, x, advance);
            let twelve = Length::from_points(12).unwrap();
            edge.at_size(twelve, twelve);
            let at = edge.place(&device, NUMBERS_AT_600_DPI, x + advance, advance);
            (at - x).units() / device.dots(1).units()
        };
        assert_eq!(step(DeviceAdvance::ExactAdvances), 52);
        assert_eq!(step(DeviceAdvance::ExtrasOnTheirOwn), 53);
    }

    #[test]
    fn starts_a_line_of_glyph_steps_at_the_nearest_dot() {
        let device = Device::per_inch(288).unwrap();
        let u = Length::from_units;
        let mut edge = EdgeSteps::default();
        // 72.1 pt goes to 72 pt, the nearest quarter point; after a restart, 72.2 pt goes to
        // 72.25 pt.
        let numbers = quarter_numbers(SEGMENT);
        let at = edge.place(&device, numbers, u(1_831_340), u(46_633));
        assert_eq!(at, Length::from_points(72).unwrap());
        edge.restart();
        let at = edge.place(&device, numbers, u(1_833_880), u(46_633));
        assert_eq!(at, u(1_835_150));
    }

    #[test]
    fn adds_a_justified_spaces_extra_in_whole_dots() {
        // "u", a space that the justified line widens by 0.592 pt, and "t" at 9 pt, as in a
        // target's PDF: from the space's dot of 117.5 pt, the step of the space's own width
        // (2.0 pt) and the extra rounded to whole dots (0.5 pt) put "t" at 120 pt, where one
        // step of the whole distance would put it at 120.25 pt.
        let device = Device::per_inch(288).unwrap();
        let u = Length::from_units;
        let numbers = quarter_numbers(SEGMENT);
        let extra = u(15_034);
        let place = |justified: bool| {
            let mut edge = EdgeSteps::default();
            edge.place(&device, numbers, u(2_863_912), u(120_104));
            edge.place(&device, numbers, u(2_984_016), u(51_681) + extra);
            if justified {
                edge.after_extra(GlyphExtra::Justified(extra));
            }
            edge.place(&device, numbers, u(3_050_731), u(76_572))
        };
        assert_eq!(place(true), Length::from_points(120).unwrap());
        assert_eq!(place(false), u(3_054_350));
    }

    #[test]
    fn counts_a_character_spacing_as_the_nearest_whole_unit() {
        // Under `CharacterSpacingCount::NearestUnit` a spacing of -3 twips, -536.4 units of
        // 1/3,576 pt, counts as -536 units: 10,160/3,576 half-EMUs (2.84) more than the document
        // gives. One twip, 178.8 units, counts as 179: 5,080/3,576 half-EMUs (1.42) more. Five
        // twips are 894 units and count as they are, and under `Exact` no spacing adds anything.
        let device =
            |count: CharacterSpacingCount| Device::per_inch_with(600, |p| p.with_variant(count));
        let (nearest, exact) = (
            device(CharacterSpacingCount::NearestUnit),
            device(CharacterSpacingCount::Exact),
        );
        let excess = |device: &Device, twips: i64| {
            super::spacing_excess(device, Length::from_units(twips * 1_270))
        };
        assert_eq!(excess(&nearest, -3), super::Exact::reduced(10_160, 3_576));
        assert_eq!(excess(&nearest, 1), super::Exact::reduced(5_080, 3_576));
        assert_eq!(excess(&nearest, 5), super::Exact::ZERO);
        assert_eq!(excess(&exact, -3), super::Exact::ZERO);
    }

    #[test]
    fn keeps_a_glyph_whose_exact_edge_the_counted_spacing_widens() {
        // Lines of three glyphs condensed by 3 twips on a device of 600 dots per inch under the
        // edge check `GlyphEdgeCheck::Exact`. Under `NearestUnit` each glyph's spacing counts
        // 2.84 half-EMUs more in the exact edge, from the glyph that started the steps on, so
        // for some widths a glyph whose edge lies that close past the limit stays where `Exact`
        // moves it. A spacing of 5 twips counts as it is and changes no place.
        let line = |count: CharacterSpacingCount, width: i64, spacing: i64| -> Vec<Length> {
            let device = Device::per_inch_with(600, |p| {
                p.with_variant(GlyphEdgeCheck::Exact).with_variant(count)
            });
            let spacing = Length::from_units(spacing);
            let advance = Length::from_units(width) + spacing;
            let mut edge = EdgeSteps::default();
            (0..3)
                .map(|k| {
                    edge.with_extra(GlyphExtra::Spacing(spacing));
                    edge.with_character_spacing(spacing);
                    let at = edge.place(&device, NUMBERS_AT_600_DPI, advance * k, advance);
                    edge.after_extra(GlyphExtra::Spacing(spacing));
                    at
                })
                .collect()
        };
        let differ = |spacing: i64| {
            (30_000..36_000)
                .filter(|&width| {
                    line(CharacterSpacingCount::Exact, width, spacing)
                        != line(CharacterSpacingCount::NearestUnit, width, spacing)
                })
                .count()
        };
        assert!(differ(-3_810) > 0);
        assert_eq!(differ(6_350), 0);
    }

    #[test]
    fn counts_a_synthetic_bold_extra_in_the_exact_edge_and_moves_it_right_one_dot_sooner() {
        // Lines of three glyphs at 12 pt on a device of 600 dots per inch under the edge check
        // `GlyphEdgeCheck::Exact`. A synthetic bold's extra of one font unit of a face of 2,048
        // units per em counts 148.8 half-EMUs more in each glyph's exact edge, so for some widths
        // a glyph whose edge lies that close past the limit stays where it moves without the
        // extra. An ease of one dot
        // on the short side moves the second glyph one dot right where its edge ends between
        // 1,524 and 4,572 half-EMUs short of its exact edge, and never left.
        let device = Device::per_inch_with(600, |p| p.with_variant(GlyphEdgeCheck::Exact));
        let size = 304_800;
        let line = |width: i64, extra: bool, ease: bool| -> Vec<Length> {
            let advance = Length::from_units(width);
            let mut edge = EdgeSteps::default();
            (0..3)
                .map(|k| {
                    edge.with_counted_extra(extra.then_some((size, 2048)));
                    if ease {
                        edge.with_short_ease(device.dots(1));
                    }
                    edge.place(&device, NUMBERS_AT_600_DPI, advance * k, advance)
                })
                .collect()
        };
        let widths = 30_000..36_000;
        assert!(
            widths
                .clone()
                .any(|width| line(width, true, false) != line(width, false, false))
        );
        let second = |width: i64, ease: bool| line(width, false, ease).get(1).copied();
        let eased: Vec<i64> = widths
            .filter_map(|width| Some((second(width, true)? - second(width, false)?).units()))
            .collect();
        assert!(eased.contains(&device.dots(1).units()));
        assert!(
            eased
                .iter()
                .all(|&moved| moved == 0 || moved == device.dots(1).units())
        );
    }

    #[test]
    fn steps_a_glyphs_character_spacing_in_whole_dots_on_its_own() {
        // A glyph of 444 thousandths at 13 pt is 23.088 dots wide, and its run is condensed by
        // 0.15 pt, 0.6 dot. Its width's step of 23 dots and the spacing rounded to -1 dot put
        // the next glyph 22 dots on, where one step of the whole advance of 22.488 dots and
        // the bias would put it 23 dots on.
        let device = Device::per_inch(288).unwrap();
        let (numbers, dot) = (quarter_numbers(SEGMENT), device.dots(1));
        let (width, spacing) = (Length::from_units(146_609), Length::from_units(-3_810));
        let place = |extra: bool| {
            let mut edge = EdgeSteps::default();
            if extra {
                edge.with_extra(GlyphExtra::Spacing(spacing));
            }
            edge.place(&device, numbers, Length::ZERO, width + spacing);
            if extra {
                edge.after_extra(GlyphExtra::Spacing(spacing));
            }
            edge.place(&device, numbers, width + spacing, width)
        };
        assert_eq!(place(true), dot * 22);
        assert_eq!(place(false), dot * 23);
    }

    #[test]
    fn checks_a_stretched_space_by_its_width_and_its_share_in_whole_dots() {
        // Two glyphs of 10.4 dots step by 10 dots, so the space after them starts 0.8 dots
        // short of its exact place. The space is 2.4 dots wide and a justified line widens it
        // by 2.4 dots: its width and its share in whole dots are 2 and 2, which ends 1.6 dots
        // short of its exact right edge, so it moves a dot right. The two rounded together
        // are 5 dots, 0.6 dots short, which would keep it.
        let device = Device::per_inch(288).unwrap();
        let (numbers, dot) = (quarter_numbers(SEGMENT), device.dots(1));
        let u = Length::from_units;
        let place = |stretched: bool| {
            let mut edge = EdgeSteps::default();
            for k in 0..2 {
                edge.place(&device, numbers, u(k * 66_040), u(66_040));
            }
            if stretched {
                edge.with_extra(GlyphExtra::Justified(u(15_240)));
            }
            edge.place(&device, numbers, u(2 * 66_040), u(30_480))
        };
        assert_eq!(place(true), dot * 21);
        assert_eq!(place(false), dot * 20);
    }

    #[test]
    fn steps_an_extra_of_a_half_dot_away_from_zero() {
        // A glyph 10 dots wide condensed by exactly 2.5 dots: under `DeviceAdvance::ExactAdvances`
        // its spacing steps as -2 dots and the next glyph goes 8 dots on, under
        // `ExtrasOnTheirOwn` as -3 dots and 7 dots on. Each lies half a dot from the exact place, inside the edge
        // check's limit. A spacing of 2.5 dots steps as 3 dots under both, and a justified
        // space's share of -2.5 dots as -2 dots under both.
        let device = |form: DeviceAdvance| Device::per_inch_with(288, |p| p.with_variant(form));
        let numbers = quarter_numbers(SEGMENT);
        let width = Length::from_units(63_500);
        let place = |device: &Device, extra: GlyphExtra| {
            let mut edge = EdgeSteps::default();
            edge.with_extra(extra);
            edge.place(device, numbers, Length::ZERO, width + extra.length());
            edge.after_extra(extra);
            edge.place(device, numbers, width + extra.length(), width)
        };
        let spacing = |units: i64| GlyphExtra::Spacing(Length::from_units(units));
        let up = device(DeviceAdvance::ExactAdvances);
        let away = device(DeviceAdvance::ExtrasOnTheirOwn);
        let dot = up.dots(1);
        assert_eq!(dot, Length::from_units(6_350));
        assert_eq!(place(&up, spacing(-15_875)), dot * 8);
        assert_eq!(place(&away, spacing(-15_875)), dot * 7);
        assert_eq!(place(&up, spacing(15_875)), dot * 13);
        assert_eq!(place(&away, spacing(15_875)), dot * 13);
        let share = GlyphExtra::Justified(Length::from_units(-15_875));
        assert_eq!(place(&up, share), dot * 8);
        assert_eq!(place(&away, share), dot * 8);
    }

    #[test]
    fn rounds_a_spaced_share_summed_or_apart() {
        // A justified space 10 dots wide with a share of 5.34 dots and a character spacing of
        // -0.83 dot: summed, 4.51 dots step as 5 and the next glyph goes 15 dots on; apart, 5
        // and -1 step as 4 and it goes 14 on. Both lie within the edge check's limit of the
        // exact 14.51 dots.
        let device = |form: DeviceAdvance| Device::per_inch_with(288, |p| p.with_variant(form));
        let numbers = quarter_numbers(SEGMENT);
        let width = Length::from_units(63_500);
        let extra = GlyphExtra::of(Length::from_units(33_909), Length::from_units(-5_271));
        let place = |device: &Device| {
            let mut edge = EdgeSteps::default();
            edge.with_extra(extra);
            edge.place(device, numbers, Length::ZERO, width + extra.length());
            edge.after_extra(extra);
            edge.place(device, numbers, width + extra.length(), width)
        };
        let summed = device(DeviceAdvance::ExactAdvances);
        let dot = summed.dots(1);
        assert_eq!(place(&summed), dot * 15);
        assert_eq!(place(&device(DeviceAdvance::ExtrasOnTheirOwn)), dot * 14);
    }

    #[test]
    fn endnote_mark_snaps_start_and_steps_without_edge_moves() {
        // At 600 dpi (1 dot = 3,048 half-EMUs), prefix glyphs of 10.35 dots accumulate -0.70 dot
        // lag so the mark's first glyph snaps +1 dot to its nearest exact dot. Inside the mark,
        // three glyphs each 10.4 dots wide (device step 10 dots, or 10.6 -> 11 dots, +0.4 dot
        // wider per glyph) would exceed a 1.5-dot limit if edge-checked; stepping without edge
        // moves keeps all three at pure device steps and advances the anchor by device width so
        // the text after the mark inherits no drift from the mark.
        let device = Device::per_inch_with(600, |p| {
            p.with_variant(crate::quirks::NoteMarkPlace::NearestExact)
                .with_variant(GlyphEdgeCheck::Exact)
        });
        let dot = device.dots(1);
        let numbers = (Length::ZERO, Length::from_units(4_572), device.dots(1_024));
        let u = Length::from_units;
        let mut edge = EdgeSteps::default();
        let mut x = Length::ZERO;
        // Two prefix glyphs of 10.35 dots (31,547 units): device steps 10 + 10 = 20 dots, exact
        // position 20.70 dots -> nearest exact is 21 dots (+1 dot).
        for _ in 0..2 {
            edge.place(&device, numbers, x, u(31_547));
            x += u(31_547);
        }
        // Mark glyph 0: 9.4 dots (28,651 units) -> device width 9 dots, snaps to 21 dots.
        edge.at_endnote_start(&device);
        let m0 = edge.place(&device, numbers, x, u(28_651));
        assert_eq!(m0, dot * 21);
        x += u(28_651);
        // Mark glyphs 1..4: each 10.6 dots (32,309 units) -> device step 11 dots (+0.4 dot wider),
        // accumulating +1.6 dots if checked; must stay at pure 11-dot steps with no -1 move.
        let mut expected = dot * 30;
        for _ in 0..4 {
            edge.at_endnote_step(&device);
            let mk = edge.place(&device, numbers, x, u(32_309));
            assert_eq!(mk, expected);
            x += u(32_309);
            expected += dot * 11;
        }
        // First glyph after the mark starts at expected (74 dots) and stays there without a -1
        // move because the mark advanced the anchor by its device width.
        let after = edge.place(&device, numbers, x, dot * 10);
        assert_eq!(after, expected);
    }
}