parse-zoneinfo 0.5.0

Parse zoneinfo files from the IANA database
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
//! Parsing zoneinfo data files, line-by-line.
//!
//! This module provides functions that take a line of input from a zoneinfo
//! data file and attempts to parse it, returning the details of the line if
//! it gets parsed successfully. It classifies them as `Rule`, `Link`,
//! `Zone`, or `Continuation` lines.
//!
//! `Line` is the type that parses and holds zoneinfo line data. To try to
//! parse a string, use the `Line::from_str` constructor. (This isn’t the
//! `FromStr` trait, so you can’t use `parse` on a string. Sorry!)
//!
//! ## Examples
//!
//! Parsing a `Rule` line:
//!
//! ```
//! use parse_zoneinfo::line::*;
//!
//! let line = Line::new("Rule  EU  1977    1980    -   Apr Sun>=1   1:00u  1:00    S");
//!
//! assert_eq!(line, Ok(Line::Rule(Rule {
//!     name:         "EU",
//!     from_year:    Year::Number(1977),
//!     to_year:      Some(Year::Number(1980)),
//!     month:        Month::April,
//!     day:          DaySpec::FirstOnOrAfter(Weekday::Sunday, 1),
//!     time:         TimeSpec::HoursMinutes(1, 0).with_type(TimeType::UTC),
//!     time_to_add:  TimeSpec::HoursMinutes(1, 0),
//!     letters:      Some("S"),
//! })));
//! ```
//!
//! Parsing a `Zone` line:
//!
//! ```
//! use parse_zoneinfo::line::*;
//!
//! let line = Line::new("Zone  Australia/Adelaide  9:30  Aus  AC%sT  1971 Oct 31  2:00:00");
//!
//! assert_eq!(line, Ok(Line::Zone(Zone {
//!     name: "Australia/Adelaide",
//!     info: ZoneInfo {
//!         utc_offset:  TimeSpec::HoursMinutes(9, 30),
//!         saving:      Saving::Multiple("Aus"),
//!         format:      "AC%sT",
//!         time:        Some(ChangeTime::UntilTime(
//!                         Year::Number(1971),
//!                         Month::October,
//!                         DaySpec::Ordinal(31),
//!                         TimeSpec::HoursMinutesSeconds(2, 0, 0).with_type(TimeType::Wall))
//!                      ),
//!     },
//! })));
//! ```
//!
//! Parsing a `Link` line:
//!
//! ```
//! use parse_zoneinfo::line::*;
//!
//! let line = Line::new("Link  Europe/Istanbul  Asia/Istanbul");
//! assert_eq!(line, Ok(Line::Link(Link {
//!     existing:  "Europe/Istanbul",
//!     new:       "Asia/Istanbul",
//! })));
//! ```

use std::fmt;
use std::str::FromStr;

#[derive(PartialEq, Debug, Clone)]
pub enum Error {
    FailedYearParse(String),
    FailedMonthParse(String),
    FailedWeekdayParse(String),
    InvalidLineType(String),
    TypeColumnContainedNonHyphen(String),
    CouldNotParseSaving(String),
    InvalidDaySpec(String),
    InvalidTimeSpecAndType(String),
    NonWallClockInTimeSpec(String),
    NotParsedAsRuleLine,
    NotParsedAsZoneLine,
    NotParsedAsLinkLine,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::FailedYearParse(s) => write!(f, "failed to parse as a year value: \"{}\"", s),
            Error::FailedMonthParse(s) => write!(f, "failed to parse as a month value: \"{}\"", s),
            Error::FailedWeekdayParse(s) => {
                write!(f, "failed to parse as a weekday value: \"{}\"", s)
            }
            Error::InvalidLineType(s) => write!(f, "line with invalid format: \"{}\"", s),
            Error::TypeColumnContainedNonHyphen(s) => {
                write!(
                    f,
                    "'type' column is not a hyphen but has the value: \"{}\"",
                    s
                )
            }
            Error::CouldNotParseSaving(s) => write!(f, "failed to parse RULES column: \"{}\"", s),
            Error::InvalidDaySpec(s) => write!(f, "invalid day specification ('ON'): \"{}\"", s),
            Error::InvalidTimeSpecAndType(s) => write!(f, "invalid time: \"{}\"", s),
            Error::NonWallClockInTimeSpec(s) => {
                write!(f, "time value not given as wall time: \"{}\"", s)
            }
            Error::NotParsedAsRuleLine => write!(f, "failed to parse line as a rule"),
            Error::NotParsedAsZoneLine => write!(f, "failed to parse line as a zone"),
            Error::NotParsedAsLinkLine => write!(f, "failed to parse line as a link"),
        }
    }
}

impl std::error::Error for Error {}

/// A **year** definition field.
///
/// A year has one of the following representations in a file:
///
/// - `min` or `minimum`, the minimum year possible, for when a rule needs to
///   apply up until the first rule with a specific year;
/// - `max` or `maximum`, the maximum year possible, for when a rule needs to
///   apply after the last rule with a specific year;
/// - a year number, referring to a specific year.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Year {
    /// The minimum year possible: `min` or `minimum`.
    Minimum,
    /// The maximum year possible: `max` or `maximum`.
    Maximum,
    /// A specific year number.
    Number(i64),
}

impl FromStr for Year {
    type Err = Error;

    fn from_str(input: &str) -> Result<Year, Self::Err> {
        Ok(match &*input.to_ascii_lowercase() {
            "min" | "minimum" => Year::Minimum,
            "max" | "maximum" => Year::Maximum,
            year => match year.parse() {
                Ok(year) => Year::Number(year),
                Err(_) => return Err(Error::FailedYearParse(input.to_string())),
            },
        })
    }
}

/// A **month** field, which is actually just a wrapper around
/// `datetime::Month`.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Month {
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12,
}

impl Month {
    fn length(self, is_leap: bool) -> i8 {
        match self {
            Month::January => 31,
            Month::February if is_leap => 29,
            Month::February => 28,
            Month::March => 31,
            Month::April => 30,
            Month::May => 31,
            Month::June => 30,
            Month::July => 31,
            Month::August => 31,
            Month::September => 30,
            Month::October => 31,
            Month::November => 30,
            Month::December => 31,
        }
    }

