spindrift 0.1.0

A HTML/CSS to PDF renderer, targeting spec compliance and efficiency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
use super::*;

/// Applies CSS min/max size constraints, with minimums overriding maximums.
///
/// CSS 2.2 applies max constraints first and min constraints second, so a
/// larger minimum size wins over a smaller maximum size:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-widths> and
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-heights>.
pub(in crate::layout) fn constrain(mut value: f32, min: Option<f32>, max: Option<f32>) -> f32 {
    if let Some(max) = max {
        value = value.min(max);
    }
    if let Some(min) = min {
        value = value.max(min);
    }
    value
}

/// Resolves CSS Sizing Level 4 stretch-fit sizing to a content-box size.
///
/// `stretch` attempts to make the margin box fill the available space. Layout
/// callers pass the already-resolved available margin-box size, used margins,
/// and padding plus border for the relevant axis, and the content box is
/// floored at zero:
/// <https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing>.
/// Resolves CSS Sizing Level 4 stretch-fit sizing to a content-box length.
///
/// `stretch` attempts to make the margin box fill the available space. The
/// result is a CSS content-box length in Spindrift's PDF-point layout scalar, with
/// padding and border represented as an explicit semantic non-content length:
/// <https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing> and
/// <https://www.w3.org/TR/css-sizing-3/#box-sizing>.
pub(in crate::layout) fn stretch_fit_content_box_size(
    available_margin_box_size: LayoutLength,
    margin_size: LayoutLength,
    non_content_size: NonContentLength,
) -> ContentBoxLength {
    content_box_pt(
        (available_margin_box_size.points() - margin_size.points() - non_content_size.points())
            .max(0.0),
    )
}
/// Resolves used content width, falling back to filling available space for `auto`.
///
/// CSS 2.2 defines block-width used-value resolution and CSS Box Sizing defines
/// how `box-sizing` changes the content-box size:
/// <https://www.w3.org/TR/CSS22/visudet.html#blockwidth> and
/// <https://www.w3.org/TR/css-sizing-3/#box-sizing>.
pub(in crate::layout) fn used_content_box_width(
    style: &ComputedStyle,
    available_outer_width: LayoutLength,
    horizontal_non_content: NonContentLength,
) -> ContentBoxLength {
    used_content_box_size(
        style.box_values.width.clone(),
        style.box_sizing,
        PercentageBasis::definite(crate::units::layout_to_content_box_length(
            available_outer_width,
        )),
        horizontal_non_content,
    )
    .unwrap_or_else(|| {
        content_box_pt((available_outer_width.points() - horizontal_non_content.points()).max(0.0))
    })
}

/// Resolves a specified content width against a typed physical availability.
///
/// CSS percentage widths use the containing block's inline size; this entry
/// point preserves the resulting content-box quantity until the caller enters
/// a coordinate or rendering algorithm.
pub(in crate::layout) fn used_content_box_width_or_auto(
    style: &ComputedStyle,
    available_outer_width: LayoutLength,
    horizontal_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    used_content_box_size(
        style.box_values.width.clone(),
        style.box_sizing,
        PercentageBasis::definite(crate::units::layout_to_content_box_length(
            available_outer_width,
        )),
        horizontal_non_content,
    )
}

/// Resolves a specified content width against a typed percentage basis.
pub(in crate::layout) fn used_content_box_width_or_auto_with_basis<Source>(
    style: &ComputedStyle,
    available_outer_width: PercentageBasis<ContentBoxLength, Source>,
    horizontal_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    used_content_box_size_with_basis(
        style.box_values.width.clone(),
        style.box_sizing,
        available_outer_width,
        horizontal_non_content,
    )
}

/// Resolves a specified content height against a typed physical availability.
///
/// CSS percentage heights use the containing block's block-size basis; an
/// automatic height remains unresolved for its formatting context to handle.
pub(in crate::layout) fn used_content_box_height_or_auto(
    style: &ComputedStyle,
    available_outer_height: LayoutLength,
    vertical_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    used_content_box_size(
        style.box_values.height.value().clone(),
        style.box_sizing,
        PercentageBasis::definite(crate::units::layout_to_content_box_length(
            available_outer_height,
        )),
        vertical_non_content,
    )
}

/// Resolves a specified content height against a typed percentage basis.
pub(in crate::layout) fn used_content_box_height_or_auto_with_basis<Source>(
    style: &ComputedStyle,
    available_outer_height: PercentageBasis<ContentBoxLength, Source>,
    vertical_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    used_content_box_size_with_basis(
        style.box_values.height.value().clone(),
        style.box_sizing,
        available_outer_height,
        vertical_non_content,
    )
}

/// Resolves a non-replaced preferred block size at a descendant
/// formatting-context boundary.
///
/// During intrinsic measurement of a content-sized containing block, a cyclic
/// percentage preferred size is its initial value (`auto`), rather than the
/// fixed length component of the expression. This differs from the ordinary
/// indefinite-basis fallback used by margins, padding, and minimum sizes.
/// <https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution>
pub(in crate::layout) fn used_non_replaced_content_box_height_or_auto(
    style: &ComputedStyle,
    context: DescendantBlockPercentageContext,
    vertical_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    let value = style.box_values.height.value().clone();
    if context.is_content_sized()
        && matches!(&value, css::ComputedLengthPercentageOrAuto::LengthPercentage(value) if value.needs_percentage_basis())
    {
        return None;
    }
    used_content_box_size_with_basis(
        value,
        style.box_sizing,
        context.percentage_basis(),
        vertical_non_content,
    )
}

/// The box whose dimensions participate in preferred aspect-ratio sizing.
///
/// A bare `<ratio>` uses the box selected by `box-sizing`, while the ratio in
/// `auto && <ratio>` always operates on content-box dimensions for a
/// non-replaced box:
/// <https://drafts.csswg.org/css-sizing-4/#aspect-ratio>.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum AspectRatioCalculationBox {
    ContentBox,
    BorderBox,
}

/// A resolved preferred aspect ratio and the physical box-space inputs needed
/// to transfer sizes between its axes.
///
/// CSS Sizing Level 4 defines the preferred aspect ratio in width/height order
/// and requires ratio-dependent automatic sizes to use the same sizing box in
/// every phase. Keeping the non-content extents in their semantic type makes
/// crossing between content-box and border-box space explicit:
/// <https://drafts.csswg.org/css-sizing-4/#aspect-ratio>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct ResolvedAspectRatio {
    ratio: f32,
    calculation_box: AspectRatioCalculationBox,
    horizontal_non_content: NonContentLength,
    vertical_non_content: NonContentLength,
}

impl ResolvedAspectRatio {
    pub(in crate::layout) fn for_non_replaced(
        style: &ComputedStyle,
        horizontal_non_content: NonContentLength,
        vertical_non_content: NonContentLength,
    ) -> Option<Self> {
        let ratio = style.aspect_ratio.preferred_ratio_for_non_replaced(false)?;
        Self::new(
            ratio,
            if style.aspect_ratio.uses_content_box_for_non_replaced()
                || style.box_sizing == BoxSizing::ContentBox
            {
                AspectRatioCalculationBox::ContentBox
            } else {
                AspectRatioCalculationBox::BorderBox
            },
            horizontal_non_content,
            vertical_non_content,
        )
    }

    pub(in crate::layout) fn new(
        ratio: f32,
        calculation_box: AspectRatioCalculationBox,
        horizontal_non_content: NonContentLength,
        vertical_non_content: NonContentLength,
    ) -> Option<Self> {
        (ratio.is_finite() && ratio > 0.0).then_some(Self {
            ratio,
            calculation_box,
            horizontal_non_content,
            vertical_non_content,
        })
    }

    pub(in crate::layout) fn width_from_height(
        self,
        content_height: ContentBoxLength,
    ) -> ContentBoxLength {
        match self.calculation_box {
            AspectRatioCalculationBox::ContentBox => {
                content_box_pt(content_height.points() * self.ratio)
            }
            AspectRatioCalculationBox::BorderBox => {
                let border_box_height =
                    content_box_to_border_box_length(content_height, self.vertical_non_content);
                border_box_to_content_box_length(
                    border_box_pt(border_box_height.points() * self.ratio),
                    self.horizontal_non_content,
                )
            }
        }
    }

