fasti 0.2.0

Dates, calendars, business-day conventions and day-count fractions for financial code. Native Rust, no_std, float-free; designed after QuantLib's ql/time.
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
//! Dates and their building blocks: [`Date`], [`Year`], [`Month`],
//! [`Weekday`], and [`Ordinal`].
//!
//! [`Date`] is a newtype over [`u32`] counting days from 1901-01-01 (serial
//! zero); supported range 1901-01-01..=2199-12-31, else [`TimeError`].

use crate::{Period, TimeError};
use core::fmt;
use core::ops::{Add, Range, Sub};

// ---- Range constants ----------------------------------------------------

const EPOCH_YEAR: u16 = 1901;
const END_YEAR: u16 = 2199;
const NUM_YEARS: u16 = END_YEAR - EPOCH_YEAR + 1;

const fn is_leap(year: u16) -> bool {
    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}

/// `CUMULATIVE[i]` = days from 1901-01-01 to (1901 + i)-01-01; the entry
/// at index `NUM_YEARS` is one past the last valid day.
const CUMULATIVE: [u32; NUM_YEARS as usize + 1] = {
    let mut out = [0u32; NUM_YEARS as usize + 1];
    let mut i: u16 = 0;
    while i < NUM_YEARS {
        let year = EPOCH_YEAR + i;
        let len: u32 = if is_leap(year) { 366 } else { 365 };
        out[i as usize + 1] = out[i as usize] + len;
        i += 1;
    }
    out
};

const MAX_SERIAL: u32 = CUMULATIVE[NUM_YEARS as usize] - 1;

/// 0-based day-of-year at the start of month `i + 1`, non-leap year;
/// entry 12 is a sentinel.
const MONTH_OFFSETS_NONLEAP: [u32; 13] =
    [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];

/// As [`MONTH_OFFSETS_NONLEAP`], for a leap year.
const MONTH_OFFSETS_LEAP: [u32; 13] = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];

// ---- Year ---------------------------------------------------------------

/// A year in the range 1901..=2199.
///
/// ```
/// use fasti::Year;
/// let y = Year::new(2026)?;
/// assert_eq!(y.get(), 2026);
/// assert!(!y.is_leap());
/// assert!(Year::new(1900).is_err());
/// # Ok::<(), fasti::TimeError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Year(u16);

impl Year {
    /// The earliest supported year, 1901.
    pub const MIN: Self = Self(EPOCH_YEAR);

    /// The latest supported year, 2199.
    pub const MAX: Self = Self(END_YEAR);

    /// Construct a [`Year`], refusing values outside `1901..=2199`.
    pub const fn new(year: u16) -> Result<Self, TimeError> {
        if year < EPOCH_YEAR || year > END_YEAR {
            Err(TimeError::YearOutOfRange)
        } else {
            Ok(Self(year))
        }
    }

    /// Construct a [`Year`] from a compile-time literal; an out-of-range
    /// value is a compile error, not a runtime panic.
    ///
    /// ```
    /// use fasti::Year;
    /// const MLK_FEDERAL_FROM: Year = Year::literal(1986);
    /// assert_eq!(MLK_FEDERAL_FROM.get(), 1986);
    /// ```
    ///
    /// ```compile_fail
    /// use fasti::Year;
    /// // Compile error: argument out of range.
    /// const BAD: Year = Year::literal(1800);
    /// ```
    #[must_use]
    #[allow(clippy::panic)]
    pub const fn literal(year: u16) -> Self {
        match Self::new(year) {
            Ok(y) => y,
            // Reached only at const-eval time — a compile error, not a runtime panic.
            Err(_) => panic!("Year::literal: argument must be in 1901..=2199"),
        }
    }

    /// Return the underlying year as a [`u16`].
    ///
    /// ```
    /// use fasti::Year;
    /// assert_eq!(Year::new(2026)?.get(), 2026);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }

    /// `true` iff this is a Gregorian leap year.
    ///
    /// ```
    /// use fasti::Year;
    /// assert!(Year::new(2000)?.is_leap());   // div by 400
    /// assert!(!Year::new(2100)?.is_leap());  // div by 100 but not 400
    /// assert!(Year::new(2024)?.is_leap());   // div by 4 only
    /// assert!(!Year::new(2025)?.is_leap());
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn is_leap(self) -> bool {
        is_leap(self.0)
    }

    /// Number of days in the year (365 or 366).
    ///
    /// ```
    /// use fasti::Year;
    /// assert_eq!(Year::new(2024)?.length(), 366);
    /// assert_eq!(Year::new(2025)?.length(), 365);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn length(self) -> u16 {
        if self.is_leap() { 366 } else { 365 }
    }
}

impl fmt::Display for Year {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ---- Month --------------------------------------------------------------

/// A month of the year, discriminant 1..=12.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Month {
    /// January
    Jan = 1,
    /// February
    Feb = 2,
    /// March
    Mar = 3,
    /// April
    Apr = 4,
    /// May
    May = 5,
    /// June
    Jun = 6,
    /// July
    Jul = 7,
    /// August
    Aug = 8,
    /// September
    Sep = 9,
    /// October
    Oct = 10,
    /// November
    Nov = 11,
    /// December
    Dec = 12,
}

impl Month {
    /// Month number, `Jan => 1`, ..., `Dec => 12`.
    ///
    /// ```
    /// use fasti::Month;
    /// assert_eq!(Month::Jul.get(), 7);
    /// ```
    #[must_use]
    pub const fn get(self) -> u8 {
        self as u8
    }

    /// Construct a [`Month`] from a 1-based month number, refusing
    /// anything outside `1..=12`.
    ///
    /// ```
    /// use fasti::{Month, TimeError};
    /// assert_eq!(Month::try_from_u8(7)?, Month::Jul);
    /// assert_eq!(Month::try_from_u8(0), Err(TimeError::MonthOutOfRange));
    /// assert_eq!(Month::try_from_u8(13), Err(TimeError::MonthOutOfRange));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn try_from_u8(month: u8) -> Result<Self, TimeError> {
        match month {
            1 => Ok(Self::Jan),
            2 => Ok(Self::Feb),
            3 => Ok(Self::Mar),
            4 => Ok(Self::Apr),
            5 => Ok(Self::May),
            6 => Ok(Self::Jun),
            7 => Ok(Self::Jul),
            8 => Ok(Self::Aug),
            9 => Ok(Self::Sep),
            10 => Ok(Self::Oct),
            11 => Ok(Self::Nov),
            12 => Ok(Self::Dec),
            _ => Err(TimeError::MonthOutOfRange),
        }
    }

    /// Number of days in this month for the given [`Year`], with February
    /// returning 28 or 29 as appropriate.
    ///
    /// ```
    /// use fasti::{Month, Year};
    /// assert_eq!(Month::Feb.length(Year::new(2024)?), 29); // leap
    /// assert_eq!(Month::Feb.length(Year::new(2025)?), 28);
    /// assert_eq!(Month::Apr.length(Year::new(2025)?), 30);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn length(self, year: Year) -> u8 {
        match self {
            Self::Jan | Self::Mar | Self::May | Self::Jul | Self::Aug | Self::Oct | Self::Dec => 31,
            Self::Apr | Self::Jun | Self::Sep | Self::Nov => 30,
            Self::Feb => {
                if year.is_leap() {
                    29
                } else {
                    28
                }
            }
        }
    }
}

impl fmt::Display for Month {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Jan => "Jan",
            Self::Feb => "Feb",
            Self::Mar => "Mar",
            Self::Apr => "Apr",
            Self::May => "May",
            Self::Jun => "Jun",
            Self::Jul => "Jul",
            Self::Aug => "Aug",
            Self::Sep => "Sep",
            Self::Oct => "Oct",
            Self::Nov => "Nov",
            Self::Dec => "Dec",
        };
        f.write_str(name)
    }
}

// ---- Weekday ------------------------------------------------------------