    /// Get the next calendar month, with an error going from Dec->Jan
    fn next_in_year(self) -> Result<Month, &'static str> {
        Ok(match self {
            Month::January => Month::February,
            Month::February => Month::March,
            Month::March => Month::April,
            Month::April => Month::May,
            Month::May => Month::June,
            Month::June => Month::July,
            Month::July => Month::August,
            Month::August => Month::September,
            Month::September => Month::October,
            Month::October => Month::November,
            Month::November => Month::December,
            Month::December => Err("Cannot wrap year from dec->jan")?,
        })
    }

    /// Get the previous calendar month, with an error going from Jan->Dec
    fn prev_in_year(self) -> Result<Month, &'static str> {
        Ok(match self {
            Month::January => Err("Cannot wrap years from jan->dec")?,
            Month::February => Month::January,
            Month::March => Month::February,
            Month::April => Month::March,
            Month::May => Month::April,
            Month::June => Month::May,
            Month::July => Month::June,
            Month::August => Month::July,
            Month::September => Month::August,
            Month::October => Month::September,
            Month::November => Month::October,
            Month::December => Month::November,
        })
    }
}

impl FromStr for Month {
    type Err = Error;

    /// Attempts to parse the given string into a value of this type.
    fn from_str(input: &str) -> Result<Month, Self::Err> {
        Ok(match &*input.to_ascii_lowercase() {
            "jan" | "january" => Month::January,
            "feb" | "february" => Month::February,
            "mar" | "march" => Month::March,
            "apr" | "april" => Month::April,
            "may" => Month::May,
            "jun" | "june" => Month::June,
            "jul" | "july" => Month::July,
            "aug" | "august" => Month::August,
            "sep" | "september" => Month::September,
            "oct" | "october" => Month::October,
            "nov" | "november" => Month::November,
            "dec" | "december" => Month::December,
            other => return Err(Error::FailedMonthParse(other.to_string())),
        })
    }
}

/// A **weekday** field, which is actually just a wrapper around
/// `datetime::Weekday`.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
}

impl Weekday {
    fn calculate(year: i64, month: Month, day: i8) -> Weekday {
        let m = month as i64;
        let y = if m < 3 { year - 1 } else { year };
        let d = day as i64;
        const T: [i64; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
        match (y + y / 4 - y / 100 + y / 400 + T[m as usize - 1] + d) % 7 {
            0 => Weekday::Sunday,
            1 => Weekday::Monday,
            2 => Weekday::Tuesday,
            3 => Weekday::Wednesday,
            4 => Weekday::Thursday,
            5 => Weekday::Friday,
            6 => Weekday::Saturday,
            _ => panic!("why is negative modulus designed so?"),
        }
    }
}

impl FromStr for Weekday {
    type Err = Error;

    fn from_str(input: &str) -> Result<Weekday, Self::Err> {
        Ok(match &*input.to_ascii_lowercase() {
            "mon" | "monday" => Weekday::Monday,
            "tue" | "tuesday" => Weekday::Tuesday,
            "wed" | "wednesday" => Weekday::Wednesday,
            "thu" | "thursday" => Weekday::Thursday,
            "fri" | "friday" => Weekday::Friday,
            "sat" | "saturday" => Weekday::Saturday,
            "sun" | "sunday" => Weekday::Sunday,
            other => return Err(Error::FailedWeekdayParse(other.to_string())),
        })
    }
}

/// A **day** definition field.
///
/// This can be given in either absolute terms (such as “the fifth day of the
/// month”), or relative terms (such as “the last Sunday of the month”, or
/// “the last Friday before or including the 13th”).
///
/// Note that in the last example, it’s allowed for that particular Friday to
/// *be* the 13th in question.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum DaySpec {
    /// A specific day of the month, given by its number.
    Ordinal(i8),
    /// The last day of the month with a specific weekday.
    Last(Weekday),
    /// The **last** day with the given weekday **before** (or including) a
    /// day with a specific number.
    LastOnOrBefore(Weekday, i8),
    /// The **first** day with the given weekday **after** (or including) a
    /// day with a specific number.
    FirstOnOrAfter(Weekday, i8),
}

impl DaySpec {
    /// Converts this day specification to a concrete date, given the year and
    /// month it should occur in.
    pub fn to_concrete_day(&self, year: i64, month: Month) -> (Month, i8) {
        let leap = is_leap(year);
        let length = month.length(leap);
        // we will never hit the 0 because we unwrap prev_in_year below
        let prev_length = month.prev_in_year().map(|m| m.length(leap)).unwrap_or(0);

        match *self {
            DaySpec::Ordinal(day) => (month, day),
            DaySpec::Last(weekday) => (
                month,
                (1..length + 1)
                    .rev()
                    .find(|&day| Weekday::calculate(year, month, day) == weekday)
                    .unwrap(),
            ),
            DaySpec::LastOnOrBefore(weekday, day) => (-7..day + 1)
                .rev()
                .flat_map(|inner_day| {
                    if inner_day >= 1 && Weekday::calculate(year, month, inner_day) == weekday {
                        Some((month, inner_day))
                    } else if inner_day < 1
                        && Weekday::calculate(
                            year,
                            month.prev_in_year().unwrap(),
                            prev_length + inner_day,
                        ) == weekday
                    {
                        // inner_day is negative, so this is subtraction
                        Some((month.prev_in_year().unwrap(), prev_length + inner_day))
                    } else {
                        None
                    }
                })
                .next()
                .unwrap(),
            DaySpec::FirstOnOrAfter(weekday, day) => (day..day + 8)
                .flat_map(|inner_day| {
                    if inner_day <= length && Weekday::calculate(year, month, inner_day) == weekday
                    {
                        Some((month, inner_day))
                    } else if inner_day > length
                        && Weekday::calculate(
                            year,
                            month.next_in_year().unwrap(),
                            inner_day - length,
                        ) == weekday
                    {
                        Some((month.next_in_year().unwrap(), inner_day - length))
                    } else {
                        None
                    }
                })
                .next()
                .unwrap(),
        }
    }
}