    pub(in crate::layout) fn height_from_width(
        self,
        content_width: ContentBoxLength,
    ) -> ContentBoxLength {
        match self.calculation_box {
            AspectRatioCalculationBox::ContentBox => {
                content_box_pt(content_width.points() / self.ratio)
            }
            AspectRatioCalculationBox::BorderBox => {
                let border_box_width =
                    content_box_to_border_box_length(content_width, self.horizontal_non_content);
                border_box_to_content_box_length(
                    border_box_pt(border_box_width.points() / self.ratio),
                    self.vertical_non_content,
                )
            }
        }
    }
}

/// Definite preferred and min/max sizes for one physical axis in content-box
/// space. `None` retains the CSS constraint's indefinite/automatic state.
#[derive(Debug, Clone, Copy, Default)]
pub(in crate::layout) struct AspectRatioAxisConstraints {
    pub(in crate::layout) preferred: Option<ContentBoxLength>,
    pub(in crate::layout) minimum: Option<ContentBoxLength>,
    pub(in crate::layout) maximum: Option<ContentBoxLength>,
}

impl AspectRatioAxisConstraints {
    pub(in crate::layout) fn constrain(self, value: ContentBoxLength) -> ContentBoxLength {
        constrain_aspect_ratio_axis(value, self)
    }
}

/// The two-axis result of CSS aspect-ratio min/max constraint transfer.
///
/// CSS Sizing Level 4 section 4.4 transfers definite minimums and maximums to
/// an automatic constraint in the ratio-dependent axis. A transferred minimum
/// is capped by definite preferred/maximum sizes in that destination axis; a
/// transferred maximum is floored by definite preferred/minimum sizes. The
/// resulting constraints are then applied independently after preferred-size
/// transfer:
/// <https://drafts.csswg.org/css-sizing-4/#aspect-ratio-minimum>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct ResolvedAspectRatioConstraints {
    pub(in crate::layout) width: AspectRatioAxisConstraints,
    pub(in crate::layout) height: AspectRatioAxisConstraints,
}

impl ResolvedAspectRatioConstraints {
    pub(in crate::layout) fn resolve(
        ratio: ResolvedAspectRatio,
        width: AspectRatioAxisConstraints,
        height: AspectRatioAxisConstraints,
    ) -> Self {
        let transferred_width_minimum = height.minimum.map(|minimum| {
            cap_transferred_minimum(
                ratio.width_from_height(minimum),
                width.preferred,
                width.maximum,
            )
        });
        let transferred_height_minimum = width.minimum.map(|minimum| {
            cap_transferred_minimum(
                ratio.height_from_width(minimum),
                height.preferred,
                height.maximum,
            )
        });
        let resolved_width_minimum = combine_minimum(width.minimum, transferred_width_minimum);
        let resolved_height_minimum = combine_minimum(height.minimum, transferred_height_minimum);
        let transferred_width_maximum = height.maximum.map(|maximum| {
            floor_transferred_maximum(
                ratio.width_from_height(maximum),
                width.preferred,
                resolved_width_minimum,
            )
        });
        let transferred_height_maximum = width.maximum.map(|maximum| {
            floor_transferred_maximum(
                ratio.height_from_width(maximum),
                height.preferred,
                resolved_height_minimum,
            )
        });
        let resolved_width = AspectRatioAxisConstraints {
            minimum: resolved_width_minimum,
            maximum: combine_maximum(width.maximum, transferred_width_maximum),
            ..width
        };
        let resolved_height = AspectRatioAxisConstraints {
            minimum: resolved_height_minimum,
            maximum: combine_maximum(height.maximum, transferred_height_maximum),
            ..height
        };

        Self {
            width: resolved_width,
            height: resolved_height,
        }
    }

    pub(in crate::layout) fn constrain_width(self, value: ContentBoxLength) -> ContentBoxLength {
        constrain_aspect_ratio_axis(value, self.width)
    }

    pub(in crate::layout) fn constrain_height(self, value: ContentBoxLength) -> ContentBoxLength {
        constrain_aspect_ratio_axis(value, self.height)
    }
}

fn combine_minimum(
    authored: Option<ContentBoxLength>,
    transferred: Option<ContentBoxLength>,
) -> Option<ContentBoxLength> {
    match (authored, transferred) {
        (Some(authored), Some(transferred)) => {
            Some(content_box_pt(authored.points().max(transferred.points())))
        }
        (authored, transferred) => authored.or(transferred),
    }
}

fn combine_maximum(
    authored: Option<ContentBoxLength>,
    transferred: Option<ContentBoxLength>,
) -> Option<ContentBoxLength> {
    match (authored, transferred) {
        (Some(authored), Some(transferred)) => {
            Some(content_box_pt(authored.points().min(transferred.points())))
        }
        (authored, transferred) => authored.or(transferred),
    }
}

fn cap_transferred_minimum(
    transferred: ContentBoxLength,
    preferred: Option<ContentBoxLength>,
    maximum: Option<ContentBoxLength>,
) -> ContentBoxLength {
    content_box_pt(
        [preferred, maximum]
            .into_iter()
            .flatten()
            .fold(transferred.points(), |value, limit| {
                value.min(limit.points())
            })
            .max(0.0),
    )
}

fn floor_transferred_maximum(
    transferred: ContentBoxLength,
    preferred: Option<ContentBoxLength>,
    minimum: Option<ContentBoxLength>,
) -> ContentBoxLength {
    content_box_pt(
        [preferred, minimum]
            .into_iter()
            .flatten()
            .fold(transferred.points(), |value, limit| {
                value.max(limit.points())
            })
            .max(0.0),
    )
}

fn constrain_aspect_ratio_axis(
    value: ContentBoxLength,
    constraints: AspectRatioAxisConstraints,
) -> ContentBoxLength {
    content_box_pt(constrain(
        value.points(),
        constraints.minimum.map(SemanticLengthExt::points),
        constraints.maximum.map(SemanticLengthExt::points),
    ))
}

/// Transfer a definite non-replaced content width through its preferred aspect
/// ratio to obtain an automatic content height.
///
/// The ratio applies in the box defined by `box-sizing`; converting both
/// dimensions through the content box keeps borders and padding from being
/// counted asymmetrically. Constraint application remains with the formatting
/// context because its percentage basis and intrinsic contributions are
/// context-dependent.
/// <https://www.w3.org/TR/css-sizing-4/#aspect-ratio>
pub(in crate::layout) fn non_replaced_aspect_ratio_content_height(
    style: &ComputedStyle,
    content_width: f32,
    horizontal_non_content: f32,
    vertical_non_content: f32,
) -> Option<f32> {
    let calc_size = style.box_values.height.calc_size_with_auto_basis();
    if !style.box_values.height.is_auto() && calc_size.is_none() {
        return None;
    }
    let ratio = ResolvedAspectRatio::for_non_replaced(
        style,
        non_content_pt(horizontal_non_content),
        non_content_pt(vertical_non_content),
    )?;
    let height = ratio
        .height_from_width(content_box_pt(content_width))
        .points();
    Some(
        calc_size
            .map(|value| {
                value
                    .used_value(
                        height,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        PercentageBasis::definite(layout_pt(0.0)),
                    )
                    .points()
            })
            .unwrap_or(height)
            .max(0.0),
    )
}

/// Transfer a definite non-replaced content height through its preferred
/// aspect ratio to obtain an automatic content width.
///
/// This is the reciprocal of [`non_replaced_aspect_ratio_content_height`];
/// keeping both conversions here makes each formatting context choose a used
/// size without reimplementing `box-sizing` arithmetic.
/// <https://www.w3.org/TR/css-sizing-4/#aspect-ratio>
pub(in crate::layout) fn non_replaced_aspect_ratio_content_width(
    style: &ComputedStyle,
    content_height: f32,
    horizontal_non_content: f32,
    vertical_non_content: f32,
) -> Option<f32> {
    let calc_size = style.box_values.width.clone().calc_size_with_auto_basis();
    if !style.box_values.width.clone().is_auto() && calc_size.is_none() {
        return None;
    }
    let ratio = ResolvedAspectRatio::for_non_replaced(
        style,
        non_content_pt(horizontal_non_content),
        non_content_pt(vertical_non_content),
    )?;
    let width = ratio
        .width_from_height(content_box_pt(content_height))
        .points();
    Some(
        calc_size
            .map(|value| {
                value
                    .used_value(
                        width,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        PercentageBasis::definite(layout_pt(0.0)),
                    )
                    .points()
            })
            .unwrap_or(width)
            .max(0.0),
    )
}