/// Day of the week. Discriminants follow ISO 8601: Monday = 1 .. Sunday = 7.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Weekday {
    /// Monday — ISO 1.
    Mon = 1,
    /// Tuesday — ISO 2.
    Tue = 2,
    /// Wednesday — ISO 3.
    Wed = 3,
    /// Thursday — ISO 4.
    Thu = 4,
    /// Friday — ISO 5.
    Fri = 5,
    /// Saturday — ISO 6.
    Sat = 6,
    /// Sunday — ISO 7.
    Sun = 7,
}

impl Weekday {
    /// The ISO 8601 weekday number: Monday = 1 .. Sunday = 7.
    ///
    /// ```
    /// use fasti::Weekday;
    /// assert_eq!(Weekday::Mon.get(), 1);
    /// assert_eq!(Weekday::Sun.get(), 7);
    /// ```
    #[must_use]
    pub const fn get(self) -> u8 {
        self as u8
    }

    /// Construct a [`Weekday`] from an ISO weekday number (`1..=7`),
    /// refusing anything outside that range.
    ///
    /// ```
    /// use fasti::{Weekday, TimeError};
    /// assert_eq!(Weekday::try_from_u8(1)?, Weekday::Mon);
    /// assert_eq!(Weekday::try_from_u8(7)?, Weekday::Sun);
    /// assert_eq!(Weekday::try_from_u8(0), Err(TimeError::WeekdayOutOfRange));
    /// assert_eq!(Weekday::try_from_u8(8), Err(TimeError::WeekdayOutOfRange));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn try_from_u8(weekday: u8) -> Result<Self, TimeError> {
        match weekday {
            1 => Ok(Self::Mon),
            2 => Ok(Self::Tue),
            3 => Ok(Self::Wed),
            4 => Ok(Self::Thu),
            5 => Ok(Self::Fri),
            6 => Ok(Self::Sat),
            7 => Ok(Self::Sun),
            _ => Err(TimeError::WeekdayOutOfRange),
        }
    }
}

impl fmt::Display for Weekday {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Mon => "Mon",
            Self::Tue => "Tue",
            Self::Wed => "Wed",
            Self::Thu => "Thu",
            Self::Fri => "Fri",
            Self::Sat => "Sat",
            Self::Sun => "Sun",
        };
        f.write_str(name)
    }
}

// ---- Ordinal ------------------------------------------------------------

/// An ordinal position within a month for nth-weekday rules. "First" =
/// first occurrence, "Fifth" = fifth (which may not exist in every month).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Ordinal {
    /// 1st occurrence.
    First = 1,
    /// 2nd occurrence.
    Second = 2,
    /// 3rd occurrence.
    Third = 3,
    /// 4th occurrence.
    Fourth = 4,
    /// 5th occurrence (may not exist in all month/weekday pairs).
    Fifth = 5,
}

impl Ordinal {
    /// The underlying 1-based discriminant.
    ///
    /// ```
    /// use fasti::Ordinal;
    /// assert_eq!(Ordinal::Third.get(), 3);
    /// ```
    #[must_use]
    pub const fn get(self) -> u8 {
        self as u8
    }

    /// Construct an [`Ordinal`] from a 1-based value, refusing anything
    /// outside `1..=5`.
    ///
    /// ```
    /// use fasti::{Ordinal, TimeError};
    /// assert_eq!(Ordinal::try_from_u8(3)?, Ordinal::Third);
    /// assert_eq!(Ordinal::try_from_u8(0), Err(TimeError::OrdinalOutOfRange));
    /// assert_eq!(Ordinal::try_from_u8(6), Err(TimeError::OrdinalOutOfRange));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn try_from_u8(n: u8) -> Result<Self, TimeError> {
        match n {
            1 => Ok(Self::First),
            2 => Ok(Self::Second),
            3 => Ok(Self::Third),
            4 => Ok(Self::Fourth),
            5 => Ok(Self::Fifth),
            _ => Err(TimeError::OrdinalOutOfRange),
        }
    }
}

impl fmt::Display for Ordinal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::First => "First",
            Self::Second => "Second",
            Self::Third => "Third",
            Self::Fourth => "Fourth",
            Self::Fifth => "Fifth",
        };
        f.write_str(name)
    }
}

// ---- Date ---------------------------------------------------------------

/// A calendar date in the supported range 1901-01-01..=2199-12-31.
///
/// Internally a [`u32`] count of days since 1901-01-01 (inclusive).
///
/// ```
/// use fasti::{Date, Month, Weekday};
///
/// let d = Date::from_ymd(2026, Month::Jul, 4)?;
/// assert_eq!(d.year().get(), 2026);
/// assert_eq!(d.month(), Month::Jul);
/// assert_eq!(d.day(), 4);
/// assert_eq!(d.weekday(), Weekday::Sat);
/// # Ok::<(), fasti::TimeError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Date(u32);

impl Date {
    /// The earliest representable date, 1901-01-01.
    pub const MIN: Self = Self(0);

    /// The latest representable date, 2199-12-31.
    pub const MAX: Self = Self(MAX_SERIAL);

    /// Construct a [`Date`] from year, month, and day. Refuses
    /// out-of-range years, zero days, and days exceeding the month length
    /// (accounting for leap years).
    pub const fn from_ymd(year: u16, month: Month, day: u8) -> Result<Self, TimeError> {
        let y = match Year::new(year) {
            Ok(y) => y,
            Err(e) => return Err(e),
        };
        let len = month.length(y);
        if day == 0 || day > len {
            return Err(TimeError::DayOutOfRange);
        }
        let year_idx = (year - EPOCH_YEAR) as usize;
        let year_start = CUMULATIVE[year_idx];
        let month_offset = if y.is_leap() {
            MONTH_OFFSETS_LEAP[(month.get() - 1) as usize]
        } else {
            MONTH_OFFSETS_NONLEAP[(month.get() - 1) as usize]
        };
        Ok(Self(year_start + month_offset + day as u32 - 1))
    }

    /// Construct a [`Date`] from compile-time year, month, and day
    /// literals; an invalid date is a compile error, not a runtime panic.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// const CARTER_FUNERAL: Date = Date::literal(2025, Month::Jan, 9);
    /// assert_eq!(CARTER_FUNERAL.year().get(), 2025);
    /// ```
    ///
    /// ```compile_fail
    /// use fasti::{Date, Month};
    /// // Compile error: Feb 30 does not exist.
    /// const BAD: Date = Date::literal(2025, Month::Feb, 30);
    /// ```
    #[must_use]
    #[allow(clippy::panic)]
    pub const fn literal(year: u16, month: Month, day: u8) -> Self {
        match Self::from_ymd(year, month, day) {
            Ok(d) => d,
            // Reached only at const-eval time — a compile error, not a runtime panic.
            Err(_) => panic!("Date::literal: invalid year/month/day"),
        }
    }