impl FromStr for DaySpec {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        // Parse the field as a number if it vaguely resembles one.
        if input.chars().all(|c| c.is_ascii_digit()) {
            return Ok(DaySpec::Ordinal(input.parse().unwrap()));
        }
        // Check if it starts with ‘last’, and trim off the first four bytes if it does
        else if let Some(remainder) = input.strip_prefix("last") {
            let weekday = remainder.parse()?;
            return Ok(DaySpec::Last(weekday));
        }

        let weekday = match input.get(..3) {
            Some(wd) => Weekday::from_str(wd)?,
            None => return Err(Error::InvalidDaySpec(input.to_string())),
        };

        let dir = match input.get(3..5) {
            Some(">=") => true,
            Some("<=") => false,
            _ => return Err(Error::InvalidDaySpec(input.to_string())),
        };

        let day = match input.get(5..) {
            Some(day) => u8::from_str(day).map_err(|_| Error::InvalidDaySpec(input.to_string()))?,
            None => return Err(Error::InvalidDaySpec(input.to_string())),
        } as i8;

        Ok(match dir {
            true => DaySpec::FirstOnOrAfter(weekday, day),
            false => DaySpec::LastOnOrBefore(weekday, day),
        })
    }
}

fn is_leap(year: i64) -> bool {
    // Leap year rules: years which are factors of 4, except those divisible
    // by 100, unless they are divisible by 400.
    //
    // We test most common cases first: 4th year, 100th year, then 400th year.
    //
    // We factor out 4 from 100 since it was already tested, leaving us checking
    // if it's divisible by 25. Afterwards, we do the same, factoring 25 from
    // 400, leaving us with 16.
    //
    // Factors of 4 and 16 can quickly be found with bitwise AND.
    year & 3 == 0 && (year % 25 != 0 || year & 15 == 0)
}

/// A **time** definition field.
///
/// A time must have an hours component, with optional minutes and seconds
/// components. It can also be negative with a starting ‘-’.
///
/// Hour 0 is midnight at the start of the day, and Hour 24 is midnight at the
/// end of the day.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TimeSpec {
    /// A number of hours.
    Hours(i8),
    /// A number of hours and minutes.
    HoursMinutes(i8, i8),
    /// A number of hours, minutes, and seconds.
    HoursMinutesSeconds(i8, i8, i8),
    /// Zero, or midnight at the start of the day.
    Zero,
}

impl TimeSpec {
    /// Returns the number of seconds past midnight that this time spec
    /// represents.
    pub fn as_seconds(self) -> i64 {
        match self {
            TimeSpec::Hours(h) => h as i64 * 60 * 60,
            TimeSpec::HoursMinutes(h, m) => h as i64 * 60 * 60 + m as i64 * 60,
            TimeSpec::HoursMinutesSeconds(h, m, s) => h as i64 * 60 * 60 + m as i64 * 60 + s as i64,
            TimeSpec::Zero => 0,
        }
    }

    pub fn with_type(self, timetype: TimeType) -> TimeSpecAndType {
        TimeSpecAndType(self, timetype)
    }
}

impl FromStr for TimeSpec {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if input == "-" {
            return Ok(TimeSpec::Zero);
        }

        let neg = if input.starts_with('-') { -1 } else { 1 };
        let mut state = TimeSpec::Zero;
        for part in input.split(':') {
            state = match (state, part) {
                (TimeSpec::Zero, hour) => TimeSpec::Hours(
                    i8::from_str(hour)
                        .map_err(|_| Error::InvalidTimeSpecAndType(input.to_string()))?,
                ),
                (TimeSpec::Hours(hours), minutes) if minutes.len() == 2 => TimeSpec::HoursMinutes(
                    hours,
                    i8::from_str(minutes)
                        .map_err(|_| Error::InvalidTimeSpecAndType(input.to_string()))?
                        * neg,
                ),
                (TimeSpec::HoursMinutes(hours, minutes), seconds) if seconds.len() == 2 => {
                    TimeSpec::HoursMinutesSeconds(
                        hours,
                        minutes,
                        i8::from_str(seconds)
                            .map_err(|_| Error::InvalidTimeSpecAndType(input.to_string()))?
                            * neg,
                    )
                }
                _ => return Err(Error::InvalidTimeSpecAndType(input.to_string())),
            };
        }

        Ok(state)
    }
}

#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TimeType {
    Wall,
    Standard,
    UTC,
}

impl TimeType {
    fn from_char(c: char) -> Option<Self> {
        Some(match c {
            'w' => Self::Wall,
            's' => Self::Standard,
            'u' | 'g' | 'z' => Self::UTC,
            _ => return None,
        })
    }
}

#[derive(PartialEq, Debug, Copy, Clone)]
pub struct TimeSpecAndType(pub TimeSpec, pub TimeType);

impl FromStr for TimeSpecAndType {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if input == "-" {
            return Ok(TimeSpecAndType(TimeSpec::Zero, TimeType::Wall));
        } else if input.chars().all(|c| c == '-' || c.is_ascii_digit()) {
            return Ok(TimeSpecAndType(TimeSpec::from_str(input)?, TimeType::Wall));
        }

        let (input, ty) = match input.chars().last().and_then(TimeType::from_char) {
            Some(ty) => (&input[..input.len() - 1], Some(ty)),
            None => (input, None),
        };

        let spec = TimeSpec::from_str(input)?;
        Ok(TimeSpecAndType(spec, ty.unwrap_or(TimeType::Wall)))
    }
}

/// The time at which the rules change for a location.
///
/// This is described with as few units as possible: a change that occurs at
/// the beginning of the year lists only the year, a change that occurs on a
/// particular day has to list the year, month, and day, and one that occurs
/// at a particular second has to list everything.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum ChangeTime {
    /// The earliest point in a particular **year**.
    UntilYear(Year),
    /// The earliest point in a particular **month**.
    UntilMonth(Year, Month),
    /// The earliest point in a particular **day**.
    UntilDay(Year, Month, DaySpec),
    /// The earliest point in a particular **hour, minute, or second**.
    UntilTime(Year, Month, DaySpec, TimeSpecAndType),
}