/// Resolves a width/height value to a typed content-box used size.
///
/// CSS Box Sizing defines conversion between border-box and content-box sizes:
/// <https://www.w3.org/TR/css-sizing-3/#box-sizing>.
///
/// The returned value is a CSS content-box length in Spindrift's PDF-point layout
/// scalar. Callers should keep this typed until they cross a layout/paint or
/// external adapter boundary.
pub(in crate::layout) fn used_content_box_size<Source>(
    value: css::ComputedLengthPercentageOrAuto,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength, Source>,
    non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    used_content_box_size_with_basis(value, box_sizing, percentage_basis, non_content)
}

/// Resolves a width/height value to a typed content-box used size.
///
/// CSS Sizing treats pure lengths as definite without a percentage basis, while
/// percentage sizes are definite only when the containing block axis is
/// definite. CSS Box Sizing then maps the specified content-box or border-box
/// value into the content-box coordinate space:
/// <https://www.w3.org/TR/css-sizing-3/#definite> and
/// <https://www.w3.org/TR/css-sizing-3/#box-sizing>.
pub(in crate::layout) fn used_content_box_size_with_basis<Source>(
    value: css::ComputedLengthPercentageOrAuto,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength, Source>,
    non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    let specified = match value {
        css::ComputedLengthPercentageOrAuto::Auto => return None,
        css::ComputedLengthPercentageOrAuto::Stretch => {
            return percentage_basis.points().map(|basis| {
                stretch_fit_content_box_size(layout_pt(basis), layout_pt(0.0), non_content)
            });
        }
        css::ComputedLengthPercentageOrAuto::LengthPercentage(value) => {
            layout_points(used_length_percentage_with_basis(value, percentage_basis)?)
        }
        css::ComputedLengthPercentageOrAuto::MinContent
        | css::ComputedLengthPercentageOrAuto::MaxContent
        | css::ComputedLengthPercentageOrAuto::FitContent(_)
        | css::ComputedLengthPercentageOrAuto::CalcSize(_) => return None,
    };
    Some(used_content_box_size_from_specified(
        specified,
        box_sizing,
        non_content,
    ))
}

fn used_content_box_size_from_specified(
    specified: f32,
    box_sizing: BoxSizing,
    non_content: NonContentLength,
) -> ContentBoxLength {
    match box_sizing {
        BoxSizing::BorderBox => {
            border_box_to_content_box_length(border_box_pt(specified), non_content)
        }
        BoxSizing::ContentBox => content_box_pt(specified.max(0.0)),
    }
}

/// Resolves used `min-width`.
///
/// CSS 2.2 defines min/max width constraints:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-widths>.
pub(in crate::layout) fn used_min_width<T, Source>(
    style: &ComputedStyle,
    percentage_basis: PercentageBasis<T, Source>,
) -> Option<ContentBoxLength>
where
    T: SemanticLengthExt,
{
    used_length_percentage_or_auto(style.box_values.min_width.clone(), percentage_basis)
        .map(|value| content_box_pt(value.points().max(0.0)))
}

/// Resolves used `max-width`.
///
/// CSS 2.2 defines min/max width constraints:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-widths>.
pub(in crate::layout) fn used_max_width<T, Source>(
    style: &ComputedStyle,
    percentage_basis: PercentageBasis<T, Source>,
) -> Option<ContentBoxLength>
where
    T: SemanticLengthExt,
{
    used_length_percentage_or_auto(style.box_values.max_width.clone(), percentage_basis)
        .map(|value| content_box_pt(value.points().max(0.0)))
}

/// Return whether a sizing value needs intrinsic min/max-content contributions.
///
/// CSS Sizing defines these keywords in terms of intrinsic size contributions,
/// so callers must measure contents before resolving them:
/// <https://www.w3.org/TR/css-sizing-3/#sizing-values>.
pub(in crate::layout) fn needs_intrinsic_width_contribution(
    value: css::ComputedLengthPercentageOrAuto,
) -> bool {
    matches!(
        value,
        css::ComputedLengthPercentageOrAuto::MinContent
            | css::ComputedLengthPercentageOrAuto::MaxContent
            | css::ComputedLengthPercentageOrAuto::FitContent(_)
    ) || matches!(&value, css::ComputedLengthPercentageOrAuto::CalcSize(value) if value.needs_intrinsic_size())
        // A percentage-dependent width has no used value during intrinsic
        // sizing. CSS Sizing therefore measures the contents instead of
        // prematurely using the fixed component of `calc()`, including an
        // authored `0%` component.
        // <https://www.w3.org/TR/css-sizing-3/#intrinsic-sizes>.
        || matches!(&value, css::ComputedLengthPercentageOrAuto::LengthPercentage(value) if value.needs_percentage_basis())
}

/// Return whether a block-axis sizing value needs intrinsic min/max-content contributions.
///
/// CSS Sizing defines block-axis `min-content` and `max-content` sizes in
/// terms of the content's intrinsic block size. Normal block containers have
/// equivalent min-content and max-content block sizes, but callers still need
/// the laid-out content height before resolving these keywords:
/// <https://www.w3.org/TR/css-sizing-3/#sizing-values> and
/// <https://github.com/w3c/csswg-drafts/issues/3973>.
pub(in crate::layout) fn needs_intrinsic_height_contribution(
    value: css::ComputedLengthPercentageOrAuto,
) -> bool {
    matches!(
        value,
        css::ComputedLengthPercentageOrAuto::MinContent
            | css::ComputedLengthPercentageOrAuto::MaxContent
            | css::ComputedLengthPercentageOrAuto::FitContent(_)
    ) || matches!(value, css::ComputedLengthPercentageOrAuto::CalcSize(value) if value.needs_intrinsic_size())
}

/// Resolves used `min-height`.
///
/// CSS 2.2 defines min/max height constraints:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-heights>.
pub(in crate::layout) fn used_min_height<T, Source>(
    style: &ComputedStyle,
    percentage_basis: PercentageBasis<T, Source>,
) -> Option<ContentBoxLength>
where
    T: SemanticLengthExt,
{
    match style.box_values.min_height.clone() {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(value) => {
            // A cyclic min-size percentage contributes zero, rather than
            // discarding an accompanying fixed `calc()` term.  For example,
            // `min-height: calc(25px + 50%)` in an auto-height containing
            // block has a used minimum of 25px.
            // <https://www.w3.org/TR/css-sizing-3/#cyclic-percentage-contribution>
            Some(content_box_pt(
                used_length_percentage(value, percentage_basis)
                    .points()
                    .max(0.0),
            ))
        }
        css::ComputedLengthPercentageOrAuto::Auto
        | css::ComputedLengthPercentageOrAuto::Stretch
        | css::ComputedLengthPercentageOrAuto::MinContent
        | css::ComputedLengthPercentageOrAuto::MaxContent
        | css::ComputedLengthPercentageOrAuto::FitContent(_)
        | css::ComputedLengthPercentageOrAuto::CalcSize(_) => None,
    }
}

/// Resolves used `max-height`.
///
/// CSS 2.2 defines min/max height constraints:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-heights>.
pub(in crate::layout) fn used_max_height<T, Source>(
    style: &ComputedStyle,
    percentage_basis: PercentageBasis<T, Source>,
) -> Option<ContentBoxLength>
where
    T: SemanticLengthExt,
{
    used_length_percentage_or_auto(style.box_values.max_height.clone(), percentage_basis)
        .map(|value| content_box_pt(value.points().max(0.0)))
}