    /// Construct a [`Date`] from a serial day count relative to
    /// 1901-01-01 (serial 0). Refuses values outside the supported range.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// assert_eq!(Date::from_serial(0)?, Date::from_ymd(1901, Month::Jan, 1)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn from_serial(serial: u32) -> Result<Self, TimeError> {
        if serial > MAX_SERIAL {
            Err(TimeError::DateOutOfRange)
        } else {
            Ok(Self(serial))
        }
    }

    /// The underlying serial: days since 1901-01-01 inclusive (serial 0).
    #[must_use]
    pub const fn serial(self) -> u32 {
        self.0
    }

    /// The [`Year`] component.
    #[must_use]
    pub const fn year(self) -> Year {
        // A Gregorian cycle is 146 097 days over 400 years, so the
        // serial names its own year index to within one (pinned
        // exhaustively by `year_is_correct_for_every_serial`); the
        // loops absorb the remainder. The upward loop needs no bounds
        // check: `CUMULATIVE`'s final entry is one past the last valid
        // day, so it never compares `<=` a valid serial. `serial * 400`
        // peaks below 44 million — no overflow.
        let serial = self.0;
        // `serial * 400 / 146_097 < NUM_YEARS` for every valid serial, so
        // the `u32 -> u16` narrowing is safe and the index in bounds.
        #[allow(clippy::cast_possible_truncation)]
        let mut idx = (serial * 400 / 146_097) as u16;
        while CUMULATIVE[idx as usize + 1] <= serial {
            idx += 1;
        }
        while CUMULATIVE[idx as usize] > serial {
            idx -= 1;
        }
        Year(EPOCH_YEAR + idx)
    }

    /// Decompose into `(year, month, day-of-month)`.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let d = Date::from_ymd(2026, Month::Jul, 4)?;
    /// let (y, m, dom) = d.to_ymd();
    /// assert_eq!((y.get(), m, dom), (2026, Month::Jul, 4));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn to_ymd(self) -> (Year, Month, u8) {
        let y = self.year();
        let year_idx = (y.0 - EPOCH_YEAR) as usize;
        let doy = self.0 - CUMULATIVE[year_idx];
        let offsets = if y.is_leap() {
            &MONTH_OFFSETS_LEAP
        } else {
            &MONTH_OFFSETS_NONLEAP
        };
        let mut m: usize = 0;
        while m + 1 < 13 && offsets[m + 1] <= doy {
            m += 1;
        }
        let month = match m {
            0 => Month::Jan,
            1 => Month::Feb,
            2 => Month::Mar,
            3 => Month::Apr,
            4 => Month::May,
            5 => Month::Jun,
            6 => Month::Jul,
            7 => Month::Aug,
            8 => Month::Sep,
            9 => Month::Oct,
            10 => Month::Nov,
            _ => Month::Dec,
        };
        // `doy - offsets[m] + 1` is bounded 1..=31, so the `as u8` narrowing is safe.
        #[allow(clippy::cast_possible_truncation)]
        let day_of_month = (doy - offsets[m] + 1) as u8;
        (y, month, day_of_month)
    }

    /// The [`Month`] component.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// assert_eq!(Date::from_ymd(2026, Month::Jul, 4)?.month(), Month::Jul);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn month(self) -> Month {
        let (_, m, _) = self.to_ymd();
        m
    }

    /// The day-of-month component, `1..=31`.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// assert_eq!(Date::from_ymd(2026, Month::Jul, 4)?.day(), 4);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn day(self) -> u8 {
        let (_, _, d) = self.to_ymd();
        d
    }

    /// The 1-indexed day of the year, `1..=366`.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// assert_eq!(Date::from_ymd(2024, Month::Jan, 1)?.day_of_year(), 1);
    /// assert_eq!(Date::from_ymd(2024, Month::Dec, 31)?.day_of_year(), 366); // leap
    /// assert_eq!(Date::from_ymd(2025, Month::Dec, 31)?.day_of_year(), 365);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn day_of_year(self) -> u16 {
        let y = self.year();
        let year_idx = (y.0 - EPOCH_YEAR) as usize;
        // Result is 1..=366, so the `u32 -> u16` narrowing is safe.
        #[allow(clippy::cast_possible_truncation)]
        let doy = (self.0 - CUMULATIVE[year_idx] + 1) as u16;
        doy
    }

    /// The day of the week.
    ///
    /// ```
    /// use fasti::{Date, Month, Weekday};
    /// assert_eq!(
    ///     Date::from_ymd(2026, Month::Jul, 4)?.weekday(),
    ///     Weekday::Sat,
    /// );
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn weekday(self) -> Weekday {
        // Serial 0 (1901-01-01) is Tuesday, so `(serial + 1) % 7` gives 0..=6 keyed Mon..Sun.
        match (self.0 + 1) % 7 {
            0 => Weekday::Mon,
            1 => Weekday::Tue,
            2 => Weekday::Wed,
            3 => Weekday::Thu,
            4 => Weekday::Fri,
            5 => Weekday::Sat,
            _ => Weekday::Sun,
        }
    }

    /// Add `n` days, returning [`TimeError::DateOutOfRange`] if the result
    /// would fall outside the supported range.
    ///
    /// ```
    /// use fasti::{Date, Month, TimeError};
    /// let d = Date::from_ymd(2026, Month::Feb, 28)?;
    /// assert_eq!(d.add_days(1)?, Date::from_ymd(2026, Month::Mar, 1)?);
    /// assert_eq!(Date::MAX.add_days(1), Err(TimeError::DateOutOfRange));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn add_days(self, n: i32) -> Result<Self, TimeError> {
        // Widen to `i64` so any `u32 + i32` sum fits and can be bounds-checked before narrowing.
        let target = self.0 as i64 + n as i64;
        if target < 0 || target > MAX_SERIAL as i64 {
            return Err(TimeError::DateOutOfRange);
        }
        // `target` is in `0..=MAX_SERIAL`, so the `i64 -> u32` narrowing is safe.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let serial = target as u32;
        Ok(Self(serial))
    }

    /// Signed difference `self - other` in days. Returns a negative value
    /// when `self` precedes `other`.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let a = Date::from_ymd(2026, Month::Jan, 1)?;
    /// let b = Date::from_ymd(2026, Month::Jan, 31)?;
    /// assert_eq!(b.days_since(a), 30);
    /// assert_eq!(a.days_since(b), -30);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn days_since(self, other: Self) -> i32 {
        // Widen to `i64` to avoid `u32 - u32` underflow.
        let diff = self.0 as i64 - other.0 as i64;
        // Bounded by `|diff| <= MAX_SERIAL`; `i64 -> i32` is safe.
        #[allow(clippy::cast_possible_truncation)]
        let diff_i32 = diff as i32;
        diff_i32
    }

    /// Add `n` calendar months, clamping the day-of-month to the new
    /// month's length. Matches `QuantLib`'s `Date::advance` semantics.
    /// Returns [`TimeError::DateOutOfRange`] if the result is out of range.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let jan31 = Date::from_ymd(2026, Month::Jan, 31)?;
    /// assert_eq!(jan31.add_months(1)?, Date::from_ymd(2026, Month::Feb, 28)?);
    /// let feb28_2024 = Date::from_ymd(2024, Month::Feb, 28)?;
    /// assert_eq!(feb28_2024.add_months(12)?, Date::from_ymd(2025, Month::Feb, 28)?);
    /// let apr30 = Date::from_ymd(2026, Month::Apr, 30)?;
    /// assert_eq!(apr30.add_months(-2)?, Date::from_ymd(2026, Month::Feb, 28)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn add_months(self, n: i32) -> Result<Self, TimeError> {
        let (year, month, day) = self.to_ymd();
        // Zero-based month index in `i32` — all in-range (year, month) pairs fit.
        let total_months = year.get() as i32 * 12 + (month.get() as i32 - 1);
        let Some(new_total) = total_months.checked_add(n) else {
            return Err(TimeError::DateOutOfRange);
        };
        // Euclidean div/rem stay correct if `new_total` is negative.
        let target_year_i32 = new_total.div_euclid(12);
        let new_month_idx = new_total.rem_euclid(12);
        if target_year_i32 < Year::MIN.get() as i32 || target_year_i32 > Year::MAX.get() as i32 {
            return Err(TimeError::DateOutOfRange);
        }
        // `target_year_i32` is bounded to 1901..=2199, a `u16` range; narrowing is safe.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let new_year_u16 = target_year_i32 as u16;
        // `new_month_idx` is bounded to 0..=11, a `u8` range.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let new_month = match Month::try_from_u8((new_month_idx as u8) + 1) {
            Ok(found) => found,
            Err(err) => return Err(err),
        };
        let target_year = match Year::new(new_year_u16) {
            Ok(found) => found,
            Err(err) => return Err(err),
        };
        let clamped_day = {
            let len = new_month.length(target_year);
            if day > len { len } else { day }
        };
        Self::from_ymd(new_year_u16, new_month, clamped_day)
    }

    /// Add `n` calendar years, clamping Feb 29 to Feb 28 when the
    /// target year is not a leap year.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let leap_day = Date::from_ymd(2024, Month::Feb, 29)?;
    /// // 2025 is not a leap year — Feb 29 clamps to Feb 28.
    /// assert_eq!(leap_day.add_years(1)?, Date::from_ymd(2025, Month::Feb, 28)?);
    /// // 2028 is a leap year — Feb 29 preserved.
    /// assert_eq!(leap_day.add_years(4)?, Date::from_ymd(2028, Month::Feb, 29)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub const fn add_years(self, n: i32) -> Result<Self, TimeError> {
        let Some(months) = n.checked_mul(12) else {
            return Err(TimeError::DateOutOfRange);
        };
        self.add_months(months)
    }

    /// `self + period`, preserving end-of-month when `end_of_month`
    /// is set and `self` is itself the last day of its month.
    ///
    /// This is the crate's one stepping rule: [`Calendar::advance`](crate::Calendar::advance)
    /// rolls its result onto a business day, and
    /// [`Generation::step`](crate::Generation::step) scales the tenor
    /// before calling it. The flag is inert for `Days` and `Weeks`
    /// periods, where end-of-month has no meaning. Semantics match
    /// `QuantLib`'s `Date::advance`.
    ///
    /// ```
    /// use fasti::{Date, Month, Period};
    /// let feb_end = Date::from_ymd(2025, Month::Feb, 28)?;
    /// assert_eq!(feb_end.advance(Period::Months(1), false)?, Date::from_ymd(2025, Month::Mar, 28)?);
    /// assert_eq!(feb_end.advance(Period::Months(1), true)?, Date::from_ymd(2025, Month::Mar, 31)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub fn advance(self, period: Period, end_of_month: bool) -> Result<Self, TimeError> {
        let stepped = (self + period)?;
        Ok(
            if end_of_month
                && self.is_end_of_month()
                && matches!(period, Period::Months(_) | Period::Years(_))
            {
                stepped.end_of_month()
            } else {
                stepped
            },
        )
    }

    /// The first day of `self`'s month.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let d = Date::from_ymd(2024, Month::Feb, 10)?;
    /// assert_eq!(d.start_of_month(), Date::from_ymd(2024, Month::Feb, 1)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn start_of_month(self) -> Self {
        Self(self.0 - (self.day() as u32 - 1))
    }

    /// `true` iff `self` is the first day of its month.
    #[must_use]
    pub const fn is_start_of_month(self) -> bool {
        self.day() == 1
    }

    /// The first `weekday` on or after `self`.
    ///
    /// ```
    /// use fasti::{Date, Month, Weekday};
    /// let wed = Date::from_ymd(2025, Month::Jan, 1)?; // a Wednesday
    /// assert_eq!(wed.next_weekday(Weekday::Wed)?, wed); // already Wednesday
    /// assert_eq!(wed.next_weekday(Weekday::Mon)?, Date::from_ymd(2025, Month::Jan, 6)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub fn next_weekday(self, weekday: Weekday) -> Result<Self, TimeError> {
        let delta = (i32::from(weekday.get()) - i32::from(self.weekday().get())).rem_euclid(7);
        self.add_days(delta)
    }

    /// The `n`th `weekday` of `month` in `year` — "third Monday of
    /// January", the shape `QuantLib` spells `Date::nthWeekday`.
    ///
    /// Returns [`TimeError::DayOutOfRange`] when that occurrence does
    /// not exist, which only a fifth occurrence can fail to.
    ///
    /// ```
    /// use fasti::{Date, Month, Ordinal, Weekday, Year};
    /// // MLK Day 2026: third Monday of January.
    /// assert_eq!(
    ///     Date::nth_weekday(Ordinal::Third, Weekday::Mon, Month::Jan, Year::new(2026)?)?,
    ///     Date::from_ymd(2026, Month::Jan, 19)?,
    /// );
    /// // February 2026 has only four Sundays.
    /// assert!(Date::nth_weekday(Ordinal::Fifth, Weekday::Sun, Month::Feb, Year::new(2026)?).is_err());
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    pub fn nth_weekday(
        n: Ordinal,
        weekday: Weekday,
        month: Month,
        year: Year,
    ) -> Result<Self, TimeError> {
        let first = Self::from_ymd(year.get(), month, 1)?.next_weekday(weekday)?;
        let nth = first.add_days(7 * (i32::from(n.get()) - 1))?;
        if nth.month() == month {
            Ok(nth)
        } else {
            Err(TimeError::DayOutOfRange)
        }
    }

    /// The last day of `self`'s month.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// let d = Date::from_ymd(2024, Month::Feb, 10)?;
    /// assert_eq!(d.end_of_month(), Date::from_ymd(2024, Month::Feb, 29)?);
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn end_of_month(self) -> Self {
        let (year, month, _) = self.to_ymd();
        let last = month.length(year);
        // Serial arithmetic — month start plus (length - 1) — avoids an unreachable `from_ymd` error path.
        let month_start = self.0 - (self.day() as u32 - 1);
        Self(month_start + last as u32 - 1)
    }

    /// `true` iff `self` is the last day of its month.
    ///
    /// ```
    /// use fasti::{Date, Month};
    /// assert!(Date::from_ymd(2024, Month::Feb, 29)?.is_end_of_month()); // leap
    /// assert!(Date::from_ymd(2025, Month::Feb, 28)?.is_end_of_month()); // non-leap
    /// assert!(!Date::from_ymd(2025, Month::Feb, 27)?.is_end_of_month());
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    #[must_use]
    pub const fn is_end_of_month(self) -> bool {
        let (year, month, day) = self.to_ymd();
        day == month.length(year)
    }
}