impl ChangeTime {
    /// Convert this change time to an absolute timestamp, as the number of
    /// seconds since the Unix epoch that the change occurs at.
    pub fn to_timestamp(&self, utc_offset: i64, dst_offset: i64) -> i64 {
        fn seconds_in_year(year: i64) -> i64 {
            if is_leap(year) {
                366 * 24 * 60 * 60
            } else {
                365 * 24 * 60 * 60
            }
        }

        fn seconds_until_start_of_year(year: i64) -> i64 {
            if year >= 1970 {
                (1970..year).map(seconds_in_year).sum()
            } else {
                -(year..1970).map(seconds_in_year).sum::<i64>()
            }
        }

        fn time_to_timestamp(
            year: i64,
            month: i8,
            day: i8,
            hour: i8,
            minute: i8,
            second: i8,
        ) -> i64 {
            const MONTHS_NON_LEAP: [i64; 12] = [
                0,
                31,
                31 + 28,
                31 + 28 + 31,
                31 + 28 + 31 + 30,
                31 + 28 + 31 + 30 + 31,
                31 + 28 + 31 + 30 + 31 + 30,
                31 + 28 + 31 + 30 + 31 + 30 + 31,
                31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
                31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
                31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
                31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
            ];
            const MONTHS_LEAP: [i64; 12] = [
                0,
                31,
                31 + 29,
                31 + 29 + 31,
                31 + 29 + 31 + 30,
                31 + 29 + 31 + 30 + 31,
                31 + 29 + 31 + 30 + 31 + 30,
                31 + 29 + 31 + 30 + 31 + 30 + 31,
                31 + 29 + 31 + 30 + 31 + 30 + 31 + 31,
                31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
                31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
                31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
            ];
            seconds_until_start_of_year(year)
                + 60 * 60
                    * 24
                    * if is_leap(year) {
                        MONTHS_LEAP[month as usize - 1]
                    } else {
                        MONTHS_NON_LEAP[month as usize - 1]
                    }
                + 60 * 60 * 24 * (day as i64 - 1)
                + 60 * 60 * hour as i64
                + 60 * minute as i64
                + second as i64
        }

        match *self {
            ChangeTime::UntilYear(Year::Number(y)) => {
                time_to_timestamp(y, 1, 1, 0, 0, 0) - (utc_offset + dst_offset)
            }
            ChangeTime::UntilMonth(Year::Number(y), m) => {
                time_to_timestamp(y, m as i8, 1, 0, 0, 0) - (utc_offset + dst_offset)
            }
            ChangeTime::UntilDay(Year::Number(y), m, d) => {
                let (m, wd) = d.to_concrete_day(y, m);
                time_to_timestamp(y, m as i8, wd, 0, 0, 0) - (utc_offset + dst_offset)
            }
            ChangeTime::UntilTime(Year::Number(y), m, d, time) => {
                (match time.0 {
                    TimeSpec::Zero => {
                        let (m, wd) = d.to_concrete_day(y, m);
                        time_to_timestamp(y, m as i8, wd, 0, 0, 0)
                    }
                    TimeSpec::Hours(h) => {
                        let (m, wd) = d.to_concrete_day(y, m);
                        time_to_timestamp(y, m as i8, wd, h, 0, 0)
                    }
                    TimeSpec::HoursMinutes(h, min) => {
                        let (m, wd) = d.to_concrete_day(y, m);
                        time_to_timestamp(y, m as i8, wd, h, min, 0)
                    }
                    TimeSpec::HoursMinutesSeconds(h, min, s) => {
                        let (m, wd) = d.to_concrete_day(y, m);
                        time_to_timestamp(y, m as i8, wd, h, min, s)
                    }
                }) - match time.1 {
                    TimeType::UTC => 0,
                    TimeType::Standard => utc_offset,
                    TimeType::Wall => utc_offset + dst_offset,
                }
            }

            _ => unreachable!(),
        }
    }

    pub fn year(&self) -> i64 {
        match *self {
            ChangeTime::UntilYear(Year::Number(y)) => y,
            ChangeTime::UntilMonth(Year::Number(y), ..) => y,
            ChangeTime::UntilDay(Year::Number(y), ..) => y,
            ChangeTime::UntilTime(Year::Number(y), ..) => y,
            _ => unreachable!(),
        }
    }
}

/// The information contained in both zone lines *and* zone continuation lines.
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct ZoneInfo<'a> {
    /// The amount of time that needs to be added to UTC to get the standard
    /// time in this zone.
    pub utc_offset: TimeSpec,
    /// The name of all the rules that should apply in the time zone, or the
    /// amount of time to add.
    pub saving: Saving<'a>,
    /// The format for time zone abbreviations, with `%s` as the string marker.
    pub format: &'a str,
    /// The time at which the rules change for this location, or `None` if
    /// these rules are in effect until the end of time (!).
    pub time: Option<ChangeTime>,
}