/// Resolves a non-replaced maximum block-size at a descendant
/// formatting-context boundary.
///
/// A cyclic percentage maximum is `none` for an intrinsic contribution. Do
/// not route this through `used_max_height`: its generic indefinite-basis
/// behavior intentionally retains a fixed `calc()` component for properties
/// whose cyclic rule is different.
/// <https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution>
pub(in crate::layout) fn used_non_replaced_max_height(
    style: &ComputedStyle,
    context: DescendantBlockPercentageContext,
) -> Option<ContentBoxLength> {
    let value = style.box_values.max_height.clone();
    if context.is_content_sized()
        && matches!(&value, css::ComputedLengthPercentageOrAuto::LengthPercentage(value) if value.needs_percentage_basis())
    {
        return None;
    }
    used_max_height(style, context.percentage_basis())
}

/// Applies ordinary non-replaced block-size constraints at a descendant
/// formatting-context boundary.
///
/// This is the non-intrinsic counterpart of
/// [`constrain_non_replaced_height_with_intrinsic`].
/// <https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution>
pub(in crate::layout) fn constrain_non_replaced_content_height(
    style: &ComputedStyle,
    value: ContentBoxLength,
    context: DescendantBlockPercentageContext,
) -> ContentBoxLength {
    let mut cyclic_style;
    let style = if context.is_content_sized()
        && matches!(
            &style.box_values.max_height,
            css::ComputedLengthPercentageOrAuto::LengthPercentage(value) if value.needs_percentage_basis()
        ) {
        cyclic_style = style.clone();
        cyclic_style.box_values.max_height = css::ComputedLengthPercentageOrAuto::Auto;
        &cyclic_style
    } else {
        style
    };
    constrain_content_height(style, value, context.percentage_basis())
}

/// Applies non-intrinsic used min/max width constraints to a content width.
///
/// CSS 2.2 defines min/max width constraint application. Intrinsic sizing
/// keywords need content measurements and are intentionally ignored here; use
/// `constrain_width_with_intrinsic` when min/max-content contributions are
/// available:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-widths> and
/// <https://www.w3.org/TR/css-sizing-3/#sizing-values>.
pub(in crate::layout) trait ConstraintPercentageBasis {
    fn into_layout_basis(self) -> PercentageBasis<LayoutLength>;
}

impl<T, Source> ConstraintPercentageBasis for PercentageBasis<T, Source>
where
    T: crate::units::IntoLayoutLength,
{
    fn into_layout_basis(self) -> PercentageBasis<LayoutLength> {
        match self {
            PercentageBasis::Definite { value, .. } => {
                PercentageBasis::definite(crate::units::IntoLayoutLength::into_layout_length(value))
            }
            PercentageBasis::Indefinite => PercentageBasis::indefinite(),
        }
    }
}

/// Applies used width constraints to a typed content-box size.
///
pub(in crate::layout) fn constrain_content_width<B>(
    style: &ComputedStyle,
    value: ContentBoxLength,
    percentage_basis: B,
) -> ContentBoxLength
where
    B: ConstraintPercentageBasis,
{
    let percentage_basis = percentage_basis.into_layout_basis();
    content_box_pt(constrain(
        value.points(),
        used_min_width(style, percentage_basis).map(SemanticLengthExt::points),
        used_max_width(style, percentage_basis).map(SemanticLengthExt::points),
    ))
}

/// Apply width constraints, resolving `stretch` against the available margin
/// box rather than treating it as an ordinary length.
///
/// CSS Sizing defines stretch-fit sizing on the margin box. Normal-flow block
/// width resolution reaches this point after margin values are known, which is
/// the shared boundary where a stretch min/max constraint can retain that
/// distinction from a content-box length.
/// <https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing>
pub(in crate::layout) fn constrain_width_with_stretch_fit(
    style: &ComputedStyle,
    value: ContentBoxLength,
    available_margin_box_width: LayoutLength,
    horizontal_margin: LayoutLength,
    horizontal_non_content: NonContentLength,
) -> ContentBoxLength {
    let stretch = || {
        stretch_fit_content_box_size(
            available_margin_box_width,
            horizontal_margin,
            horizontal_non_content,
        )
        .points()
    };
    let min = if style.box_values.min_width == css::ComputedLengthPercentageOrAuto::Stretch {
        Some(stretch())
    } else {
        used_min_width(style, PercentageBasis::definite(available_margin_box_width))
            .map(SemanticLengthExt::points)
    };
    let max = if style.box_values.max_width == css::ComputedLengthPercentageOrAuto::Stretch {
        Some(stretch())
    } else {
        used_max_width(style, PercentageBasis::definite(available_margin_box_width))
            .map(SemanticLengthExt::points)
    };
    content_box_pt(constrain(value.points(), min, max))
}

/// Applies min/max width constraints, including intrinsic sizing keywords.
///
/// CSS Sizing defines `min-content`, `max-content`, and `fit-content()` in
/// terms of a box's intrinsic contributions. This helper keeps the tentative
/// width in content-box space and converts definite constraint arguments
/// through `box-sizing` before clamping:
/// <https://www.w3.org/TR/css-sizing-3/#sizing-values>,
/// <https://www.w3.org/TR/css-sizing-3/#fit-content-size>, and
/// <https://www.w3.org/TR/css-sizing-3/#box-sizing>.
pub(in crate::layout) fn constrain_width_with_intrinsic<Source>(
    style: &ComputedStyle,
    value: ContentBoxLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
    percentage_basis: PercentageBasis<ContentBoxLength, Source>,
    horizontal_non_content: NonContentLength,
) -> ContentBoxLength {
    let min_content = content_box_pt(min_content.points().max(0.0));
    let max_content = content_box_pt(max_content.points().max(min_content.points()).max(0.0));
    let percentage_basis = match percentage_basis {
        PercentageBasis::Definite { value, .. } => PercentageBasis::definite(value),
        PercentageBasis::Indefinite => PercentageBasis::indefinite(),
    };
    let min_constraint = intrinsic_width_constraint(
        style.box_values.min_width.clone(),
        style.box_sizing,
        percentage_basis,
        horizontal_non_content,
        min_content,
        max_content,
    );
    let max_constraint = intrinsic_width_constraint(
        style.box_values.max_width.clone(),
        style.box_sizing,
        percentage_basis,
        horizontal_non_content,
        min_content,
        max_content,
    );
    content_box_pt(
        constrain(
            value.points().max(0.0),
            min_constraint.map(SemanticLengthExt::points),
            max_constraint.map(SemanticLengthExt::points),
        )
        .max(0.0),
    )
}

pub(in crate::layout) fn intrinsic_width_constraint(
    value: css::ComputedLengthPercentageOrAuto,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength>,
    horizontal_non_content: NonContentLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
) -> Option<ContentBoxLength> {
    match value {
        css::ComputedLengthPercentageOrAuto::Auto => None,
        css::ComputedLengthPercentageOrAuto::MinContent => Some(min_content),
        css::ComputedLengthPercentageOrAuto::MaxContent => Some(max_content),
        css::ComputedLengthPercentageOrAuto::FitContent(limit) => {
            let stretch = limit
                .map(|limit| {
                    intrinsic_constraint_length(
                        limit,
                        box_sizing,
                        percentage_basis,
                        horizontal_non_content,
                    )
                })
                .unwrap_or_else(|| {
                    percentage_basis.points().map(|basis| {
                        stretch_fit_content_box_size(
                            layout_pt(basis),
                            layout_pt(0.0),
                            horizontal_non_content,
                        )
                    })
                })?;
            Some(content_box_pt(
                max_content
                    .points()
                    .min(min_content.points().max(stretch.points()))
                    .max(0.0),
            ))
        }
        css::ComputedLengthPercentageOrAuto::LengthPercentage(value) => {
            intrinsic_constraint_length(value, box_sizing, percentage_basis, horizontal_non_content)
        }
        css::ComputedLengthPercentageOrAuto::Stretch => percentage_basis.points().map(|basis| {
            stretch_fit_content_box_size(layout_pt(basis), layout_pt(0.0), horizontal_non_content)
        }),
        css::ComputedLengthPercentageOrAuto::CalcSize(value) => calc_size_intrinsic_constraint(
            value,
            box_sizing,
            percentage_basis,
            horizontal_non_content,
            min_content,
            max_content,
        ),
    }
}