/// Date-aware operations on a half-open range `start..end`.
///
/// `fasti` spells every date interval — accrual periods, schedule
/// periods, calendar queries — as a [`Range<Date>`](core::ops::Range)
/// rather than a bespoke type; this trait is the vocabulary that goes
/// with it.
///
/// ```
/// use fasti::{Date, DateRange, Month};
/// let jan = Date::from_ymd(2026, Month::Jan, 1)?..Date::from_ymd(2026, Month::Feb, 1)?;
/// assert_eq!(jan.days(), 31);
/// assert_eq!(jan.dates().count(), 31);
/// # Ok::<(), fasti::TimeError>(())
/// ```
pub trait DateRange: Sized {
    /// Elapsed days, signed by direction.
    fn days(&self) -> i64;

    /// The overlap with `other`, if the two share any days. Ranges
    /// that merely touch at a boundary share none.
    fn intersect(&self, other: &Self) -> Option<Self>;

    /// Every date in the range, ascending; the end bound is excluded.
    /// The iterator copies the bounds, so it outlives the range.
    fn dates(&self) -> impl DoubleEndedIterator<Item = Date> + use<Self>;
}

impl DateRange for Range<Date> {
    fn days(&self) -> i64 {
        i64::from(self.end.days_since(self.start))
    }

    fn intersect(&self, other: &Self) -> Option<Self> {
        let both = self.start.max(other.start)..self.end.min(other.end);
        (both.start < both.end).then_some(both)
    }

    fn dates(&self) -> impl DoubleEndedIterator<Item = Date> + use<> {
        // Both bounds are valid dates, so every serial between them is too.
        (self.start.serial()..self.end.serial()).filter_map(|s| Date::from_serial(s).ok())
    }
}

impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Decompose once instead of three separate year lookups.
        let (y, m, d) = self.to_ymd();
        write!(f, "{:04}-{:02}-{:02}", y.get(), m.get(), d)
    }
}

impl core::str::FromStr for Date {
    type Err = TimeError;