impl<'a> ZoneInfo<'a> {
    fn from_iter(iter: impl Iterator<Item = &'a str>) -> Result<Self, Error> {
        let mut state = ZoneInfoState::Start;
        for part in iter {
            state = match (state, part) {
                // In theory a comment is allowed to come after a field without preceding
                // whitespace, but this doesn't seem to be used in practice.
                (st, _) if part.starts_with('#') => {
                    state = st;
                    break;
                }
                (ZoneInfoState::Start, offset) => ZoneInfoState::Save {
                    offset: TimeSpec::from_str(offset)?,
                },
                (ZoneInfoState::Save { offset }, saving) => ZoneInfoState::Format {
                    offset,
                    saving: Saving::from_str(saving)?,
                },
                (ZoneInfoState::Format { offset, saving }, format) => ZoneInfoState::Year {
                    offset,
                    saving,
                    format,
                },
                (
                    ZoneInfoState::Year {
                        offset,
                        saving,
                        format,
                    },
                    year,
                ) => ZoneInfoState::Month {
                    offset,
                    saving,
                    format,
                    year: Year::from_str(year)?,
                },
                (
                    ZoneInfoState::Month {
                        offset,
                        saving,
                        format,
                        year,
                    },
                    month,
                ) => ZoneInfoState::Day {
                    offset,
                    saving,
                    format,
                    year,
                    month: Month::from_str(month)?,
                },
                (
                    ZoneInfoState::Day {
                        offset,
                        saving,
                        format,
                        year,
                        month,
                    },
                    day,
                ) => ZoneInfoState::Time {
                    offset,
                    saving,
                    format,
                    year,
                    month,
                    day: DaySpec::from_str(day)?,
                },
                (
                    ZoneInfoState::Time {
                        offset,
                        saving,
                        format,
                        year,
                        month,
                        day,
                    },
                    time,
                ) => {
                    return Ok(Self {
                        utc_offset: offset,
                        saving,
                        format,
                        time: Some(ChangeTime::UntilTime(
                            year,
                            month,
                            day,
                            TimeSpecAndType::from_str(time)?,
                        )),
                    })
                }
            };
        }

        match state {
            ZoneInfoState::Start | ZoneInfoState::Save { .. } | ZoneInfoState::Format { .. } => {
                Err(Error::NotParsedAsZoneLine)
            }
            ZoneInfoState::Year {
                offset,
                saving,
                format,
            } => Ok(Self {
                utc_offset: offset,
                saving,
                format,
                time: None,
            }),
            ZoneInfoState::Month {
                offset,
                saving,
                format,
                year,
            } => Ok(Self {
                utc_offset: offset,
                saving,
                format,
                time: Some(ChangeTime::UntilYear(year)),
            }),
            ZoneInfoState::Day {
                offset,
                saving,
                format,
                year,
                month,
            } => Ok(Self {
                utc_offset: offset,
                saving,
                format,
                time: Some(ChangeTime::UntilMonth(year, month)),
            }),
            ZoneInfoState::Time {
                offset,
                saving,
                format,
                year,
                month,
                day,
            } => Ok(Self {
                utc_offset: offset,
                saving,
                format,
                time: Some(ChangeTime::UntilDay(year, month, day)),
            }),
        }
    }
}

enum ZoneInfoState<'a> {
    Start,
    Save {
        offset: TimeSpec,
    },
    Format {
        offset: TimeSpec,
        saving: Saving<'a>,
    },
    Year {
        offset: TimeSpec,
        saving: Saving<'a>,
        format: &'a str,
    },
    Month {
        offset: TimeSpec,
        saving: Saving<'a>,
        format: &'a str,
        year: Year,
    },
    Day {
        offset: TimeSpec,
        saving: Saving<'a>,
        format: &'a str,
        year: Year,
        month: Month,
    },
    Time {
        offset: TimeSpec,
        saving: Saving<'a>,
        format: &'a str,
        year: Year,
        month: Month,
        day: DaySpec,
    },
}

/// The amount of daylight saving time (DST) to apply to this timespan. This
/// is a special type for a certain field in a zone line, which can hold
/// different types of value.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Saving<'a> {
    /// Just stick to the base offset.
    NoSaving,
    /// This amount of time should be saved while this timespan is in effect.
    /// (This is the equivalent to there being a single one-off rule with the
    /// given amount of time to save).
    OneOff(TimeSpec),
    /// All rules with the given name should apply while this timespan is in
    /// effect.
    Multiple(&'a str),
}

impl<'a> Saving<'a> {
    fn from_str(input: &'a str) -> Result<Self, Error> {
        if input == "-" {
            Ok(Self::NoSaving)
        } else if input
            .chars()
            .all(|c| c == '-' || c == '_' || c.is_alphabetic())
        {
            Ok(Self::Multiple(input))
        } else if let Ok(time) = TimeSpec::from_str(input) {
            Ok(Self::OneOff(time))
        } else {
            Err(Error::CouldNotParseSaving(input.to_string()))
        }
    }
}

/// A **rule** definition line.
///
/// According to the `zic(8)` man page, a rule line has this form, along with
/// an example:
///
/// ```text
///     Rule  NAME  FROM  TO    TYPE  IN   ON       AT    SAVE  LETTER/S
///     Rule  US    1967  1973  ‐     Apr  lastSun  2:00  1:00  D
/// ```
///
/// Apart from the opening `Rule` to specify which kind of line this is, and
/// the `type` column, every column in the line has a field in this struct.
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Rule<'a> {
    /// The name of the set of rules that this rule is part of.
    pub name: &'a str,
    /// The first year in which the rule applies.
    pub from_year: Year,
    /// The final year, or `None` if’s ‘only’.
    pub to_year: Option<Year>,
    /// The month in which the rule takes effect.
    pub month: Month,
    /// The day on which the rule takes effect.
    pub day: DaySpec,
    /// The time of day at which the rule takes effect.
    pub time: TimeSpecAndType,
    /// The amount of time to be added when the rule is in effect.
    pub time_to_add: TimeSpec,
    /// The variable part of time zone abbreviations to be used when this rule
    /// is in effect, if any.
    pub letters: Option<&'a str>,
}