fn intrinsic_constraint_length(
    value: css::ComputedLengthPercentage,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength>,
    horizontal_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    // Intrinsic max-size contributions use an indefinite basis for cyclic
    // percentages. An authored `0%` remains a percentage in CSS syntax, so
    // `calc(45px + 0%)` is just as cyclic as `50%` here and max-width must
    // fall back to its initial value rather than impose a 45px cap. Numeric
    // resolution alone cannot express that distinction after canonicalizing
    // a length-percentage expression.
    // <https://www.w3.org/TR/css-sizing-3/#intrinsic-contribution>
    if !percentage_basis.is_definite() && value.contains_percentage() {
        return None;
    }
    let specified = used_length_percentage_with_basis(value, percentage_basis)?.points();
    Some(used_content_box_size_from_specified(
        specified,
        box_sizing,
        horizontal_non_content,
    ))
}

/// Resolves a calc-size constraint after intrinsic contributions are known.
///
/// Intrinsic sizing supplies a zero percentage basis for cyclic percentages,
/// while the retained calc-size basis is selected from the same content-box
/// contributions as CSS Sizing's intrinsic keywords. The calculation itself
/// happens in the property's specified box space before CSS box-sizing maps it
/// back to the content box:
/// <https://drafts.csswg.org/css-values-5/#calc-size> and
/// <https://www.w3.org/TR/css-sizing-3/#intrinsic-contribution>.
pub(in crate::layout) fn calc_size_intrinsic_constraint(
    value: css::CalcSize,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength>,
    non_content: NonContentLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
) -> Option<ContentBoxLength> {
    let percentage_basis_points = percentage_basis.points().unwrap_or(0.0);
    let to_specified = |content: ContentBoxLength| match box_sizing {
        BoxSizing::ContentBox => content.points(),
        BoxSizing::BorderBox => content.points() + non_content.points(),
    };
    let min_content = to_specified(min_content);
    let max_content = to_specified(max_content).max(min_content);
    let stretch = stretch_fit_content_box_size(
        layout_pt(percentage_basis_points),
        layout_pt(0.0),
        non_content,
    )
    .points();
    let fit_content = max_content.min(min_content.max(stretch));
    let basis = match &value.basis {
        css::CalcSizeBasis::Auto | css::CalcSizeBasis::MinContent => min_content,
        css::CalcSizeBasis::MaxContent => max_content,
        css::CalcSizeBasis::FitContent => fit_content,
        css::CalcSizeBasis::Stretch => stretch,
        css::CalcSizeBasis::LengthPercentage(value) => {
            used_length_percentage_with_basis(value.clone(), percentage_basis)?.points()
        }
    };
    Some(used_content_box_size_from_specified(
        value
            .used_value(
                basis,
                min_content,
                max_content,
                fit_content,
                stretch,
                percentage_basis,
            )
            .max(layout_pt(0.0))
            .points(),
        box_sizing,
        non_content,
    ))
}

/// Return non-replaced intrinsic inline-size contributions in content-box space.
///
/// CSS Sizing defines intrinsic contributions for non-replaced boxes by
/// treating cyclic percentage preferred and max sizes as their initial values
/// while resolving min-size percentages against zero. Preferred sizes such as
/// `fit-content(<length-percentage>)` are applied to the measured content
/// contribution before min/max constraints:
/// <https://www.w3.org/TR/css-sizing-3/#intrinsic-contribution> and
/// <https://www.w3.org/TR/css-sizing-3/#valdef-width-fit-content-length-percentage>.
pub(in crate::layout) fn non_replaced_intrinsic_width_contributions(
    style: &ComputedStyle,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
    horizontal_non_content: NonContentLength,
) -> (ContentBoxLength, ContentBoxLength) {
    let intrinsic_min_content = content_box_pt(min_content.points().max(0.0));
    let intrinsic_max_content = content_box_pt(
        max_content
            .points()
            .max(intrinsic_min_content.points())
            .max(0.0),
    );
    let preferred_width = non_replaced_intrinsic_preferred_width(
        style.box_values.width.clone(),
        style.box_sizing,
        horizontal_non_content,
        intrinsic_min_content,
        intrinsic_max_content,
    );
    // Constraints select their `calc-size()` intrinsic bases from the raw
    // content contributions. A ratio-derived preferred width is instead the
    // tentative size to which those constraints apply. Conflating the two
    // would make `min-width: calc-size(auto, size - 50px)` use the unbounded
    // raw contribution as the final intrinsic contribution.
    // <https://drafts.csswg.org/css-sizing-3/#intrinsic-contribution> and
    // <https://drafts.csswg.org/css-values-5/#calc-size>.
    // CSS Sizing resolves cyclic percentage min sizes against zero, while a
    // cyclic percentage preferred or max size is treated as its initial value.
    // Keep those distinct at the typed percentage-basis boundary: fixed
    // components still resolve through `Indefinite`, but max-width and
    // fit-content percentage components remain absent instead of becoming a
    // spurious zero cap.
    // <https://www.w3.org/TR/css-sizing-3/#intrinsic-contribution>
    let intrinsic_min_percentage_basis = PercentageBasis::definite(content_box_pt(0.0));
    let intrinsic_max_percentage_basis = PercentageBasis::indefinite();
    let min_constraint = intrinsic_width_constraint(
        style.box_values.min_width.clone(),
        style.box_sizing,
        intrinsic_min_percentage_basis,
        horizontal_non_content,
        intrinsic_min_content,
        intrinsic_max_content,
    )
    .map(SemanticLengthExt::points);
    let max_constraint = intrinsic_width_constraint(
        style.box_values.max_width.clone(),
        style.box_sizing,
        intrinsic_max_percentage_basis,
        horizontal_non_content,
        intrinsic_min_content,
        intrinsic_max_content,
    )
    .map(SemanticLengthExt::points);
    // A definite preferred block size transfers through a preferred aspect
    // ratio when computing a non-replaced box's intrinsic inline
    // contributions.  Resolve block min/max constraints first, in content-box
    // space, so `box-sizing: border-box` and padding affect the transferred
    // inline size exactly once.
    // <https://drafts.csswg.org/css-sizing-4/#aspect-ratio>
    let transferred_aspect_width = (!matches!(
        style.box_values.width.clone(),
        css::ComputedLengthPercentageOrAuto::LengthPercentage(_)
    ))
    .then(|| {
        let vertical_non_content = intrinsic_box_metrics(style).vertical_non_content_length();
        used_content_box_size(
            style.box_values.height.value().clone(),
            style.box_sizing,
            PercentageBasis::definite(content_box_pt(0.0)),
            vertical_non_content,
        )
        .map(|height| {
            constrain_height_with_intrinsic(
                style,
                height,
                height,
                height,
                PercentageBasis::definite(content_box_pt(0.0)),
                vertical_non_content,
            )
            .points()
        })
        .and_then(|height| {
            non_replaced_aspect_ratio_content_width(
                style,
                height,
                horizontal_non_content.points(),
                vertical_non_content.points(),
            )
        })
    })
    .flatten();
    let preferred_min_content = preferred_width
        .map(|value| value.0)
        .unwrap_or(intrinsic_min_content)
        .points();
    let preferred_max_content = preferred_width
        .map(|value| value.1)
        .unwrap_or(intrinsic_max_content)
        .points();
    // A definite block size and automatic inline size select the aspect-ratio
    // transfer as the inline preferred size. The content contribution remains
    // available above solely for the automatic min-size constraint.
    // <https://drafts.csswg.org/css-sizing-4/#aspect-ratio>.
    let (min_content, max_content) = if style.box_values.width.clone().is_auto() {
        transferred_aspect_width
            .map(|width| (width, width))
            .unwrap_or((preferred_min_content, preferred_max_content))
    } else {
        (
            preferred_min_content.max(transferred_aspect_width.unwrap_or(0.0)),
            preferred_max_content.max(transferred_aspect_width.unwrap_or(0.0)),
        )
    };
    (
        content_box_pt(constrain(min_content, min_constraint, max_constraint).max(0.0)),
        content_box_pt(constrain(max_content, min_constraint, max_constraint).max(0.0)),
    )
}