    /// Parse a strict ISO-8601 `YYYY-MM-DD` date — the exact format
    /// [`Display`](fmt::Display) produces. Malformed strings return
    /// [`TimeError::InvalidDateString`]; range errors match [`Date::from_ymd`].
    ///
    /// ```
    /// use fasti::{Date, Month, TimeError};
    /// let d: Date = "2026-07-04".parse()?;
    /// assert_eq!(d, Date::from_ymd(2026, Month::Jul, 4)?);
    /// // Round trip through Display.
    /// assert_eq!("2026-07-04".parse::<Date>()?.to_string(), "2026-07-04");
    /// // Malformed strings are rejected.
    /// assert_eq!("2026-7-4".parse::<Date>(), Err(TimeError::InvalidDateString));
    /// // Well-formed but nonexistent dates surface the range error.
    /// assert_eq!("2026-02-30".parse::<Date>(), Err(TimeError::DayOutOfRange));
    /// # Ok::<(), fasti::TimeError>(())
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const fn digit(b: u8) -> Result<u16, TimeError> {
            if b.is_ascii_digit() {
                Ok((b - b'0') as u16)
            } else {
                Err(TimeError::InvalidDateString)
            }
        }
        let [y3, y2, y1, y0, h1, m1, m0, h2, d1, d0] = s.as_bytes() else {
            return Err(TimeError::InvalidDateString);
        };
        if *h1 != b'-' || *h2 != b'-' {
            return Err(TimeError::InvalidDateString);
        }
        let year = 1000 * digit(*y3)? + 100 * digit(*y2)? + 10 * digit(*y1)? + digit(*y0)?;
        let month_num = 10 * digit(*m1)? + digit(*m0)?;
        let day = 10 * digit(*d1)? + digit(*d0)?;
        // Both values are at most 99, so the u16 -> u8 narrowing is exact.
        #[allow(clippy::cast_possible_truncation)]
        let month = Month::try_from_u8(month_num as u8)?;
        #[allow(clippy::cast_possible_truncation)]
        let day = day as u8;
        Self::from_ymd(year, month, day)
    }
}

/// Step a [`Date`] forward by a [`Period`]. Returns
/// [`TimeError::DateOutOfRange`] for out-of-range results; `Months`/`Years`
/// clamp the day-of-month (see [`Date::add_months`]).
///
/// ```
/// use fasti::{Date, Month, Period};
/// let d = Date::from_ymd(2026, Month::Jan, 15)?;
/// assert_eq!((d + Period::Months(6))?, Date::from_ymd(2026, Month::Jul, 15)?);
/// assert_eq!((d + Period::Years(1))?, Date::from_ymd(2027, Month::Jan, 15)?);
/// assert_eq!((d + Period::Days(7))?, Date::from_ymd(2026, Month::Jan, 22)?);
/// // Negative periods step backward.
/// assert_eq!((d + (-Period::Months(1)))?, Date::from_ymd(2025, Month::Dec, 15)?);
/// # Ok::<(), fasti::TimeError>(())
/// ```
impl Add<Period> for Date {
    type Output = Result<Self, TimeError>;

    fn add(self, period: Period) -> Self::Output {
        match period {
            Period::Days(n) => self.add_days(n),
            Period::Weeks(n) => match n.checked_mul(7) {
                Some(days) => self.add_days(days),
                None => Err(TimeError::DateOutOfRange),
            },
            Period::Months(n) => self.add_months(n),
            Period::Years(n) => self.add_years(n),
        }
    }
}

/// Step a [`Date`] backward by a [`Period`]. Uses [`Period::checked_neg`],
/// surfacing `i32::MIN` overflow as [`TimeError::DateOutOfRange`].
///
/// ```
/// use fasti::{Date, Month, Period};
/// let d = Date::from_ymd(2026, Month::Jul, 15)?;
/// assert_eq!((d - Period::Months(6))?, Date::from_ymd(2026, Month::Jan, 15)?);
/// # Ok::<(), fasti::TimeError>(())
/// ```
impl Sub<Period> for Date {
    type Output = Result<Self, TimeError>;

    fn sub(self, period: Period) -> Self::Output {
        // `+` inside `Sub` is the deliberate factoring: delegate to `Add` after negating.
        #[allow(clippy::suspicious_arithmetic_impl)]
        match period.checked_neg() {
            Some(neg) => self + neg,
            None => Err(TimeError::DateOutOfRange),
        }
    }
}