impl<'a> Rule<'a> {
    fn from_str(input: &'a str) -> Result<Self, Error> {
        let mut state = RuleState::Start;
        // Not handled: quoted strings, parts of which are allowed to contain whitespace.
        // Extra complexity does not seem worth it while they don't seem to be used in practice.
        for part in input.split_ascii_whitespace() {
            if part.starts_with('#') {
                continue;
            }

            state = match (state, part) {
                (RuleState::Start, "Rule") => RuleState::Name,
                (RuleState::Name, name) => RuleState::FromYear { name },
                (RuleState::FromYear { name }, year) => RuleState::ToYear {
                    name,
                    from_year: Year::from_str(year)?,
                },
                (RuleState::ToYear { name, from_year }, year) => RuleState::Type {
                    name,
                    from_year,
                    // The end year can be ‘only’ to indicate that this rule only
                    // takes place on that year.
                    to_year: match year {
                        "only" => None,
                        _ => Some(Year::from_str(year)?),
                    },
                },
                // According to the spec, the only value inside the ‘type’ column
                // should be “-”, so throw an error if it isn’t. (It only exists
                // for compatibility with old versions that used to contain year
                // types.) Sometimes “‐”, a Unicode hyphen, is used as well.
                (
                    RuleState::Type {
                        name,
                        from_year,
                        to_year,
                    },
                    "-" | "\u{2010}",
                ) => RuleState::Month {
                    name,
                    from_year,
                    to_year,
                },
                (RuleState::Type { .. }, _) => {
                    return Err(Error::TypeColumnContainedNonHyphen(part.to_string()))
                }
                (
                    RuleState::Month {
                        name,
                        from_year,
                        to_year,
                    },
                    month,
                ) => RuleState::Day {
                    name,
                    from_year,
                    to_year,
                    month: Month::from_str(month)?,
                },
                (
                    RuleState::Day {
                        name,
                        from_year,
                        to_year,
                        month,
                    },
                    day,
                ) => RuleState::Time {
                    name,
                    from_year,
                    to_year,
                    month,
                    day: DaySpec::from_str(day)?,
                },
                (
                    RuleState::Time {
                        name,
                        from_year,
                        to_year,
                        month,
                        day,
                    },
                    time,
                ) => RuleState::TimeToAdd {
                    name,
                    from_year,
                    to_year,
                    month,
                    day,
                    time: TimeSpecAndType::from_str(time)?,
                },
                (
                    RuleState::TimeToAdd {
                        name,
                        from_year,
                        to_year,
                        month,
                        day,
                        time,
                    },
                    time_to_add,
                ) => RuleState::Letters {
                    name,
                    from_year,
                    to_year,
                    month,
                    day,
                    time,
                    time_to_add: TimeSpec::from_str(time_to_add)?,
                },
                (
                    RuleState::Letters {
                        name,
                        from_year,
                        to_year,
                        month,
                        day,
                        time,
                        time_to_add,
                    },
                    letters,
                ) => {
                    return Ok(Self {
                        name,
                        from_year,
                        to_year,
                        month,
                        day,
                        time,
                        time_to_add,
                        letters: match letters {
                            "-" => None,
                            _ => Some(letters),
                        },
                    })
                }
                _ => return Err(Error::NotParsedAsRuleLine),
            };
        }

        Err(Error::NotParsedAsRuleLine)
    }
}

enum RuleState<'a> {
    Start,
    Name,
    FromYear {
        name: &'a str,
    },
    ToYear {
        name: &'a str,
        from_year: Year,
    },
    Type {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
    },
    Month {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
    },
    Day {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
        month: Month,
    },
    Time {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
        month: Month,
        day: DaySpec,
    },
    TimeToAdd {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
        month: Month,
        day: DaySpec,
        time: TimeSpecAndType,
    },
    Letters {
        name: &'a str,
        from_year: Year,
        to_year: Option<Year>,
        month: Month,
        day: DaySpec,
        time: TimeSpecAndType,
        time_to_add: TimeSpec,
    },
}

/// A **zone** definition line.
///
/// According to the `zic(8)` man page, a zone line has this form, along with
/// an example:
///
/// ```text
///     Zone  NAME                GMTOFF  RULES/SAVE  FORMAT  [UNTILYEAR [MONTH [DAY [TIME]]]]
///     Zone  Australia/Adelaide  9:30    Aus         AC%sT   1971       Oct    31   2:00
/// ```
///
/// The opening `Zone` identifier is ignored, and the last four columns are
/// all optional, with their variants consolidated into a `ChangeTime`.
///
/// The `Rules/Save` column, if it contains a value, *either* contains the
/// name of the rules to use for this zone, *or* contains a one-off period of
/// time to save.
///
/// A continuation rule line contains all the same fields apart from the
/// `Name` column and the opening `Zone` identifier.
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Zone<'a> {
    /// The name of the time zone.
    pub name: &'a str,
    /// All the other fields of info.
    pub info: ZoneInfo<'a>,
}

impl<'a> Zone<'a> {
    fn from_str(input: &'a str) -> Result<Self, Error> {
        let mut iter = input.split_ascii_whitespace();
        if iter.next() != Some("Zone") {
            return Err(Error::NotParsedAsZoneLine);
        }

        let name = match iter.next() {
            Some(name) => name,
            None => return Err(Error::NotParsedAsZoneLine),
        };

        Ok(Self {
            name,
            info: ZoneInfo::from_iter(iter)?,
        })
    }
}

#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Link<'a> {
    pub existing: &'a str,
    pub new: &'a str,
}

impl<'a> Link<'a> {
    fn from_str(input: &'a str) -> Result<Self, Error> {
        let mut iter = input.split_ascii_whitespace();
        if iter.next() != Some("Link") {
            return Err(Error::NotParsedAsLinkLine);
        }

        Ok(Link {
            existing: iter.next().ok_or(Error::NotParsedAsLinkLine)?,
            new: iter.next().ok_or(Error::NotParsedAsLinkLine)?,
        })
    }
}