/// Apply non-replaced intrinsic inline-size constraints to content widths.
///
/// Transitional raw compatibility wrapper for
/// `non_replaced_intrinsic_width_contributions`.
pub(in crate::layout) fn constrain_non_replaced_intrinsic_widths(
    style: &ComputedStyle,
    min_content: f32,
    max_content: f32,
    horizontal_non_content: f32,
) -> (f32, f32) {
    let (min_content, max_content) = non_replaced_intrinsic_width_contributions(
        style,
        content_box_pt(min_content),
        content_box_pt(max_content),
        non_content_pt(horizontal_non_content),
    );
    (min_content.points(), max_content.points())
}

fn non_replaced_intrinsic_preferred_width(
    value: css::ComputedLengthPercentageOrAuto,
    box_sizing: BoxSizing,
    horizontal_non_content: NonContentLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
) -> Option<(ContentBoxLength, ContentBoxLength)> {
    match value {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(value) => {
            non_cyclic_content_box_length(value, box_sizing, horizontal_non_content)
                .map(|value| (value, value))
        }
        css::ComputedLengthPercentageOrAuto::MinContent => Some((min_content, min_content)),
        css::ComputedLengthPercentageOrAuto::MaxContent => Some((max_content, max_content)),
        css::ComputedLengthPercentageOrAuto::FitContent(Some(limit)) => {
            non_replaced_intrinsic_fit_content_width(
                limit,
                box_sizing,
                horizontal_non_content,
                min_content,
                max_content,
            )
            .map(|value| (value, value))
        }
        css::ComputedLengthPercentageOrAuto::CalcSize(value) => {
            let min_content_points = min_content.points();
            let max_content_points = max_content.points();
            let intrinsic_basis = |min_size: f32, max_size: f32| match &value.basis {
                css::CalcSizeBasis::Auto
                | css::CalcSizeBasis::FitContent
                | css::CalcSizeBasis::MinContent => (min_size, max_size),
                css::CalcSizeBasis::MaxContent => (max_size, max_size),
                css::CalcSizeBasis::Stretch => (0.0, 0.0),
                css::CalcSizeBasis::LengthPercentage(basis) => {
                    let basis = used_length_percentage(
                        basis.clone(),
                        PercentageBasis::definite(layout_pt(0.0)),
                    )
                    .points();
                    (basis, basis)
                }
            };
            let (min_basis, max_basis) = intrinsic_basis(min_content_points, max_content_points);
            let min_specified = value
                .used_value(
                    min_basis,
                    min_content_points,
                    max_content_points,
                    min_basis,
                    0.0,
                    PercentageBasis::definite(layout_pt(0.0)),
                )
                .points();
            let max_specified = value
                .used_value(
                    max_basis,
                    min_content_points,
                    max_content_points,
                    max_basis,
                    0.0,
                    PercentageBasis::definite(layout_pt(0.0)),
                )
                .points();
            Some((
                used_content_box_size_from_specified(
                    min_specified.max(0.0),
                    box_sizing,
                    horizontal_non_content,
                ),
                used_content_box_size_from_specified(
                    max_specified.max(0.0),
                    box_sizing,
                    horizontal_non_content,
                ),
            ))
        }
        css::ComputedLengthPercentageOrAuto::Auto
        | css::ComputedLengthPercentageOrAuto::FitContent(None)
        | css::ComputedLengthPercentageOrAuto::Stretch => None,
    }
}

fn non_replaced_intrinsic_fit_content_width(
    limit: css::ComputedLengthPercentage,
    box_sizing: BoxSizing,
    horizontal_non_content: NonContentLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
) -> Option<ContentBoxLength> {
    let limit = non_cyclic_content_box_length(limit, box_sizing, horizontal_non_content)?;
    Some(content_box_pt(
        max_content
            .points()
            .min(min_content.points().max(limit.points()))
            .max(0.0),
    ))
}

fn non_cyclic_content_box_length(
    value: css::ComputedLengthPercentage,
    box_sizing: BoxSizing,
    horizontal_non_content: NonContentLength,
) -> Option<ContentBoxLength> {
    let specified = value.length_if_no_percent()?;
    Some(used_content_box_size_from_specified(
        specified,
        box_sizing,
        horizontal_non_content,
    ))
}

/// Applies used min/max height constraints to a content height.
///
/// CSS 2.2 defines min/max height constraint application:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-heights>.
/// Applies used height constraints to a typed content-box size.
///
pub(in crate::layout) fn constrain_content_height<B>(
    style: &ComputedStyle,
    value: ContentBoxLength,
    percentage_basis: B,
) -> ContentBoxLength
where
    B: ConstraintPercentageBasis,
{
    let percentage_basis = percentage_basis.into_layout_basis();
    let vertical_non_content = intrinsic_box_metrics(style).vertical_non_content_length();
    let content_box_constraint = |value: ContentBoxLength| {
        used_content_box_size_from_specified(
            value.points().max(0.0),
            style.box_sizing,
            vertical_non_content,
        )
        .points()
    };
    content_box_pt(constrain(
        value.points(),
        used_min_height(style, percentage_basis).map(content_box_constraint),
        used_max_height(style, percentage_basis).map(content_box_constraint),
    ))
}

/// Apply block-size constraints, resolving `stretch` against the available
/// containing-block size before margins are applied.
/// <https://drafts.csswg.org/css-sizing-4/#stretch-fit-sizing>
pub(in crate::layout) fn constrain_height_with_stretch_fit(
    style: &ComputedStyle,
    value: ContentBoxLength,
    available_margin_box_height: LayoutLength,
    _vertical_margin: LayoutLength,
    vertical_non_content: NonContentLength,
) -> ContentBoxLength {
    let stretch = || {
        stretch_fit_content_box_size(
            available_margin_box_height,
            layout_pt(0.0),
            vertical_non_content,
        )
        .points()
    };
    let min = if style.box_values.min_height == css::ComputedLengthPercentageOrAuto::Stretch {
        Some(stretch())
    } else {
        used_min_height(
            style,
            PercentageBasis::definite(available_margin_box_height),
        )
        .map(|value| {
            used_content_box_size_from_specified(
                value.points(),
                style.box_sizing,
                vertical_non_content,
            )
            .points()
        })
    };
    let max = if style.box_values.max_height == css::ComputedLengthPercentageOrAuto::Stretch {
        Some(stretch())
    } else {
        used_max_height(
            style,
            PercentageBasis::definite(available_margin_box_height),
        )
        .map(|value| {
            used_content_box_size_from_specified(
                value.points(),
                style.box_sizing,
                vertical_non_content,
            )
            .points()
        })
    };
    content_box_pt(constrain(value.points(), min, max))
}

/// Applies min/max height constraints, including intrinsic sizing keywords.
///
/// CSS 2.2 applies `min-height`/`max-height` by recalculating the used height
/// with the constraining property substituted for `height`. CSS Sizing extends
/// those properties with intrinsic keywords; for normal block containers the
/// min-content and max-content block sizes are both the laid-out content block
/// size measured with cyclic block-axis percentages unresolved:
/// <https://www.w3.org/TR/CSS22/visudet.html#min-max-heights>,
/// <https://www.w3.org/TR/css-sizing-3/#sizing-values>, and
/// <https://www.w3.org/TR/css-sizing-3/#percentage-sizing>.
pub(in crate::layout) fn constrain_height_with_intrinsic<Source>(
    style: &ComputedStyle,
    value: ContentBoxLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
    percentage_basis: PercentageBasis<ContentBoxLength, Source>,
    vertical_non_content: NonContentLength,
) -> ContentBoxLength {
    let min_content = content_box_pt(min_content.points().max(0.0));
    let max_content = content_box_pt(max_content.points().max(min_content.points()).max(0.0));
    let percentage_basis = match percentage_basis {
        PercentageBasis::Definite { value, .. } => PercentageBasis::definite(value),
        PercentageBasis::Indefinite => PercentageBasis::indefinite(),
    };
    let min_constraint = intrinsic_height_constraint(
        style.box_values.min_height.clone(),
        style.box_sizing,
        percentage_basis,
        vertical_non_content,
        min_content,
        max_content,
    );
    let max_constraint = intrinsic_height_constraint(
        style.box_values.max_height.clone(),
        style.box_sizing,
        percentage_basis,
        vertical_non_content,
        min_content,
        max_content,
    );
    content_box_pt(
        constrain(
            value.points().max(0.0),
            min_constraint.map(SemanticLengthExt::points),
            max_constraint.map(SemanticLengthExt::points),
        )
        .max(0.0),
    )
}