// ---- Tests --------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    extern crate alloc;

    use super::*;
    use proptest::prelude::*;

    #[test]
    fn epoch_is_1901_01_01_tuesday() {
        let d = Date::MIN;
        assert_eq!(d.serial(), 0);
        assert_eq!(d.year().get(), 1901);
        assert_eq!(d.month(), Month::Jan);
        assert_eq!(d.day(), 1);
        assert_eq!(d.weekday(), Weekday::Tue);
    }

    #[test]
    fn max_is_2199_12_31() {
        let d = Date::MAX;
        assert_eq!(d.year().get(), 2199);
        assert_eq!(d.month(), Month::Dec);
        assert_eq!(d.day(), 31);
    }

    #[test]
    fn from_ymd_rejects_out_of_range_year() {
        assert_eq!(
            Date::from_ymd(1900, Month::Jan, 1),
            Err(TimeError::YearOutOfRange)
        );
        assert_eq!(
            Date::from_ymd(2200, Month::Jan, 1),
            Err(TimeError::YearOutOfRange)
        );
    }

    #[test]
    fn from_ymd_rejects_day_zero_and_overflow() {
        assert_eq!(
            Date::from_ymd(2026, Month::Jan, 0),
            Err(TimeError::DayOutOfRange)
        );
        assert_eq!(
            Date::from_ymd(2026, Month::Jan, 32),
            Err(TimeError::DayOutOfRange)
        );
        assert_eq!(
            Date::from_ymd(2026, Month::Apr, 31),
            Err(TimeError::DayOutOfRange)
        );
    }

    #[test]
    fn february_leap_year_behavior() {
        // 2000 is a leap year (divisible by 400).
        assert!(Date::from_ymd(2000, Month::Feb, 29).is_ok());
        // 2100 is NOT a leap year (divisible by 100, not 400).
        assert_eq!(
            Date::from_ymd(2100, Month::Feb, 29),
            Err(TimeError::DayOutOfRange)
        );
        // 2024 is a leap year (divisible by 4, not 100).
        assert!(Date::from_ymd(2024, Month::Feb, 29).is_ok());
        // 2026 is not a leap year.
        assert_eq!(
            Date::from_ymd(2026, Month::Feb, 29),
            Err(TimeError::DayOutOfRange)
        );
    }

    #[test]
    fn known_weekdays() {
        // Anchors independently verifiable.
        assert_eq!(
            Date::from_ymd(1901, Month::Jan, 1).unwrap().weekday(),
            Weekday::Tue,
        );
        assert_eq!(
            Date::from_ymd(2000, Month::Jan, 1).unwrap().weekday(),
            Weekday::Sat,
        );
        assert_eq!(
            Date::from_ymd(2026, Month::Jul, 4).unwrap().weekday(),
            Weekday::Sat,
        );
        assert_eq!(
            Date::from_ymd(2021, Month::Jun, 19).unwrap().weekday(),
            Weekday::Sat,
        );
        assert_eq!(
            Date::from_ymd(2199, Month::Dec, 31).unwrap().weekday(),
            Weekday::Tue,
        );
    }

    #[test]
    fn year_is_correct_for_every_serial() {
        // Exhaustive: walk the whole range once, tracking the expected
        // year incrementally, so `year`'s estimate-plus-correction is
        // pinned at every day — boundaries included — along with the
        // doc comment's claim that the 400-year-cycle estimate is off
        // by at most one year index (which also keeps the unclamped
        // table index in bounds).
        let mut expected: u16 = EPOCH_YEAR;
        let mut next_year_start: u32 = CUMULATIVE[1];
        for serial in 0..=MAX_SERIAL {
            if serial == next_year_start {
                expected += 1;
                next_year_start = CUMULATIVE[(expected - EPOCH_YEAR) as usize + 1];
            }
            assert_eq!(
                Date::from_serial(serial).unwrap().year().get(),
                expected,
                "serial {serial}",
            );
            let estimate = serial * 400 / 146_097;
            assert!(
                estimate.abs_diff(u32::from(expected - EPOCH_YEAR)) <= 1,
                "serial {serial}: estimate {estimate} not within one of the true index",
            );
        }
    }

    #[test]
    fn day_of_year_boundaries() {
        assert_eq!(
            Date::from_ymd(2024, Month::Jan, 1).unwrap().day_of_year(),
            1,
        );
        assert_eq!(
            Date::from_ymd(2024, Month::Dec, 31).unwrap().day_of_year(),
            366, // leap
        );
        assert_eq!(
            Date::from_ymd(2025, Month::Dec, 31).unwrap().day_of_year(),
            365,
        );
    }

    #[test]
    fn add_days_at_boundaries() {
        assert_eq!(Date::MIN.add_days(-1), Err(TimeError::DateOutOfRange));
        assert_eq!(Date::MAX.add_days(1), Err(TimeError::DateOutOfRange));
        let d = Date::from_ymd(2026, Month::Feb, 28).unwrap();
        assert_eq!(
            d.add_days(1).unwrap(),
            Date::from_ymd(2026, Month::Mar, 1).unwrap()
        );
        let leap = Date::from_ymd(2024, Month::Feb, 28).unwrap();
        assert_eq!(
            leap.add_days(1).unwrap(),
            Date::from_ymd(2024, Month::Feb, 29).unwrap()
        );
    }

    #[test]
    fn display_is_iso_8601() {
        let d = Date::from_ymd(2026, Month::Jul, 4).unwrap();
        assert_eq!(alloc::format!("{d}"), "2026-07-04");
    }

    #[test]
    fn weekday_iso_numbering() {
        assert_eq!(Weekday::Mon.get(), 1);
        assert_eq!(Weekday::Sun.get(), 7);
        assert_eq!(Weekday::try_from_u8(1).unwrap(), Weekday::Mon);
        assert_eq!(Weekday::try_from_u8(7).unwrap(), Weekday::Sun);
        assert_eq!(Weekday::try_from_u8(0), Err(TimeError::WeekdayOutOfRange));
        assert_eq!(Weekday::try_from_u8(8), Err(TimeError::WeekdayOutOfRange));
    }

    #[test]
    fn ordinal_display() {
        assert_eq!(alloc::format!("{}", Ordinal::First), "First");
        assert_eq!(alloc::format!("{}", Ordinal::Fifth), "Fifth");
    }

    #[test]
    fn from_str_parses_display_output() {
        for (y, m, d) in [
            (1901u16, Month::Jan, 1u8),
            (2026, Month::Jul, 4),
            (2024, Month::Feb, 29),
            (2199, Month::Dec, 31),
        ] {
            let date = Date::from_ymd(y, m, d).unwrap();
            let parsed: Date = alloc::format!("{date}").parse().unwrap();
            assert_eq!(parsed, date);
        }
    }

    #[test]
    fn from_str_rejects_malformed_strings() {
        for bad in [
            "",
            "2026",
            "2026-07",
            "2026-7-4",    // not zero-padded
            "26-07-04",    // two-digit year
            "2026/07/04",  // wrong separator
            "2026-07-04T", // trailing content
            " 2026-07-04", // leading whitespace
            "2026-07-04 ", // trailing whitespace
            "+026-07-04",  // sign
            "2026-0a-04",  // non-digit
            "٢٠٢٦-07-04",  // non-ASCII digits
        ] {
            assert_eq!(
                bad.parse::<Date>(),
                Err(TimeError::InvalidDateString),
                "{bad:?} should be rejected as malformed",
            );
        }
    }

    #[test]
    fn from_str_surfaces_range_errors_for_well_formed_input() {
        assert_eq!("1900-12-31".parse::<Date>(), Err(TimeError::YearOutOfRange));
        assert_eq!("2200-01-01".parse::<Date>(), Err(TimeError::YearOutOfRange));
        assert_eq!(
            "2026-13-01".parse::<Date>(),
            Err(TimeError::MonthOutOfRange)
        );
        assert_eq!(
            "2026-00-01".parse::<Date>(),
            Err(TimeError::MonthOutOfRange)
        );
        assert_eq!("2026-02-30".parse::<Date>(), Err(TimeError::DayOutOfRange));
        assert_eq!("2026-01-00".parse::<Date>(), Err(TimeError::DayOutOfRange));
    }

    #[test]
    fn to_ymd_matches_individual_accessors() {
        let d = Date::from_ymd(2026, Month::Jul, 4).unwrap();
        let (y, m, dom) = d.to_ymd();
        assert_eq!(y, d.year());
        assert_eq!(m, d.month());
        assert_eq!(dom, d.day());
    }

    // ---- property tests ------------------------------------------------

    /// Strategy: uniformly sample a valid (year, month, day) in range.
    fn any_ymd() -> impl Strategy<Value = (u16, Month, u8)> {
        (EPOCH_YEAR..=END_YEAR, 1u8..=12u8).prop_flat_map(|(y, m)| {
            let month = Month::try_from_u8(m).expect("1..=12");
            let year = Year::new(y).expect("in range");
            let max_day = month.length(year);
            (Just(y), Just(month), 1u8..=max_day)
        })
    }

    proptest! {
        #[test]
        fn from_ymd_round_trips(
            (year, month, day) in any_ymd()
        ) {
            let d = Date::from_ymd(year, month, day).expect("valid ymd");
            prop_assert_eq!(d.year().get(), year);
            prop_assert_eq!(d.month(), month);
            prop_assert_eq!(d.day(), day);
        }

        #[test]
        fn serial_round_trips(
            serial in 0u32..=MAX_SERIAL,
        ) {
            let d = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(d.serial(), serial);
            let ymd = Date::from_ymd(d.year().get(), d.month(), d.day()).expect("valid");
            prop_assert_eq!(ymd.serial(), serial);
        }

        #[test]
        fn weekday_advances_by_one_per_day(
            serial in 0u32..MAX_SERIAL,
        ) {
            let today = Date::from_serial(serial).expect("in range");
            let tomorrow = today.add_days(1).expect("in range");
            let expected = match today.weekday() {
                Weekday::Mon => Weekday::Tue,
                Weekday::Tue => Weekday::Wed,
                Weekday::Wed => Weekday::Thu,
                Weekday::Thu => Weekday::Fri,
                Weekday::Fri => Weekday::Sat,
                Weekday::Sat => Weekday::Sun,
                Weekday::Sun => Weekday::Mon,
            };
            prop_assert_eq!(tomorrow.weekday(), expected);
        }

        #[test]
        fn add_days_is_inverse_of_days_since(
            a_serial in 0u32..=MAX_SERIAL,
            b_serial in 0u32..=MAX_SERIAL,
        ) {
            let a = Date::from_serial(a_serial).unwrap();
            let b = Date::from_serial(b_serial).unwrap();
            let diff = b.days_since(a);
            prop_assert_eq!(a.add_days(diff).unwrap(), b);
        }

        #[test]
        fn day_of_year_is_consistent(
            (year, month, day) in any_ymd()
        ) {
            let d = Date::from_ymd(year, month, day).expect("valid");
            let year_start = Date::from_ymd(year, Month::Jan, 1).expect("valid");
            prop_assert_eq!(
                u16::try_from(d.days_since(year_start) + 1).unwrap(),
                d.day_of_year(),
            );
        }

        #[test]
        fn month_try_from_u8_round_trips(m in 1u8..=12u8) {
            let parsed = Month::try_from_u8(m).expect("1..=12");
            prop_assert_eq!(parsed.get(), m);
        }

        #[test]
        fn weekday_try_from_u8_round_trips(n in 1u8..=7u8) {
            let parsed = Weekday::try_from_u8(n).expect("1..=7");
            prop_assert_eq!(parsed.get(), n);
        }

        #[test]
        fn ordinal_try_from_u8_round_trips(n in 1u8..=5u8) {
            let parsed = Ordinal::try_from_u8(n).expect("1..=5");
            prop_assert_eq!(parsed.get(), n);
        }

        #[test]
        fn add_days_accepts_iff_result_in_range(
            serial in 0u32..=MAX_SERIAL,
            n in i32::MIN..=i32::MAX,
        ) {
            let d = Date::from_serial(serial).expect("in range");
            let result = d.add_days(n);
            let target = i64::from(serial) + i64::from(n);
            let in_range = (0..=i64::from(MAX_SERIAL)).contains(&target);
            prop_assert_eq!(result.is_ok(), in_range);
            if in_range {
                prop_assert_eq!(
                    result.expect("in-range").serial(),
                    u32::try_from(target).expect("fits in u32"),
                );
            } else {
                prop_assert_eq!(result, Err(TimeError::DateOutOfRange));
            }
        }

        #[test]
        fn to_ymd_round_trips(serial in 0u32..=MAX_SERIAL) {
            let d = Date::from_serial(serial).expect("in range");
            let (y, m, dom) = d.to_ymd();
            let rebuilt = Date::from_ymd(y.get(), m, dom).expect("valid");
            prop_assert_eq!(rebuilt.serial(), serial);
        }

        /// Every date's `Display` output parses back to the same date.
        #[test]
        fn display_and_from_str_round_trip(serial in 0u32..=MAX_SERIAL) {
            let d = Date::from_serial(serial).expect("in range");
            let parsed: Date = alloc::format!("{d}").parse().expect("Display output is valid");
            prop_assert_eq!(parsed, d);
        }

        /// `add_months(n)` then `add_months(-n)` round-trips exactly for day ≤ 28 (never clamped).
        #[test]
        fn add_months_round_trip_on_safe_days(
            year in 1910u16..=2190,
            month in 1u8..=12,
            day in 1u8..=28,
            n in -500i32..=500,
        ) {
            let parsed_month = Month::try_from_u8(month).expect("1..=12");
            let start = Date::from_ymd(year, parsed_month, day).expect("valid");
            if let Ok(stepped) = start.add_months(n)
                && let Ok(restored) = stepped.add_months(-n)
            {
                prop_assert_eq!(restored, start);
            }
        }

        /// `add_months(n)` equals `add_years(n/12)` then `add_months(n%12)` for day ≤ 28;
        /// the year range keeps intermediates in range.
        #[test]
        fn add_months_decomposes_into_years_plus_months(
            year in 1921u16..=2179,
            month in 1u8..=12,
            day in 1u8..=28,
            whole_years in -20i32..=20,
            extra_months in -11i32..=11,
        ) {
            let parsed_month = Month::try_from_u8(month).expect("1..=12");
            let start = Date::from_ymd(year, parsed_month, day).expect("valid");
            let direct = start.add_months(whole_years * 12 + extra_months);
            let stepped = start
                .add_years(whole_years)
                .and_then(|x| x.add_months(extra_months));
            prop_assert_eq!(direct, stepped);
        }

        /// `add_months` never yields a day past the target month's length.
        #[test]
        fn add_months_never_exceeds_target_month_length(
            serial in 0u32..=MAX_SERIAL,
            n in -200i32..=200,
        ) {
            let d = Date::from_serial(serial).expect("in range");
            if let Ok(out) = d.add_months(n) {
                let (y, m, dom) = out.to_ymd();
                prop_assert!(dom <= m.length(y));
                prop_assert!(dom >= 1);
            }
        }

        /// `end_of_month` is idempotent.
        #[test]
        fn end_of_month_is_idempotent(serial in 0u32..=MAX_SERIAL) {
            let d = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(d.end_of_month(), d.end_of_month().end_of_month());
            prop_assert!(d.end_of_month().is_end_of_month());
        }

        /// `date + Period::Days(n)` matches `date.add_days(n)`.
        #[test]
        fn add_period_days_matches_add_days(
            serial in 0u32..=MAX_SERIAL,
            n in -10_000i32..=10_000,
        ) {
            let start = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(start + crate::Period::Days(n), start.add_days(n));
        }

        /// `date + Period::Weeks(n)` matches `date.add_days(n * 7)`
        /// (modulo overflow on the multiplication).
        #[test]
        fn add_period_weeks_equals_add_days_times_seven(
            serial in 0u32..=MAX_SERIAL,
            n in (i32::MIN / 7)..=(i32::MAX / 7),
        ) {
            let start = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(start + crate::Period::Weeks(n), start.add_days(n * 7));
        }

        /// `date + Period::Months(n)` matches `date.add_months(n)`.
        #[test]
        fn add_period_months_matches_add_months(
            serial in 0u32..=MAX_SERIAL,
            n in -200i32..=200,
        ) {
            let start = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(start + crate::Period::Months(n), start.add_months(n));
        }

        /// `date + Period::Years(n)` matches `date.add_years(n)`.
        #[test]
        fn add_period_years_matches_add_years(
            serial in 0u32..=MAX_SERIAL,
            n in -100i32..=100,
        ) {
            let start = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(start + crate::Period::Years(n), start.add_years(n));
        }

        /// `(date - period)` equals `(date + (-period))` for every
        /// non-`i32::MIN` length.
        #[test]
        fn sub_period_equals_add_negated_period(
            serial in 0u32..=MAX_SERIAL,
            length in (i32::MIN + 1)..=i32::MAX,
            unit_idx in 0u8..=3,
        ) {
            let p = match unit_idx {
                0 => crate::Period::Days(length),
                1 => crate::Period::Weeks(length),
                2 => crate::Period::Months(length),
                _ => crate::Period::Years(length),
            };
            let start = Date::from_serial(serial).expect("in range");
            prop_assert_eq!(start - p, start + (-p));
        }
    }

    // ---- example-based tests for month/year arithmetic -----------------

    #[test]
    fn add_months_clamps_to_target_month_length() {
        let jan31 = Date::from_ymd(2026, Month::Jan, 31).unwrap();
        assert_eq!(
            jan31.add_months(1).unwrap(),
            Date::from_ymd(2026, Month::Feb, 28).unwrap()
        );
        // Leap year: Jan 31 2024 + 1M → Feb 29.
        let jan31_leap = Date::from_ymd(2024, Month::Jan, 31).unwrap();
        assert_eq!(
            jan31_leap.add_months(1).unwrap(),
            Date::from_ymd(2024, Month::Feb, 29).unwrap()
        );
        // May 31 + 1M → Jun 30 (no May 31 + 1M = Jun 31).
        let may31 = Date::from_ymd(2026, Month::May, 31).unwrap();
        assert_eq!(
            may31.add_months(1).unwrap(),
            Date::from_ymd(2026, Month::Jun, 30).unwrap()
        );
    }

    /// Clamp-on-add-months is not composable across end-of-month dates:
    /// `Jan 31 → Feb 28 → Mar 28` differs from `Jan 31 → Mar 31`.
    #[test]
    fn add_months_clamp_is_not_composable_across_eom() {
        let jan31 = Date::from_ymd(2026, Month::Jan, 31).unwrap();
        // Two single-month hops: 31 → 28 → 28. Day-of-month sticks at 28.
        let two_hops = jan31.add_months(1).unwrap().add_months(1).unwrap();
        assert_eq!(two_hops, Date::from_ymd(2026, Month::Mar, 28).unwrap());
        // One two-month hop: 31 → 31 (March has 31 days).
        let single_hop = jan31.add_months(2).unwrap();
        assert_eq!(single_hop, Date::from_ymd(2026, Month::Mar, 31).unwrap());
        // The two paths disagree by 3 days.
        assert_ne!(two_hops, single_hop);
    }

    #[test]
    fn add_months_crosses_year_boundaries() {
        let nov15 = Date::from_ymd(2026, Month::Nov, 15).unwrap();
        assert_eq!(
            nov15.add_months(3).unwrap(),
            Date::from_ymd(2027, Month::Feb, 15).unwrap()
        );
        assert_eq!(
            nov15.add_months(-11).unwrap(),
            Date::from_ymd(2025, Month::Dec, 15).unwrap()
        );
    }

    #[test]
    fn add_months_zero_is_identity() {
        let d = Date::from_ymd(2026, Month::Jul, 4).unwrap();
        assert_eq!(d.add_months(0).unwrap(), d);
    }

    #[test]
    fn add_months_refuses_out_of_range_result() {
        assert_eq!(Date::MAX.add_months(1), Err(TimeError::DateOutOfRange));
        assert_eq!(Date::MIN.add_months(-1), Err(TimeError::DateOutOfRange));
    }

    #[test]
    fn add_years_clamps_feb_29_in_non_leap_target() {
        let feb29 = Date::from_ymd(2024, Month::Feb, 29).unwrap();
        assert_eq!(
            feb29.add_years(1).unwrap(),
            Date::from_ymd(2025, Month::Feb, 28).unwrap()
        );
        assert_eq!(
            feb29.add_years(4).unwrap(),
            Date::from_ymd(2028, Month::Feb, 29).unwrap()
        );
    }

    #[test]
    fn end_of_month_examples() {
        // Jan 15 2024 → Jan 31 2024.
        let d = Date::from_ymd(2024, Month::Jan, 15).unwrap();
        assert_eq!(
            d.end_of_month(),
            Date::from_ymd(2024, Month::Jan, 31).unwrap()
        );
        // Feb 10 2024 (leap) → Feb 29 2024.
        let d = Date::from_ymd(2024, Month::Feb, 10).unwrap();
        assert_eq!(
            d.end_of_month(),
            Date::from_ymd(2024, Month::Feb, 29).unwrap()
        );
        // Feb 10 2025 (non-leap) → Feb 28 2025.
        let d = Date::from_ymd(2025, Month::Feb, 10).unwrap();
        assert_eq!(
            d.end_of_month(),
            Date::from_ymd(2025, Month::Feb, 28).unwrap()
        );
        // Dec 31 2199 (max) is already EoM.
        assert_eq!(Date::MAX.end_of_month(), Date::MAX);
        // Jan 1 1901 (min) → Jan 31 1901.
        assert_eq!(
            Date::MIN.end_of_month(),
            Date::from_ymd(1901, Month::Jan, 31).unwrap()
        );
    }

    #[test]
    fn is_end_of_month_examples() {
        assert!(
            Date::from_ymd(2024, Month::Feb, 29)
                .unwrap()
                .is_end_of_month()
        );
        assert!(
            !Date::from_ymd(2024, Month::Feb, 28)
                .unwrap()
                .is_end_of_month()
        );
        assert!(
            Date::from_ymd(2025, Month::Feb, 28)
                .unwrap()
                .is_end_of_month()
        );
        assert!(
            Date::from_ymd(2026, Month::Apr, 30)
                .unwrap()
                .is_end_of_month()
        );
        assert!(
            Date::from_ymd(2026, Month::May, 31)
                .unwrap()
                .is_end_of_month()
        );
    }

    #[test]
    fn start_of_month_examples() {
        let d = Date::from_ymd(2024, Month::Feb, 29).unwrap();
        assert_eq!(
            d.start_of_month(),
            Date::from_ymd(2024, Month::Feb, 1).unwrap()
        );
        assert!(d.start_of_month().is_start_of_month());
        assert!(!d.is_start_of_month());
        assert_eq!(Date::MIN.start_of_month(), Date::MIN);
    }

    #[test]
    fn next_weekday_is_the_identity_on_a_match() {
        // Thu Jan 1 2026.
        let thu = Date::from_ymd(2026, Month::Jan, 1).unwrap();
        assert_eq!(thu.next_weekday(Weekday::Thu).unwrap(), thu);
        assert_eq!(
            thu.next_weekday(Weekday::Wed).unwrap(),
            Date::from_ymd(2026, Month::Jan, 7).unwrap(),
        );
    }

    #[test]
    fn nth_weekday_examples() {
        let y = Year::new(2026).unwrap();
        // MLK Day: third Monday of January 2026.
        assert_eq!(
            Date::nth_weekday(Ordinal::Third, Weekday::Mon, Month::Jan, y).unwrap(),
            Date::from_ymd(2026, Month::Jan, 19).unwrap(),
        );
        // Thanksgiving: fourth Thursday of November 2026.
        assert_eq!(
            Date::nth_weekday(Ordinal::Fourth, Weekday::Thu, Month::Nov, y).unwrap(),
            Date::from_ymd(2026, Month::Nov, 26).unwrap(),
        );
        // Feb 2026 has four Sundays, not five.
        assert_eq!(
            Date::nth_weekday(Ordinal::Fifth, Weekday::Sun, Month::Feb, y),
            Err(TimeError::DayOutOfRange),
        );
    }

    #[test]
    fn date_range_dates_walks_both_ends() {
        let jan = Date::from_ymd(2026, Month::Jan, 1).unwrap()
            ..Date::from_ymd(2026, Month::Feb, 1).unwrap();
        assert_eq!(i64::try_from(jan.dates().count()).unwrap(), jan.days());
        assert_eq!(jan.dates().next(), Some(jan.start));
        assert_eq!(
            jan.dates().next_back(),
            Some(Date::from_ymd(2026, Month::Jan, 31).unwrap()),
        );
        // Empty and reversed ranges are both empty.
        assert_eq!((jan.start..jan.start).dates().count(), 0);
        assert_eq!((jan.end..jan.start).dates().count(), 0);
    }

    proptest! {
        /// Every date in a range is contained by it, and the count
        /// matches the day span.
        #[test]
        fn dates_agree_with_days(serial in 0u32..(MAX_SERIAL - 400), len in 0u32..400) {
            let start = Date::from_serial(serial).unwrap();
            let range = start..Date::from_serial(serial + len).unwrap();
            prop_assert_eq!(i64::try_from(range.dates().count()).unwrap(), range.days());
            prop_assert!(range.dates().all(|d| range.contains(&d)));
        }

        /// `nth_weekday` lands on the requested weekday and month.
        #[test]
        fn nth_weekday_lands_where_asked(y in 1901u16..=2199, m in 1u8..=12, w in 1u8..=7, n in 1u8..=5) {
            let (month, weekday) = (Month::try_from_u8(m).unwrap(), Weekday::try_from_u8(w).unwrap());
            let ordinal = Ordinal::try_from_u8(n).unwrap();
            if let Ok(d) = Date::nth_weekday(ordinal, weekday, month, Year::new(y).unwrap()) {
                prop_assert_eq!(d.weekday(), weekday);
                prop_assert_eq!(d.month(), month);
                prop_assert!(d.day() > 7 * (n - 1) && d.day() <= 7 * n);
            }
        }
    }

    #[test]
    fn add_period_dispatches_by_unit() {
        let start = Date::from_ymd(2026, Month::Jan, 15).unwrap();
        assert_eq!(
            (start + crate::Period::Days(1)).unwrap(),
            Date::from_ymd(2026, Month::Jan, 16).unwrap()
        );
        assert_eq!(
            (start + crate::Period::Weeks(2)).unwrap(),
            Date::from_ymd(2026, Month::Jan, 29).unwrap()
        );
        assert_eq!(
            (start + crate::Period::Months(3)).unwrap(),
            Date::from_ymd(2026, Month::Apr, 15).unwrap()
        );
        assert_eq!(
            (start + crate::Period::Years(1)).unwrap(),
            Date::from_ymd(2027, Month::Jan, 15).unwrap()
        );
    }

    #[test]
    fn sub_period_steps_backward() {
        let start = Date::from_ymd(2026, Month::Jul, 15).unwrap();
        assert_eq!(
            (start - crate::Period::Months(6)).unwrap(),
            Date::from_ymd(2026, Month::Jan, 15).unwrap(),
        );
        // Sub on a negative period steps forward.
        assert_eq!(
            (start - (-crate::Period::Months(6))).unwrap(),
            Date::from_ymd(2027, Month::Jan, 15).unwrap(),
        );
    }
}