#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Line<'a> {
    /// This line is empty.
    Space,
    /// This line contains a **zone** definition.
    Zone(Zone<'a>),
    /// This line contains a **continuation** of a zone definition.
    Continuation(ZoneInfo<'a>),
    /// This line contains a **rule** definition.
    Rule(Rule<'a>),
    /// This line contains a **link** definition.
    Link(Link<'a>),
}

impl<'a> Line<'a> {
    /// Attempt to parse this line, returning a `Line` depending on what
    /// type of line it was, or an `Error` if it couldn't be parsed.
    pub fn new(input: &'a str) -> Result<Line<'a>, Error> {
        let input = match input.split_once('#') {
            Some((input, _)) => input,
            None => input,
        };

        if input.trim().is_empty() {
            return Ok(Line::Space);
        }

        if input.starts_with("Zone") {
            return Ok(Line::Zone(Zone::from_str(input)?));
        }

        if input.starts_with(&[' ', '\t'][..]) {
            return Ok(Line::Continuation(ZoneInfo::from_iter(
                input.split_ascii_whitespace(),
            )?));
        }

        if input.starts_with("Rule") {
            return Ok(Line::Rule(Rule::from_str(input)?));
        }

        if input.starts_with("Link") {
            return Ok(Line::Link(Link::from_str(input)?));
        }

        Err(Error::InvalidLineType(input.to_string()))
    }
}

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

    #[test]
    fn weekdays() {
        assert_eq!(
            Weekday::calculate(1970, Month::January, 1),
            Weekday::Thursday
        );
        assert_eq!(
            Weekday::calculate(2017, Month::February, 11),
            Weekday::Saturday
        );
        assert_eq!(Weekday::calculate(1890, Month::March, 2), Weekday::Sunday);
        assert_eq!(Weekday::calculate(2100, Month::April, 20), Weekday::Tuesday);
        assert_eq!(Weekday::calculate(2009, Month::May, 31), Weekday::Sunday);
        assert_eq!(Weekday::calculate(2001, Month::June, 9), Weekday::Saturday);
        assert_eq!(Weekday::calculate(1995, Month::July, 21), Weekday::Friday);
        assert_eq!(Weekday::calculate(1982, Month::August, 8), Weekday::Sunday);
        assert_eq!(
            Weekday::calculate(1962, Month::September, 6),
            Weekday::Thursday
        );
        assert_eq!(
            Weekday::calculate(1899, Month::October, 14),
            Weekday::Saturday
        );
        assert_eq!(
            Weekday::calculate(2016, Month::November, 18),
            Weekday::Friday
        );
        assert_eq!(
            Weekday::calculate(2010, Month::December, 19),
            Weekday::Sunday
        );
        assert_eq!(
            Weekday::calculate(2016, Month::February, 29),
            Weekday::Monday
        );
    }

    #[test]
    fn last_monday() {
        let dayspec = DaySpec::Last(Weekday::Monday);
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::January),
            (Month::January, 25)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::February),
            (Month::February, 29)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::March),
            (Month::March, 28)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::April),
            (Month::April, 25)
        );
        assert_eq!(dayspec.to_concrete_day(2016, Month::May), (Month::May, 30));
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::June),
            (Month::June, 27)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::July),
            (Month::July, 25)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::August),
            (Month::August, 29)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::September),
            (Month::September, 26)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::October),
            (Month::October, 31)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::November),
            (Month::November, 28)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::December),
            (Month::December, 26)
        );
    }

    #[test]
    fn first_monday_on_or_after() {
        let dayspec = DaySpec::FirstOnOrAfter(Weekday::Monday, 20);
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::January),
            (Month::January, 25)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::February),
            (Month::February, 22)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::March),
            (Month::March, 21)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::April),
            (Month::April, 25)
        );
        assert_eq!(dayspec.to_concrete_day(2016, Month::May), (Month::May, 23));
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::June),
            (Month::June, 20)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::July),
            (Month::July, 25)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::August),
            (Month::August, 22)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::September),
            (Month::September, 26)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::October),
            (Month::October, 24)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::November),
            (Month::November, 21)
        );
        assert_eq!(
            dayspec.to_concrete_day(2016, Month::December),
            (Month::December, 26)
        );
    }

    // A couple of specific timezone transitions that we care about
    #[test]
    fn first_sunday_in_toronto() {
        let dayspec = DaySpec::FirstOnOrAfter(Weekday::Sunday, 25);
        assert_eq!(dayspec.to_concrete_day(1932, Month::April), (Month::May, 1));
        // asia/zion
        let dayspec = DaySpec::LastOnOrBefore(Weekday::Friday, 1);
        assert_eq!(
            dayspec.to_concrete_day(2012, Month::April),
            (Month::March, 30)
        );
    }

    #[test]
    fn to_timestamp() {
        let time = ChangeTime::UntilYear(Year::Number(1970));
        assert_eq!(time.to_timestamp(0, 0), 0);
        let time = ChangeTime::UntilYear(Year::Number(2016));
        assert_eq!(time.to_timestamp(0, 0), 1451606400);
        let time = ChangeTime::UntilYear(Year::Number(1900));
        assert_eq!(time.to_timestamp(0, 0), -2208988800);
        let time = ChangeTime::UntilTime(
            Year::Number(2000),
            Month::February,
            DaySpec::Last(Weekday::Sunday),
            TimeSpecAndType(TimeSpec::Hours(9), TimeType::Wall),
        );
        assert_eq!(time.to_timestamp(3600, 3600), 951642000 - 2 * 3600);
    }

    macro_rules! test {
        ($name:ident: $input:expr => $result:expr) => {
            #[test]
            fn $name() {
                assert_eq!(Line::new($input), $result);
            }
        };
    }

    test!(empty:    ""          => Ok(Line::Space));
    test!(spaces:   "        "  => Ok(Line::Space));

    test!(rule_1: "Rule  US    1967  1973  ‐     Apr  lastSun  2:00  1:00  D" => Ok(Line::Rule(Rule {
        name:         "US",
        from_year:    Year::Number(1967),
        to_year:      Some(Year::Number(1973)),
        month:        Month::April,
        day:          DaySpec::Last(Weekday::Sunday),
        time:         TimeSpec::HoursMinutes(2, 0).with_type(TimeType::Wall),
        time_to_add:  TimeSpec::HoursMinutes(1, 0),
        letters:      Some("D"),
    })));

    test!(rule_2: "Rule	Greece	1976	only	-	Oct	10	2:00s	0	-" => Ok(Line::Rule(Rule {
        name:         "Greece",
        from_year:    Year::Number(1976),
        to_year:      None,
        month:        Month::October,
        day:          DaySpec::Ordinal(10),
        time:         TimeSpec::HoursMinutes(2, 0).with_type(TimeType::Standard),
        time_to_add:  TimeSpec::Hours(0),
        letters:      None,
    })));

    test!(rule_3: "Rule	EU	1977	1980	-	Apr	Sun>=1	 1:00u	1:00	S" => Ok(Line::Rule(Rule {
        name:         "EU",
        from_year:    Year::Number(1977),
        to_year:      Some(Year::Number(1980)),
        month:        Month::April,
        day:          DaySpec::FirstOnOrAfter(Weekday::Sunday, 1),
        time:         TimeSpec::HoursMinutes(1, 0).with_type(TimeType::UTC),
        time_to_add:  TimeSpec::HoursMinutes(1, 0),
        letters:      Some("S"),
    })));

    test!(no_hyphen: "Rule	EU	1977	1980	HEY	Apr	Sun>=1	 1:00u	1:00	S"         => Err(Error::TypeColumnContainedNonHyphen("HEY".to_string())));
    test!(bad_month: "Rule	EU	1977	1980	-	Febtober	Sun>=1	 1:00u	1:00	S" => Err(Error::FailedMonthParse("febtober".to_string())));

    test!(zone: "Zone  Australia/Adelaide  9:30    Aus         AC%sT   1971 Oct 31  2:00:00" => Ok(Line::Zone(Zone {
        name: "Australia/Adelaide",
        info: ZoneInfo {
            utc_offset:  TimeSpec::HoursMinutes(9, 30),
            saving:      Saving::Multiple("Aus"),
            format:      "AC%sT",
            time:        Some(ChangeTime::UntilTime(Year::Number(1971), Month::October, DaySpec::Ordinal(31), TimeSpec::HoursMinutesSeconds(2, 0, 0).with_type(TimeType::Wall))),
        },
    })));

    test!(continuation_1: "                          9:30    Aus         AC%sT   1971 Oct 31  2:00:00" => Ok(Line::Continuation(ZoneInfo {
        utc_offset:  TimeSpec::HoursMinutes(9, 30),
        saving:      Saving::Multiple("Aus"),
        format:      "AC%sT",
        time:        Some(ChangeTime::UntilTime(Year::Number(1971), Month::October, DaySpec::Ordinal(31), TimeSpec::HoursMinutesSeconds(2, 0, 0).with_type(TimeType::Wall))),
    })));

    test!(continuation_2: "			1:00	C-Eur	CE%sT	1943 Oct 25" => Ok(Line::Continuation(ZoneInfo {
        utc_offset:  TimeSpec::HoursMinutes(1, 00),
        saving:      Saving::Multiple("C-Eur"),
        format:      "CE%sT",
        time:        Some(ChangeTime::UntilDay(Year::Number(1943), Month::October, DaySpec::Ordinal(25))),
    })));

    test!(zone_hyphen: "Zone Asia/Ust-Nera\t 9:32:54 -\tLMT\t1919" => Ok(Line::Zone(Zone {
        name: "Asia/Ust-Nera",
        info: ZoneInfo {
            utc_offset:  TimeSpec::HoursMinutesSeconds(9, 32, 54),
            saving:      Saving::NoSaving,
            format:      "LMT",
            time:        Some(ChangeTime::UntilYear(Year::Number(1919))),
        },
    })));

    #[test]
    fn negative_offsets() {
        static LINE: &str = "Zone    Europe/London   -0:01:15 -  LMT 1847 Dec  1  0:00s";
        let zone = Zone::from_str(LINE).unwrap();
        assert_eq!(
            zone.info.utc_offset,
            TimeSpec::HoursMinutesSeconds(0, -1, -15)
        );
    }

    #[test]
    fn negative_offsets_2() {
        static LINE: &str =
            "Zone        Europe/Madrid   -0:14:44 -      LMT     1901 Jan  1  0:00s";
        let zone = Zone::from_str(LINE).unwrap();
        assert_eq!(
            zone.info.utc_offset,
            TimeSpec::HoursMinutesSeconds(0, -14, -44)
        );
    }

    #[test]
    fn negative_offsets_3() {
        static LINE: &str = "Zone America/Danmarkshavn -1:14:40 -    LMT 1916 Jul 28";
        let zone = Zone::from_str(LINE).unwrap();
        assert_eq!(
            zone.info.utc_offset,
            TimeSpec::HoursMinutesSeconds(-1, -14, -40)
        );
    }

    test!(link: "Link  Europe/Istanbul  Asia/Istanbul" => Ok(Line::Link(Link {
        existing:  "Europe/Istanbul",
        new:       "Asia/Istanbul",
    })));

    #[test]
    fn month() {
        assert_eq!(Month::from_str("Aug"), Ok(Month::August));
        assert_eq!(Month::from_str("December"), Ok(Month::December));
    }

    test!(golb: "GOLB" => Err(Error::InvalidLineType("GOLB".to_string())));

    test!(comment: "# this is a comment" => Ok(Line::Space));
    test!(another_comment: "     # so is this" => Ok(Line::Space));
    test!(multiple_hash: "     # so is this ## " => Ok(Line::Space));
    test!(non_comment: " this is not a # comment" => Err(Error::InvalidTimeSpecAndType("this".to_string())));

    test!(comment_after: "Link  Europe/Istanbul  Asia/Istanbul #with a comment after" => Ok(Line::Link(Link {
        existing:  "Europe/Istanbul",
        new:       "Asia/Istanbul",
    })));

    test!(two_comments_after: "Link  Europe/Istanbul  Asia/Istanbul   # comment ## comment" => Ok(Line::Link(Link {
        existing:  "Europe/Istanbul",
        new:       "Asia/Istanbul",
    })));

    #[test]
    fn leap_years() {
        assert!(!is_leap(1900));
        assert!(is_leap(1904));
        assert!(is_leap(1964));
        assert!(is_leap(1996));
        assert!(!is_leap(1997));
        assert!(!is_leap(1997));
        assert!(!is_leap(1999));
        assert!(is_leap(2000));
        assert!(is_leap(2016));
        assert!(!is_leap(2100));
    }
}