/// Applies intrinsic block-size constraints for a non-replaced box whose
/// containing-block context is retained separately from its numeric basis.
///
/// This is the constraint counterpart of
/// [`used_non_replaced_content_box_height_or_auto`]. A content-sized context
/// substitutes `none` for a cyclic percentage `max-height`, while retaining
/// the existing zero/length-component rule for `min-height`.
/// <https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution>
pub(in crate::layout) fn constrain_non_replaced_height_with_intrinsic(
    style: &ComputedStyle,
    value: ContentBoxLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
    context: DescendantBlockPercentageContext,
    vertical_non_content: NonContentLength,
) -> ContentBoxLength {
    let mut cyclic_style;
    let style = if context.is_content_sized()
        && matches!(
            &style.box_values.max_height,
            css::ComputedLengthPercentageOrAuto::LengthPercentage(value) if value.needs_percentage_basis()
        ) {
        cyclic_style = style.clone();
        cyclic_style.box_values.max_height = css::ComputedLengthPercentageOrAuto::Auto;
        &cyclic_style
    } else {
        style
    };
    constrain_height_with_intrinsic(
        style,
        value,
        min_content,
        max_content,
        context.percentage_basis(),
        vertical_non_content,
    )
}

pub(in crate::layout) fn intrinsic_height_constraint(
    value: css::ComputedLengthPercentageOrAuto,
    box_sizing: BoxSizing,
    percentage_basis: PercentageBasis<ContentBoxLength>,
    vertical_non_content: NonContentLength,
    min_content: ContentBoxLength,
    max_content: ContentBoxLength,
) -> Option<ContentBoxLength> {
    match value {
        css::ComputedLengthPercentageOrAuto::Auto => None,
        css::ComputedLengthPercentageOrAuto::MinContent => Some(min_content),
        css::ComputedLengthPercentageOrAuto::MaxContent => Some(max_content),
        css::ComputedLengthPercentageOrAuto::FitContent(limit) => {
            let stretch = limit
                .map(|limit| {
                    intrinsic_constraint_length(
                        limit,
                        box_sizing,
                        percentage_basis,
                        vertical_non_content,
                    )
                })
                .unwrap_or_else(|| {
                    percentage_basis.points().map(|basis| {
                        stretch_fit_content_box_size(
                            layout_pt(basis),
                            layout_pt(0.0),
                            vertical_non_content,
                        )
                    })
                })?;
            Some(content_box_pt(
                max_content
                    .points()
                    .min(min_content.points().max(stretch.points()))
                    .max(0.0),
            ))
        }
        css::ComputedLengthPercentageOrAuto::LengthPercentage(value) => {
            intrinsic_constraint_length(value, box_sizing, percentage_basis, vertical_non_content)
        }
        css::ComputedLengthPercentageOrAuto::Stretch => percentage_basis.points().map(|basis| {
            stretch_fit_content_box_size(layout_pt(basis), layout_pt(0.0), vertical_non_content)
        }),
        css::ComputedLengthPercentageOrAuto::CalcSize(value) => calc_size_intrinsic_constraint(
            value,
            box_sizing,
            percentage_basis,
            vertical_non_content,
            min_content,
            max_content,
        ),
    }
}

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

    fn length_auto(value: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_points(value),
        )
    }

    fn percent_auto(value: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_percent(value),
        )
    }

    fn fit_content(points: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::FitContent(Some(
            css::ComputedLengthPercentage::from_points(points),
        ))
    }

    fn fit_content_percent(percent: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::FitContent(Some(
            css::ComputedLengthPercentage::from_percent(percent),
        ))
    }

    fn intrinsic_width_constraint_result(style: &ComputedStyle, value: f32) -> f32 {
        constrain_width_with_intrinsic(
            style,
            content_box_pt(value),
            content_box_pt(60.0),
            content_box_pt(120.0),
            PercentageBasis::definite(content_box_pt(300.0)),
            non_content_pt(0.0),
        )
        .points()
    }

    #[test]
    fn intrinsic_fit_content_min_width_clamps_tentative_content_width() {
        let mut style = ComputedStyle::initial();
        style.box_values.min_width = fit_content(100.0);

        assert_eq!(intrinsic_width_constraint_result(&style, 10.0), 100.0);
    }

    #[test]
    fn intrinsic_fit_content_max_width_clamps_tentative_content_width() {
        let mut style = ComputedStyle::initial();
        style.box_values.max_width = fit_content(100.0);

        assert_eq!(intrinsic_width_constraint_result(&style, 150.0), 100.0);
    }

    #[test]
    fn intrinsic_min_and_max_content_constraints_clamp_content_width() {
        let mut min_style = ComputedStyle::initial();
        min_style.box_values.min_width = css::ComputedLengthPercentageOrAuto::MinContent;
        let mut max_style = ComputedStyle::initial();
        max_style.box_values.max_width = css::ComputedLengthPercentageOrAuto::MaxContent;

        assert_eq!(intrinsic_width_constraint_result(&min_style, 10.0), 60.0);
        assert_eq!(intrinsic_width_constraint_result(&max_style, 150.0), 120.0);
    }

    #[test]
    fn intrinsic_width_constraints_convert_border_box_limits_to_content_box() {
        let mut style = ComputedStyle::initial();
        style.box_sizing = BoxSizing::BorderBox;
        style.box_values.min_width = fit_content(100.0);

        let constrained = constrain_width_with_intrinsic(
            &style,
            content_box_pt(10.0),
            content_box_pt(60.0),
            content_box_pt(120.0),
            PercentageBasis::definite(content_box_pt(300.0)),
            non_content_pt(20.0),
        );

        assert_eq!(constrained.points(), 80.0);
    }

    #[test]
    fn non_replaced_intrinsic_width_uses_fit_content_length_preferred_size() {
        let mut style = ComputedStyle::initial();
        style.box_values.width = fit_content(100.0);

        let contributions = non_replaced_intrinsic_width_contributions(
            &style,
            content_box_pt(60.0),
            content_box_pt(120.0),
            non_content_pt(0.0),
        );

        assert_eq!(contributions.0.points(), 100.0);
        assert_eq!(contributions.1.points(), 100.0);
    }

    #[test]
    fn non_replaced_intrinsic_width_treats_fit_content_percentage_as_auto() {
        let mut style = ComputedStyle::initial();
        style.box_values.width = fit_content_percent(0.5);

        let contributions = non_replaced_intrinsic_width_contributions(
            &style,
            content_box_pt(100.0),
            content_box_pt(200.0),
            non_content_pt(0.0),
        );

        assert_eq!(contributions.0.points(), 100.0);
        assert_eq!(contributions.1.points(), 200.0);
    }

    #[test]
    fn non_replaced_intrinsic_width_converts_border_box_preferred_size() {
        let mut style = ComputedStyle::initial();
        style.box_sizing = BoxSizing::BorderBox;
        style.box_values.width = length_auto(100.0);

        let contributions = non_replaced_intrinsic_width_contributions(
            &style,
            content_box_pt(60.0),
            content_box_pt(120.0),
            non_content_pt(20.0),
        );

        assert_eq!(contributions.0.points(), 80.0);
        assert_eq!(contributions.1.points(), 80.0);
    }

    #[test]
    fn non_replaced_intrinsic_width_preserves_min_and_cyclic_max_constraints() {
        let mut style = ComputedStyle::initial();
        style.box_values.min_width = percent_auto(0.5);
        style.box_values.max_width = fit_content_percent(0.5);

        let contributions = non_replaced_intrinsic_width_contributions(
            &style,
            content_box_pt(20.0),
            content_box_pt(120.0),
            non_content_pt(0.0),
        );

        assert_eq!(contributions.0.points(), 20.0);
        assert_eq!(contributions.1.points(), 120.0);
    }

    #[test]
    fn cyclic_min_height_keeps_the_fixed_calc_component() {
        let mut style = ComputedStyle::initial();
        style.box_values.min_height = css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_affine(layout_pt(18.75), 0.5, true),
        );

        let used = used_min_height(&style, PercentageBasis::<ContentBoxLength>::indefinite())
            .expect("a fixed calc component remains a used min-height");

        assert_eq!(used.points(), 18.75);
    }

    #[test]
    fn content_sized_context_uses_initial_preferred_and_maximum_values() {
        let mut style = ComputedStyle::initial();
        let cyclic_calc = css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_affine(layout_pt(10.0), 0.5, true),
        );
        style
            .box_values
            .height
            .replace_with_used(cyclic_calc.clone());
        style.box_values.max_height = percent(1.0);
        style.box_values.min_height = cyclic_calc;

        let content_sized = DescendantBlockPercentageContext::ContentSized;
        assert!(
            used_non_replaced_content_box_height_or_auto(
                &style,
                content_sized,
                non_content_pt(0.0),
            )
            .is_none()
        );
        assert!(used_non_replaced_max_height(&style, content_sized).is_none());
        assert_eq!(
            used_min_height(&style, content_sized.percentage_basis())
                .expect("cyclic minimum retains its length component")
                .points(),
            10.0,
        );
    }

    #[test]
    fn definite_context_resolves_preferred_and_maximum_percentages() {
        let mut style = ComputedStyle::initial();
        style.box_values.height.replace_with_used(
            css::ComputedLengthPercentageOrAuto::LengthPercentage(
                css::ComputedLengthPercentage::from_affine(layout_pt(10.0), 0.5, true),
            ),
        );
        style.box_values.max_height = percent(1.0);
        let context = DescendantBlockPercentageContext::definite(
            content_box_pt(200.0),
            BlockSizeBasisSource::ContainingBlock,
        );

        assert_eq!(
            used_non_replaced_content_box_height_or_auto(&style, context, non_content_pt(0.0))
                .expect("a definite basis resolves the preferred size")
                .points(),
            110.0,
        );
        assert_eq!(
            used_non_replaced_max_height(&style, context)
                .expect("a definite basis resolves the maximum")
                .points(),
            200.0,
        );
    }
    #[test]
    fn typed_constraint_entry_points_preserve_content_box_lengths() {
        let style = ComputedStyle::initial();
        let width: ContentBoxLength = constrain_content_width(
            &style,
            content_box_pt(42.0),
            PercentageBasis::definite(layout_pt(100.0)),
        );
        let height: ContentBoxLength = constrain_content_height(
            &style,
            content_box_pt(24.0),
            PercentageBasis::definite(layout_pt(100.0)),
        );

        assert_eq!(width.points(), 42.0);
        assert_eq!(height.points(), 24.0);
    }
    fn length(points: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_points(points),
        )
    }

    fn percent(percent: f32) -> css::ComputedLengthPercentageOrAuto {
        css::ComputedLengthPercentageOrAuto::LengthPercentage(
            css::ComputedLengthPercentage::from_percent(percent),
        )
    }

    #[test]
    fn stretch_fit_content_size_is_non_negative_after_borders() {
        let non_content = 200.0;
        let content = stretch_fit_content_box_size(
            layout_pt(0.0),
            layout_pt(0.0),
            non_content_pt(non_content),
        )
        .points();

        assert_eq!(content, 0.0);
        assert_eq!(content + non_content, 200.0);
    }

    #[test]
    fn used_content_box_size_keeps_content_box_specified_size() {
        let content = used_content_box_size(
            length(120.0),
            BoxSizing::ContentBox,
            PercentageBasis::definite(content_box_pt(300.0)),
            non_content_pt(40.0),
        )
        .expect("content-box length should resolve");

        assert_eq!(content.points(), 120.0);
    }

    #[test]
    fn used_content_box_size_subtracts_border_box_non_content_and_clamps() {
        let content = used_content_box_size(
            length(100.0),
            BoxSizing::BorderBox,
            PercentageBasis::definite(content_box_pt(300.0)),
            non_content_pt(150.0),
        )
        .expect("border-box length should resolve");

        assert_eq!(content.points(), 0.0);
    }

    #[test]
    fn stretch_fit_content_box_size_returns_typed_non_negative_content() {
        let content =
            stretch_fit_content_box_size(layout_pt(100.0), layout_pt(30.0), non_content_pt(120.0));

        assert_eq!(content.points(), 0.0);
    }

    #[test]
    fn used_content_box_size_indefinite_basis_resolves_lengths_not_percentages() {
        let length_content = used_content_box_size_with_basis(
            length(42.0),
            BoxSizing::ContentBox,
            PercentageBasis::<ContentBoxLength>::indefinite(),
            non_content_pt(10.0),
        )
        .expect("length-only value should resolve without a basis");
        let percentage_content = used_content_box_size_with_basis(
            percent(0.5),
            BoxSizing::ContentBox,
            PercentageBasis::<ContentBoxLength>::indefinite(),
            non_content_pt(10.0),
        );

        assert_eq!(length_content.points(), 42.0);
        assert!(percentage_content.is_none());
    }

    #[test]
    fn resolved_aspect_ratio_distinguishes_content_and_border_box_with_asymmetric_padding() {
        let content_box = ResolvedAspectRatio::new(
            2.0,
            AspectRatioCalculationBox::ContentBox,
            non_content_pt(40.0),
            non_content_pt(10.0),
        )
        .unwrap();
        let border_box = ResolvedAspectRatio::new(
            2.0,
            AspectRatioCalculationBox::BorderBox,
            non_content_pt(40.0),
            non_content_pt(10.0),
        )
        .unwrap();

        assert_eq!(
            content_box
                .height_from_width(content_box_pt(100.0))
                .points(),
            50.0
        );
        assert_eq!(
            border_box.height_from_width(content_box_pt(100.0)).points(),
            60.0
        );
        assert_eq!(
            content_box.width_from_height(content_box_pt(50.0)).points(),
            100.0
        );
        assert_eq!(
            border_box.width_from_height(content_box_pt(50.0)).points(),
            80.0
        );
    }

    #[test]
    fn aspect_ratio_constraints_transfer_minimums_and_maximums_in_both_directions() {
        let ratio = ResolvedAspectRatio::new(
            2.0,
            AspectRatioCalculationBox::ContentBox,
            non_content_pt(0.0),
            non_content_pt(0.0),
        )
        .unwrap();
        let resolved = ResolvedAspectRatioConstraints::resolve(
            ratio,
            AspectRatioAxisConstraints {
                minimum: Some(content_box_pt(80.0)),
                maximum: Some(content_box_pt(240.0)),
                ..Default::default()
            },
            AspectRatioAxisConstraints::default(),
        );

        assert_eq!(resolved.height.minimum.unwrap().points(), 40.0);
        assert_eq!(resolved.height.maximum.unwrap().points(), 120.0);

        let reverse = ResolvedAspectRatioConstraints::resolve(
            ratio,
            AspectRatioAxisConstraints::default(),
            AspectRatioAxisConstraints {
                minimum: Some(content_box_pt(30.0)),
                maximum: Some(content_box_pt(90.0)),
                ..Default::default()
            },
        );
        assert_eq!(reverse.width.minimum.unwrap().points(), 60.0);
        assert_eq!(reverse.width.maximum.unwrap().points(), 180.0);
    }

    #[test]
    fn aspect_ratio_constraints_do_not_replace_a_larger_content_minimum() {
        let ratio = ResolvedAspectRatio::new(
            2.0,
            AspectRatioCalculationBox::ContentBox,
            non_content_pt(0.0),
            non_content_pt(0.0),
        )
        .unwrap();
        let resolved = ResolvedAspectRatioConstraints::resolve(
            ratio,
            AspectRatioAxisConstraints {
                minimum: Some(content_box_pt(100.0)),
                ..Default::default()
            },
            AspectRatioAxisConstraints {
                minimum: Some(content_box_pt(20.0)),
                ..Default::default()
            },
        );

        assert_eq!(resolved.width.minimum.unwrap().points(), 100.0);
        assert_eq!(
            resolved.constrain_width(content_box_pt(50.0)).points(),
            100.0
        );
    }
}