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

mod parse;

use std::rc::Rc;
use std::io;
use std::fmt;
use std::ptr;
use std::error;
use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
use std::ops::{Add, Sub, Neg};

/// A timezone.
///
/// There are several ways to create a new `Timezone`. It can be loaded from the
/// [`IANA Time Zone Database`](https://www.iana.org/time-zones), following the `Area/Location`
/// pattern (e.g. `Europe/Paris`) with `Timezone::new`. A `Timezone` can be created as a fixed offset from `UTC`
/// with `Timezone::fixed` or `UTC` itself with `Timezone::utc`. Finally, the `Timezone` can match the
/// system local timezone with `Timezone::local`.
///
/// # Example
///
/// ```rust
/// let utc = hourglass::Timezone::utc();
/// let now = utc.now();
///
/// for tzname in &["Europe/Paris", "America/New_York", "Asia/Seoul"] {
///     let tz = hourglass::Timezone::new(tzname).unwrap();
///     let now = now.project(&tz);
///     println!("it is now {:?} in {}", now, tzname);
/// }
/// ```
pub struct Timezone {
    /// The `UTC` offset transitions
    trans: Vec<Transition>,
    /// The extra transition rule
    trule: Option<TransRule>,
}

#[derive(Debug)]
struct Transition {
    utc: i64,
    ttype: Rc<Type>,
}

#[derive(Debug)]
enum TransRule {
    Fixed(Type),
    Alternate {
        dst_start: GenericDay,
        dst_stime: i32,
        dst_end: GenericDay,
        dst_etime: i32,
        std: Type,
        dst: Type,
    },
}

#[derive(Debug)]
enum GenericDay {
    Julian0 {
        jday: i32,
    },
    Julian1 {
        jday: i32,
    },
    MWDRule {
        month: i32,
        week: i32,
        wday: i32,
    },
}

#[derive(Debug, PartialEq, Eq, Clone)]
struct Type {
    off: i32,
    is_dst: bool,
    abbr: String,
}

impl Timezone {
    /// Try to load a new `Timezone`.
    /// It assumes that the zoneinfo data are located
    /// under `/usr/share/zoneinfo`.
    pub fn new(timezone: &str) -> io::Result<Self> {
        parse::load_timezone(timezone)
    }

    /// Load the local `Timezone` set by the system,
    /// disregarding the `TZ` environment variable.
    pub fn local() -> io::Result<Self> {
        parse::load_timezone("localtime")
    }

    /// Returns the `UTC` timezone.
    pub fn utc() -> Self {
        Self::fixed(0)
    }

    /// Returns a fixed offset to `UTC` timezone.
    /// The provided offset is in seconds.
    pub fn fixed(sec: i32) -> Self {
        Timezone {
            trans: vec![Transition {
                            utc: std::i64::MIN,
                            ttype: Rc::new(Type {
                                off: sec,
                                is_dst: false,
                                abbr: "".to_owned(),
                            }),
                        }],
            trule: None,
        }
    }

    /// Compute the `UTC` offset in this `Timezone` for unix timestamp `t`.
    fn offset(&self, stamp: i64) -> &Type {
        let idx = match self.trans.binary_search_by(|t| t.utc.cmp(&stamp)) {
            Err(i) if i == self.trans.len() => return self.offset_trule(stamp),
            Err(0) => 0,
            Err(i) => i - 1,
            Ok(i) => i,
        };

        &self.trans[idx].ttype
    }

    /// Compute the `UTC` offset in this `Timezone` for unix timestamp `t`
    /// using the transition rule.
    fn offset_trule(&self, stamp: i64) -> &Type {
        match self.trule {
            None => &self.trans.last().unwrap().ttype,
            Some(ref rule) => rule.get_type(stamp),
        }
    }

    /// Return the `Datetime` representing now, relative to this `Timezone`.
    pub fn now(&self) -> Datetime {
        let mut ts = libc::timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };

        unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) };

        Datetime {
            tz: self,
            sec: ts.tv_sec,
            nano: ts.tv_nsec as i32,
            is_60th_sec: false,
        }
    }

    /// Parse a `Datetime` relative to this `Timezone` according to the
    /// given format. Timezone-related field are ignored. An `InputError`
    /// is returned if the string does not match the format.
    pub fn parse(&self, s: &str, fmt: &str) -> Result<Datetime, InputError> {
        let mut tm = libc::tm {
            tm_sec: 0,
            tm_min: 0,
            tm_hour: 0,
            tm_mday: 1,
            tm_mon: 0,
            tm_year: 0,
            tm_wday: 0,
            tm_yday: 0,
            tm_isdst: 0,
            // Unused
            tm_gmtoff: 0,
            tm_zone: ptr::null(),
        };
        let ret = unsafe {
            strptime(s.as_ptr() as *const libc::c_char,
                     fmt.as_ptr() as *const libc::c_char,
                     &mut tm)
        };

        if ret == ptr::null() {
            Err(InputError::InvalidFormat)
        } else {
            self.datetime(tm.tm_year + 1900,
                          tm.tm_mon + 1,
                          tm.tm_mday,
                          tm.tm_hour,
                          tm.tm_min,
                          tm.tm_sec,
                          0)
        }
    }

    /// Create a new `Datetime` from a Unix timestamp. The provided
    /// timestamp represents Unix seconds from the Epoch, discarding any
    /// leap seconds that may have happened in between. A Unix timestamp
    /// is ambiguous on leap second insertion (e.g. `1435708800` is
    /// equal to both `2015-06-30T23:59:60Z` and `2015-07-01T00:00:00Z`)
    /// however, `unix` will always choose the non-leap second. Return
    /// an `InputError` if `nano` ∉ [0, 999999999].
    pub fn unix(&self, stamp: i64, nano: i32) -> Result<Datetime, InputError> {
        if nano < 0 || nano > 999_999_999 {
            return Err(InputError::InvalidNano);
        }

        Ok(Datetime {
            tz: self,
            sec: stamp,
            nano: nano,
            is_60th_sec: false,
        })
    }

    /// Create a new `Datetime` relative to this `Timezone`.
    /// An `InputError` is returned if the following constraints do not hold:
    ///
    /// - `month` ∊ [1, 12]
    /// - `day` ∊ [1, 31] and is valid within the month
    /// - `hour` ∊ [0, 23]
    /// - `minute` ∊ [0, 59]
    /// - `second` ∊ [0, 60]
    /// - `nano` ∊ [0, 999999999]
    pub fn datetime(&self,
                    year: i32,
                    month: i32,
                    day: i32,
                    hour: i32,
                    minute: i32,
                    second: i32,
                    nano: i32)
                    -> Result<Datetime, InputError> {
        let is_leap_year = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;

        // Error if constaints described in documentation do not hold.
        if month < 1 || month > 12 {
            return Err(InputError::InvalidMonth);
        } else if hour < 0 || hour > 23 {
            return Err(InputError::InvalidHour);
        } else if minute < 0 || minute > 59 {
            return Err(InputError::InvalidMinute);
        } else if second < 0 || second > 60 {
            return Err(InputError::InvalidSecond);
        } else if nano < 0 || nano > 999_999_999 {
            return Err(InputError::InvalidNano);
        }

        let max_day = match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 if is_leap_year => 30,
            2 => 29,
            _ => unreachable!(),
        };

        if day < 1 || day > max_day {
            return Err(InputError::InvalidDay);
        }

        // Let the libc do the heavy lifting.
        let utc_dt = libc::tm {
            tm_sec: if second == 60 {
                59
            } else {
                second as i32
            },
            tm_min: minute as i32,
            tm_hour: hour as i32,
            tm_mday: day as i32,
            tm_mon: (month - 1) as i32,
            tm_year: (year - 1900) as i32,
            tm_wday: 0,
            tm_yday: 0,
            tm_isdst: 0,
            tm_gmtoff: 0,
            tm_zone: ptr::null(),
        };

        let mut sec = tm_to_stamp(&utc_dt);
        let utc_offset = self.offset(sec).off;
        sec -= utc_offset as i64;

        if second == 60 {
            if let Err(_) = LEAP_SECONDS.binary_search(&(sec + 1)) {
                return Err(InputError::InvalidLeapSecond);
            }
            Ok(Datetime {
                tz: self,
                // The stamp actually corresponds to 00:00:00. I cheated
                // when making tm_to_stamp compute the stamp (I used
                // 59 instead of 60 seconds) because of the lack of
                // leap second support in unix timestamp. We need to
                // adjust now.
                sec: sec + 1,
                nano: nano,
                is_60th_sec: true,
            })
        } else {
            Ok(Datetime {
                tz: self,
                sec: sec,
                nano: nano,
                is_60th_sec: false,
            })
        }
    }
}

impl GenericDay {
    fn cmp_t(&self, tm: &libc::tm) -> Ordering {
        const DAYS_MONTH: &'static [i32] = &[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        let tm_year = tm.tm_year + 1900;
        let tm_mon = tm.tm_mon + 1;

        let is_leap_year = (tm_year % 4 == 0 && tm_year % 100 != 0) || tm_year % 400 == 0;

        match *self {
            GenericDay::Julian0 { jday } => jday.cmp(&tm.tm_yday),
            GenericDay::Julian1 { jday } => {
                let yday = if is_leap_year && tm_mon > 2 {
                    tm.tm_yday
                } else {
                    tm.tm_yday + 1
                };
                jday.cmp(&yday)
            }
            GenericDay::MWDRule { month, week, wday } => {
                if month < tm_mon {
                    Ordering::Less
                } else if month > tm_mon {
                    Ordering::Greater
                } else {
                    let wday_on_first = (tm.tm_wday - tm.tm_mday + 1 + 5 * 7) % 7;
                    let days_in_month = if is_leap_year && tm_mon == 2 {
                        29
                    } else {
                        DAYS_MONTH[tm_mon as usize]
                    };

                    let mut matching_week = 0;
                    let mut last_matching_day = 0;
                    for d in 0..days_in_month {
                        if (wday_on_first + d) % 7 == wday {
                            last_matching_day = d;
                            matching_week += 1;
                        }
                        if matching_week == week {
                            break;
                        }
                    }
                    (last_matching_day + 1).cmp(&tm.tm_mday)
                }
            }
        }
    }

    fn approx_month(&self) -> i32 {
        match *self {
            GenericDay::Julian0 { jday } => jday / 30,
            GenericDay::Julian1 { jday } => jday / 30,
            GenericDay::MWDRule { month, .. } => month,
        }
    }

    fn cmp(&self, other: &GenericDay) -> Ordering {
        // I make the assumption that the dst
        // start and end are more than 1 month apart.
        self.approx_month().cmp(&other.approx_month())
    }
}

impl PartialEq<libc::tm> for GenericDay {
    fn eq(&self, tm: &libc::tm) -> bool {
        self.cmp_t(tm) == Ordering::Equal
    }
}

impl PartialOrd<libc::tm> for GenericDay {
    fn partial_cmp(&self, tm: &libc::tm) -> Option<Ordering> {
        Some(self.cmp_t(tm))
    }
}

impl PartialEq<GenericDay> for GenericDay {
    fn eq(&self, other: &GenericDay) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl PartialOrd<GenericDay> for GenericDay {
    fn partial_cmp(&self, other: &GenericDay) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl TransRule {
    fn get_type(&self, stamp: i64) -> &Type {
        match *self {
            TransRule::Fixed(ref t) => t,
            TransRule::Alternate { ref dst_start, dst_stime, ref dst_end, dst_etime, ref std, ref dst } => {
                let std_t = stamp_to_tm(stamp + std.off as i64);
                let std_sec = std_t.tm_hour * 3600 + std_t.tm_min * 60 + std_t.tm_sec;

                // TODO: more efficient way to compute dst_t from std_t?
                let dst_t = stamp_to_tm(stamp + dst.off as i64);
                let dst_sec = dst_t.tm_hour * 3600 + dst_t.tm_min * 60 + dst_t.tm_sec;

                if dst_start < dst_end {
                    match (dst_start.cmp_t(&std_t), dst_stime.cmp(&std_sec)) {
                        (Ordering::Greater, _) => std,
                        (Ordering::Equal, Ordering::Greater) => std,
                        (Ordering::Equal, _) => dst,
                        (_, _) => match (dst_end.cmp_t(&dst_t), dst_etime.cmp(&dst_sec)) {
                            (Ordering::Greater, _) => dst,
                            (Ordering::Equal, Ordering::Greater) => dst,
                            (Ordering::Equal, _) => std,
                            (_, _) => std,
                        },
                    }
                } else {
                    match (dst_end.cmp_t(&dst_t), dst_etime.cmp(&dst_sec)) {
                        (Ordering::Greater, _) => dst,
                        (Ordering::Equal, Ordering::Greater) => dst,
                        (Ordering::Equal, _) => std,
                        (_, _) => match (dst_start.cmp_t(&std_t), dst_stime.cmp(&std_sec)) {
                            (Ordering::Greater, _) => std,
                            (Ordering::Equal, Ordering::Greater) => std,
                            (Ordering::Equal, _) => dst,
                            (_, _) => dst,
                        }
                    }
                }
            }
        }
    }
}

/// A precise point in time along associated to a `Timezone`.
///
/// The `Datetime` cannot be created on its own as it depends on
/// a `Timezone`. `hourglass` does not expose a naive flavor of Datetime.
/// To build a `Datetime`, instanciate a `Timezone` first and call
/// the desired method.
///
/// ```rust
/// let paris = hourglass::Timezone::new("Europe/Paris").unwrap();
/// let midnight_in_paris = paris.datetime(2015, 12, 25, 0, 0, 0, 0).unwrap();
///
/// let utc = hourglass::Timezone::utc();
/// let t = midnight_in_paris.project(&utc);
///
/// assert_eq!(t.date(), (2015, 12, 24));
/// assert_eq!(t.time(), (23, 0, 0, 0));
/// ```
#[derive(Clone, Copy)]
pub struct Datetime<'a> {
    /// The associated timezone.
    tz: &'a Timezone,
    /// The offset since Unix Epoch. This is *not* the number
    /// of SI seconds since Unix Epoch because of leap seconds.
    sec: i64,
    /// The nanosecond for the current second.
    nano: i32,
    /// Remove ambiguous datetime on leap. When stamp
    /// corresponds to a leap second, use this field
    /// to know whether the `Datetime` corresponds to
    /// the 59th or the 60th second.
    is_60th_sec: bool,
}

impl<'a> Datetime<'a> {
    /// Project the current `Datetime` in another `Timezone`.
    pub fn project<'b>(&self, tz: &'b Timezone) -> Datetime<'b> {
        Datetime {
            tz: tz,
            sec: self.sec,
            nano: self.nano,
            is_60th_sec: self.is_60th_sec,
        }
    }

    /// Return the tm in the associated `Timezone`.
    fn tm(&self) -> libc::tm {
        let offset = self.tz.offset(self.sec).off;
        let mut tm = stamp_to_tm(self.sec + offset as i64 +
                                 if self.is_60th_sec {
            -1
        } else {
            0
        });
        if self.is_60th_sec {
            tm.tm_sec = 60;
        }
        tm
    }

    /// Convert a tm to date.
    fn tm_to_date(tm: &libc::tm) -> (i32, i32, i32) {
        (tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday)
    }

    /// Convert a tm to time.
    fn tm_to_time(tm: &libc::tm) -> (i32, i32, i32) {
        (tm.tm_hour, tm.tm_min, tm.tm_sec)
    }

    /// Convert a tm to weekday string.
    fn tm_to_weekday(tm: &libc::tm) -> &'static str {
        match tm.tm_wday {
            0 => "Sunday",
            1 => "Monday",
            2 => "Tuesday",
            3 => "Wednesday",
            4 => "Thursday",
            5 => "Friday",
            6 => "Saturday",
            _ => unreachable!(),
        }
    }

    /// Convert a tm to a month string.
    fn tm_to_month(tm: &libc::tm) -> &'static str {
        match tm.tm_mon {
            0 => "January",
            1 => "February",
            2 => "March",
            3 => "April",
            4 => "May",
            5 => "June",
            6 => "July",
            7 => "August",
            8 => "September",
            9 => "October",
            10 => "November",
            11 => "December",
            _ => unreachable!(),
        }
    }

    /// Return the date component of the `Datetime` expressed
    /// in the associated `Timezone`. The tuple holds the
    /// year, month and day in this order.
    pub fn date(&self) -> (i32, i32, i32) {
        let tm = self.tm();
        Self::tm_to_date(&tm)
    }

    /// Return the time component of the `Datetime` expressed
    /// in the associated `Timezone`. The tuple holds
    /// the hour, minute, second and nanosecond in this order.
    pub fn time(&self) -> (i32, i32, i32, i32) {
        let tm = self.tm();
        let (h, m, s) = Self::tm_to_time(&tm);
        (h, m, s, self.nano)
    }

    /// Return the unix timestamp. This is the number of unix seconds
    /// since 1970-01-01T00:00:00Z.
    pub fn unix(&self) -> i64 {
        self.sec
    }

    /// Format the `Datetime` according to the provided `format`.
    /// The following control characters are implemented:
    ///
    /// - `%%`: the '%' character
    /// - `%Y`: year (2006)
    /// - `%m`: month (01)
    /// - `%d`: day of the month (02)
    /// - `%e`: day of the month (2)
    /// - `%H`: hour (15)
    /// - `%M`: minute (04)
    /// - `%S`: second (05)
    /// - `%3`: millisecond (123)
    /// - `%6`: microsecond (123456)
    /// - `%9`: nanosecond (123456789)
    /// - `%x`: `UTC` offset (+02:00 or -05:00)
    /// - `%z`: `UTC` offset (+0200 or -0500)
    /// - `%Z`: timezone abbreviation (CET)
    /// - `%w`: weekday (1)
    /// - `%a`: abbreviated weekday name (Mon)
    /// - `%A`: full weekday name (Monday)
    /// - `%b`: abbreviated month name (Jan)
    /// - `%B`: full month name (January)
    /// - `%C`: century (20)
    ///
    /// Returns a `FmtError` if the format is invalid.
    pub fn format(&self, fmt: &str) -> Result<String, FmtError> {
        use std::fmt::Write;

        let mut out = String::with_capacity(2 * fmt.len());

        let tm = self.tm();
        let date = Self::tm_to_date(&tm);
        let time = Self::tm_to_time(&tm);
        let off = self.tz.offset(self.sec);

        let mut chars = fmt.chars();
        loop {
            match chars.next() {
                None => break,
                Some('%') => {
                    match chars.next() {
                        None => return Err(FmtError::UnexpectedEndOfString),
                        Some('%') => out.push('%'),
                        Some('Y') => write!(out, "{:04}", date.0).unwrap_or(()),
                        Some('m') => write!(out, "{:02}", date.1).unwrap_or(()),
                        Some('d') => write!(out, "{:02}", date.2).unwrap_or(()),
                        Some('e') => write!(out, "{}", date.2).unwrap_or(()),
                        Some('H') => write!(out, "{:02}", time.0).unwrap_or(()),
                        Some('M') => write!(out, "{:02}", time.1).unwrap_or(()),
                        Some('S') => write!(out, "{:02}", time.2).unwrap_or(()),
                        Some('3') => write!(out, "{:03}", self.nano / 1_000_000).unwrap_or(()),
                        Some('6') => write!(out, "{:06}", self.nano / 1_000).unwrap_or(()),
                        Some('9') => write!(out, "{:09}", self.nano).unwrap_or(()),
                        Some('x') => {
                            write!(out, "{:+03}:{:02}", off.off / 3600, off.off % 3600 / 60)
                                .unwrap_or(())
                        }
                        Some('z') => {
                            write!(out, "{:+03}{:02}", off.off / 3600, off.off % 3600 / 60)
                                .unwrap_or(())
                        }
                        Some('Z') => write!(out, "{}", off.abbr).unwrap_or(()),
                        Some('w') => write!(out, "{}", tm.tm_wday).unwrap_or(()),
                        Some('a') => {
                            write!(out, "{}", &Self::tm_to_weekday(&tm)[..3]).unwrap_or(())
                        }
                        Some('A') => write!(out, "{}", Self::tm_to_weekday(&tm)).unwrap_or(()),
                        Some('b') => write!(out, "{}", &Self::tm_to_month(&tm)[..3]).unwrap_or(()),
                        Some('B') => write!(out, "{}", Self::tm_to_month(&tm)).unwrap_or(()),
                        Some('C') => write!(out, "{}", date.0 / 100).unwrap_or(()),
                        Some(c) => return Err(FmtError::InvalidFormatter(c)),
                    }
                }
                Some(c) => out.push(c),
            }
        }

        Ok(out)
    }

    /// Format `Datetime` according to RFC 3339 format.
    pub fn rfc3339(&self) -> String {
        self.format("%Y-%m-%dT%H:%M:%S%x").unwrap()
    }

    /// Format `Datetime` according to RFC 2822 format.
    pub fn rfc2822(&self) -> String {
        self.format("%a, %e %b %Y %H:%M:%S %z").unwrap()
    }
}

impl<'a> PartialEq<Datetime<'a>> for Datetime<'a> {
    fn eq(&self, other: &Datetime) -> bool {
        self.cmp(&other) == Ordering::Equal
    }
}

impl<'a> Eq for Datetime<'a> {}

impl<'a> PartialOrd<Datetime<'a>> for Datetime<'a> {
    fn partial_cmp(&self, other: &Datetime) -> Option<Ordering> {
        let cmp_sec = self.sec.cmp(&other.sec);
        if let Ordering::Equal = cmp_sec {
            // Having the 60th sec tag means
            // that the time is Ordering::Less than
            // the other time.
            let cmp_leap = other.is_60th_sec.cmp(&self.is_60th_sec);
            if let Ordering::Equal = cmp_leap {
                Some(self.nano.cmp(&other.nano))
            } else {
                Some(cmp_leap)
            }
        } else {
            Some(cmp_sec)
        }
    }
}

impl<'a> Ord for Datetime<'a> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl<'a> Add<Deltatime> for Datetime<'a> {
    type Output = Datetime<'a>;
    fn add(mut self, rhs: Deltatime) -> Self::Output {
        match rhs.0 {
            Delta::Nanoseconds(nano) => {
                if nano < 0 {
                    let nano = -nano;
                    if self.nano as i64 >= nano {
                        self.nano -= nano as i32;
                        return self;
                    }

                    let nano = nano - self.nano as i64;
                    let sec = nano / 1_000_000_000 + 1;
                    let nano_left = 1_000_000_000 - (nano - (sec - 1) * 1_000_000_000);
                    let mut t = self + Deltatime(Delta::Seconds(-sec));
                    t.nano = nano_left as i32;
                    t
                } else {
                    let nano = nano + self.nano as i64;
                    if nano < 1_000_000_000 {
                        self.nano = nano as i32;
                        return self;
                    }

                    // Let's mentally empty the dt's nano counter. They will
                    // be added later. This trick is to avoid landing on a
                    // leap second when we add the remaining nano after the
                    // full seconds were added.
                    let sec = nano / 1_000_000_000;
                    let nano = nano - sec * 1_000_000_000;
                    let mut t = self + Deltatime(Delta::Seconds(sec));
                    t.nano = nano as i32;
                    t
                }
            }
            Delta::Seconds(mut sec) => {
                // TODO: version without loops ?
                if sec < 0 {
                    sec = -sec;
                    while sec != 0 {
                        match LEAP_SECONDS.binary_search(&self.sec) {
                            Err(0) => {
                                // We won't encounter any leap second.
                                self.sec -= sec;
                                return self;
                            }
                            Err(s) => {
                                let prev_leap = LEAP_SECONDS[s - 1];
                                let prev_leap_in_sec = self.sec - prev_leap;
                                if sec <= prev_leap_in_sec {
                                    // We're done before reaching the
                                    // previous leap second.
                                    self.sec -= sec;
                                    return self;
                                } else if sec == prev_leap_in_sec + 1 {
                                    // We've landed on the leap second.
                                    self.is_60th_sec = true;
                                    self.sec = prev_leap;
                                    return self;
                                } else {
                                    // We jump right before the leap second
                                    // while retaining 1 sec from the counter.
                                    self.sec = prev_leap - 1;
                                    sec -= prev_leap_in_sec + 2;
                                }
                            }
                            Ok(_) => {
                                // We start on an ambiguous unix timestamp.
                                if self.is_60th_sec {
                                    self.is_60th_sec = false;
                                    self.sec -= 1;
                                } else {
                                    self.is_60th_sec = true;
                                }
                                sec -= 1;
                            }
                        }
                    }
                    self
                } else {
                    while sec != 0 {
                        match LEAP_SECONDS.binary_search(&self.sec) {
                            Err(s) if s == LEAP_SECONDS.len() => {
                                // No leap seconds after current datetime.
                                // So we can safely add all the second and
                                // return the result.
                                self.sec += sec;
                                return self;
                            }
                            Err(s) => {
                                let next_leap = LEAP_SECONDS[s];
                                let next_leap_in_sec = next_leap - self.sec;
                                if sec < next_leap_in_sec {
                                    // We're done before even reaching the next
                                    // leap second.
                                    self.sec += sec;
                                    return self;
                                } else if sec == next_leap_in_sec {
                                    // We've landed on the leap second.
                                    self.sec = next_leap;
                                    self.is_60th_sec = true;
                                    return self;
                                } else {
                                    // Take into account the leap second
                                    // and countinue with whatever is left
                                    // of our second counter.
                                    self.sec = next_leap;
                                    sec -= next_leap_in_sec + 1;
                                }
                            }
                            Ok(_) => {
                                // We start on an ambiguous unix timestamp.
                                // If we know we're on leap second, just
                                // remove the leap marker and remove
                                // one second. Otherwise, just move one
                                // second. Either way, we just jump out of
                                // the ambiguous zone, without having our
                                // second counter < 0.
                                if self.is_60th_sec {
                                    self.is_60th_sec = false;
                                } else {
                                    self.sec += 1;
                                }
                                sec -= 1;
                            }
                        }
                    }
                    self
                }
            }
            Delta::Days(day) => {
                self.is_60th_sec = false;
                self.sec += day * 86400;
                self
            }
        }
    }
}

impl<'a> Sub<Deltatime> for Datetime<'a> {
    type Output = Datetime<'a>;
    fn sub(self, rhs: Deltatime) -> Self::Output {
        self + (-rhs)
    }
}

impl<'a> Sub<Datetime<'a>> for Datetime<'a> {
    type Output = Deltatime;
    fn sub(self, rhs: Datetime<'a>) -> Self::Output {
        if self < rhs {
            return -(rhs - self);
        }

        // rhs <= self
        let add_sec = match (LEAP_SECONDS.binary_search(&rhs.sec),
                             LEAP_SECONDS.binary_search(&self.sec)) {
            (Err(i), Err(j)) => (j - i) as i64,
            (Err(i), Ok(j)) => {
                (j - i) as i64 +
                if self.is_60th_sec {
                    0i64
                } else {
                    1i64
                }
            }
            (Ok(i), Err(j)) => {
                (j - i) as i64 +
                if rhs.is_60th_sec {
                    0i64
                } else {
                    -1i64
                }
            }
            (Ok(i), Ok(j)) => {
                (j - i) as i64 +
                if rhs.is_60th_sec {
                    0i64
                } else {
                    -1i64
                } +
                if self.is_60th_sec {
                    0i64
                } else {
                    1i64
                }
            }
        };
        Deltatime::nanoseconds((self.sec - rhs.sec + add_sec) * 1_000_000_000 +
                               (self.nano - rhs.nano) as i64)
    }
}

impl<'a> fmt::Debug for Datetime<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.rfc3339())
    }
}

/// Possible errors when creating a `Datetime`.
pub enum InputError {
    InvalidMonth,
    InvalidDay,
    InvalidHour,
    InvalidMinute,
    InvalidSecond,
    InvalidNano,
    InvalidLeapSecond,
    InvalidFormat,
}

impl fmt::Debug for InputError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use std::error::Error;
        write!(fmt, "{}", self.description())
    }
}

impl fmt::Display for InputError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use std::error::Error;
        write!(fmt, "{}", self.description())
    }
}

impl error::Error for InputError {
    fn description(&self) -> &str {
        match *self {
            InputError::InvalidMonth => "invalid month",
            InputError::InvalidDay => "invalid day",
            InputError::InvalidHour => "invalid hour",
            InputError::InvalidMinute => "invalid minute",
            InputError::InvalidSecond => "invalid second",
            InputError::InvalidNano => "invalid nanosecond",
            InputError::InvalidLeapSecond => "invalid leap second",
            InputError::InvalidFormat => "invalid format",
        }
    }
}

/// Possible errors when formatting a `Datetime`.
pub enum FmtError {
    UnexpectedEndOfString,
    InvalidFormatter(char),
}

impl fmt::Debug for FmtError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use std::error::Error;
        write!(fmt, "{}", self.description())
    }
}

impl fmt::Display for FmtError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use std::error::Error;
        write!(fmt, "{}", self.description())
    }
}

impl error::Error for FmtError {
    fn description(&self) -> &str {
        match *self {
            FmtError::UnexpectedEndOfString => "unexpected end of string",
            FmtError::InvalidFormatter(_) => "invalid formatter",
        }
    }
}

// FIXME: is reading /usr/share/zoneinfo/leap-seconds.list
// a better way to store the leap information?
const NTP_TO_UNIX: i64 = 2208988800;
const LEAP_SECONDS: &'static [i64] = &[2272060800 - NTP_TO_UNIX,
                                       2287785600 - NTP_TO_UNIX,
                                       2303683200 - NTP_TO_UNIX,
                                       2335219200 - NTP_TO_UNIX,
                                       2366755200 - NTP_TO_UNIX,
                                       2398291200 - NTP_TO_UNIX,
                                       2429913600 - NTP_TO_UNIX,
                                       2461449600 - NTP_TO_UNIX,
                                       2492985600 - NTP_TO_UNIX,
                                       2524521600 - NTP_TO_UNIX,
                                       2571782400 - NTP_TO_UNIX,
                                       2603318400 - NTP_TO_UNIX,
                                       2634854400 - NTP_TO_UNIX,
                                       2698012800 - NTP_TO_UNIX,
                                       2776982400 - NTP_TO_UNIX,
                                       2840140800 - NTP_TO_UNIX,
                                       2871676800 - NTP_TO_UNIX,
                                       2918937600 - NTP_TO_UNIX,
                                       2950473600 - NTP_TO_UNIX,
                                       2982009600 - NTP_TO_UNIX,
                                       3029443200 - NTP_TO_UNIX,
                                       3076704000 - NTP_TO_UNIX,
                                       3124137600 - NTP_TO_UNIX,
                                       3345062400 - NTP_TO_UNIX,
                                       3439756800 - NTP_TO_UNIX,
                                       3550089600 - NTP_TO_UNIX,
                                       3644697600 - NTP_TO_UNIX];

/// A delta of time used in `Datetime` arithmetic.
///
/// This represents a duration in time and can be used to shift `Datetime`
/// by a specified amount of time or as a result of comparing two
/// `Datetime`. Different types of `Deltatime` can be created and
/// each of those types affects `Datetime` differently. For example,
/// `Deltatime::seconds(86400)` is different from `Deltatime::days(1)`
/// because a `Deltatime` is dependant of the `Datetime` it applies to.
///
/// # Example
///
/// ```rust
/// let utc = hourglass::Timezone::utc();
/// let t = utc.datetime(2015, 6, 30, 0, 0, 0, 0).unwrap();
///
/// let add_86400_secs = t + hourglass::Deltatime::seconds(86400);
///
/// assert_eq!(add_86400_secs.date(), (2015, 6, 30));
/// assert_eq!(add_86400_secs.time(), (23, 59, 60, 0));
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Deltatime(Delta);

#[derive(Clone, Copy, Debug)]
enum Delta {
    Nanoseconds(i64),
    Seconds(i64),
    Days(i64),
}

impl Deltatime {
    /// Create a delta of `n` nanoseconds. Possible leap seconds are
    /// accounted for.
    pub fn nanoseconds(n: i64) -> Self {
        Deltatime(Delta::Nanoseconds(n))
    }

    /// Create a delta of `n` microseconds. Possible leap seconds are
    /// accounted for.
    pub fn microseconds(n: i64) -> Self {
        Deltatime(Delta::Nanoseconds(n * 1_000))
    }

    /// Create a delta of `n` milliseconds. Possible leap seconds are
    /// accounted for.
    pub fn milliseconds(n: i64) -> Self {
        Deltatime(Delta::Nanoseconds(n * 1_000_000))
    }

    /// Create a delta of `n` seconds. Possible leap seconds are
    /// accounted for.
    pub fn seconds(n: i64) -> Self {
        Deltatime(Delta::Seconds(n))
    }

    /// Create a delta of `n` minutes. Possible leap seconds are
    /// accounted for.
    pub fn minutes(n: i64) -> Self {
        Deltatime(Delta::Seconds(n * 60))
    }

    /// Create a delta of `n` hours. Possible leap seconds are accounted
    /// for.
    pub fn hours(n: i64) -> Self {
        Deltatime(Delta::Seconds(n * 3600))
    }

    /// Create a delta of `n` days. The time part of the shifted
    /// `Datetime` is not affected. This is a logical day, therefore,
    /// leap seconds are ignored.
    pub fn days(n: i64) -> Self {
        Deltatime(Delta::Days(n))
    }

    /// Returns the total number of nanoseconds contained in this delta.
    /// If the delta is created from `Deltatime::days`, the number
    /// of nanoseconds in a day is assumed to be `86400e9`.
    pub fn as_nanoseconds(&self) -> i64 {
        match self.0 {
            Delta::Nanoseconds(n) => n,
            Delta::Seconds(n) => n * 1_000_000_000,
            Delta::Days(n) => n * 86400 * 1_000_000_000,
        }
    }

    /// Returns the total number of microseconds contained in this delta.
    /// If the delta is created from `Deltatime::days`, the number
    /// of microseconds in a day is assumed to be `86400e6`.
    pub fn as_microseconds(&self) -> i64 {
        self.as_nanoseconds() / 1_000
    }

    /// Returns the total number of milliseconds contained in this delta.
    /// If the delta is created from `Deltatime::days`, the number
    /// of milliseconds in a day is assumed to be `86400e3`.
    pub fn as_milliseconds(&self) -> i64 {
        self.as_nanoseconds() / 1_000_000
    }

    /// Returns the total number of seconds contained in this delta.
    /// If the delta is created from `Deltatime::days`, the number
    /// of seconds in a day is assumed to be `86400`.
    pub fn as_seconds(&self) -> i64 {
        match self.0 {
            Delta::Nanoseconds(n) => n / 1_000_000_000,
            Delta::Seconds(n) => n,
            Delta::Days(n) => n * 86400,
        }
    }

    /// Returns the total number of minutes contained in this delta.
    pub fn as_minutes(&self) -> i64 {
        self.as_seconds() / 60
    }

    /// Returns the total number of hours contained in this delta.
    pub fn as_hours(&self) -> i64 {
        self.as_seconds() / 3_600
    }

    /// Returns the total number of days contained in this delta.
    pub fn as_days(&self) -> i64 {
        match self.0 {
            Delta::Nanoseconds(n) => n / 1_000_000_000 / 86400,
            Delta::Seconds(n) => n / 86400,
            Delta::Days(n) => n,
        }
    }

    /// Compare two `Deltatime`.
    fn cmp_delta(&self, rhs: &Deltatime) -> Ordering {
        self.as_nanoseconds().cmp(&rhs.as_nanoseconds())
    }
}

impl PartialEq<Deltatime> for Deltatime {
    fn eq(&self, other: &Deltatime) -> bool {
        self.cmp_delta(&other) == Ordering::Equal
    }
}

impl Eq for Deltatime {}

impl PartialOrd<Deltatime> for Deltatime {
    fn partial_cmp(&self, other: &Deltatime) -> Option<Ordering> {
        Some(self.cmp_delta(&other))
    }
}

impl Ord for Deltatime {
    fn cmp(&self, other: &Self) -> Ordering {
        self.cmp_delta(other)
    }
}

impl Neg for Deltatime {
    type Output = Deltatime;
    fn neg(self) -> Self::Output {
        Deltatime(match self.0 {
            Delta::Nanoseconds(n) => Delta::Nanoseconds(-n),
            Delta::Seconds(n) => Delta::Seconds(-n),
            Delta::Days(n) => Delta::Days(-n),
        })
    }
}

// C bindings & conv helpers

fn stamp_to_tm(sec: i64) -> libc::tm {
    let mut tm = libc::tm {
        tm_sec: 0,
        tm_min: 0,
        tm_hour: 0,
        tm_mday: 0,
        tm_mon: 0,
        tm_year: 0,
        tm_wday: 0,
        tm_yday: 0,
        tm_isdst: 0,
        // Unused
        tm_gmtoff: 0,
        tm_zone: ptr::null(),
    };
    unsafe { libc::gmtime_r(&sec, &mut tm) };
    tm
}

fn tm_to_stamp(tm: &libc::tm) -> i64 {
    // Thanks to Eric S. Raymond for releasing this function into the
    // public domain. I've tweaked it a bit but the algorithm's still
    // the same. libc's mktime function interprets the input tm as local
    // time, which is not what we want; timegm is not portable. The original
    // version allowed month overflow; I removed this behavior.
    const CUM_DAYS: &'static [i64; 12] = &[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];

    let year = 1900 + tm.tm_year as i64;
    let mut result = (year - 1970) * 365 + CUM_DAYS[tm.tm_mon as usize];
    result += (year - 1968) / 4;
    result -= (year - 1900) / 100;
    result += (year - 1600) / 400;
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) && tm.tm_mon < 2 {
        result -= 1;
    }
    result += tm.tm_mday as i64 - 1;
    result *= 24;
    result += tm.tm_hour as i64;
    result *= 60;
    result += tm.tm_min as i64;
    result *= 60;
    result += tm.tm_sec as i64;

    result
}


extern "C" {
    fn strptime(s: *const libc::c_char,
                fmt: *const libc::c_char,
                tm: *mut libc::tm)
                -> *const libc::c_char;
}

#[cfg(test)]
mod test {
    use super::*;
    use super::libc;
    use super::{GenericDay, Type, TransRule};
    use super::{tm_to_stamp, stamp_to_tm};

    #[test]
    fn test_datetime() {
        let utc = Timezone::utc();
        for &((y, m, d, h, mi, s, n), stamp) in &[((1970, 1, 1, 0, 0, 0, 0), 0),
                                                  ((1970, 1, 1, 1, 0, 0, 0), 3600),
                                                  ((2016, 1, 1, 0, 0, 0, 0), 1451606400)] {
            let dt = utc.datetime(y, m, d, h, mi, s, n).unwrap();
            assert_eq!(dt.sec, stamp);
            assert_eq!(dt.is_60th_sec, false);
        }
    }

    #[test]
    fn test_leap_second() {
        let utc = Timezone::utc();
        let t = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t_leap = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        assert_eq!(t.is_60th_sec, false);
        assert_eq!(t_leap.is_60th_sec, true);
        assert_eq!(t.sec + 1, t_leap.sec);
        assert_eq!(t_leap.format("%S").unwrap(), "60");
        assert_eq!(t_leap.date(), (2015, 6, 30));
        assert_eq!(t_leap.time(), (23, 59, 60, 0));
        assert_eq!(t_leap.unix(), 1435708800);
        assert!(t_leap != t);
    }

    #[test]
    fn test_tz_projection() {
        let utc = Timezone::utc();
        let seoul = Timezone::new("Asia/Seoul").unwrap();
        let new_york = Timezone::new("America/New_York").unwrap();

        let t = utc.datetime(2016, 1, 15, 20, 0, 0, 0).unwrap();
        let t_seoul = t.project(&seoul);
        let t_ny = t.project(&new_york);

        assert_eq!(t.date(), (2016, 1, 15));
        assert_eq!(t.time(), (20, 0, 0, 0));
        assert_eq!(t_seoul, t);
        assert_eq!(t_seoul.date(), (2016, 1, 16));
        assert_eq!(t_seoul.time(), (5, 0, 0, 0));
        assert_eq!(t_ny, t);
        assert_eq!(t_ny.date(), (2016, 1, 15));
        assert_eq!(t_ny.time(), (15, 0, 0, 0));
    }

    #[test]
    fn test_format() {
        let paris = Timezone::new("Europe/Paris").unwrap();
        let t = paris.datetime(2006, 1, 2, 15, 4, 5, 123_456_789).unwrap();

        assert_eq!(t.format("%Y-%m-%dT%H:%M:%S").unwrap(),
                   "2006-01-02T15:04:05");
        assert_eq!(t.format("%3").unwrap(), "123");
        assert_eq!(t.format("%6").unwrap(), "123456");
        assert_eq!(t.format("%9").unwrap(), "123456789");
        assert_eq!(t.format("%z").unwrap(), "+0100");
        assert_eq!(t.format("%Z").unwrap(), "CET");
        assert_eq!(t.format("%w").unwrap(), "1");
        assert_eq!(t.format("%a").unwrap(), "Mon");
        assert_eq!(t.format("%A").unwrap(), "Monday");
        assert_eq!(t.format("%b").unwrap(), "Jan");
        assert_eq!(t.format("%B").unwrap(), "January");
        assert_eq!(t.format("%C").unwrap(), "20");
        assert_eq!(t.rfc3339(), "2006-01-02T15:04:05+01:00");
        assert_eq!(t.rfc2822(), "Mon, 2 Jan 2006 15:04:05 +0100");
    }

    #[test]
    fn test_parse() {
        let paris = Timezone::new("Europe/Paris").unwrap();
        let utc = Timezone::utc();

        let t = paris.parse("2006-01-02T15:04:05", "%Y-%m-%dT%H:%M:%S").unwrap();
        let t_utc = t.project(&utc);
        assert_eq!(t_utc.date(), (2006, 1, 2));
        assert_eq!(t_utc.time(), (14, 4, 5, 0));
    }

    #[test]
    fn test_generic_day() {
        fn t(y: i32, m: i32, d: i32) -> libc::tm {
            let tm = libc::tm {
                tm_sec: 0,
                tm_min: 0,
                tm_hour: 0,
                tm_mday: d,
                tm_mon: m - 1,
                tm_year: y - 1900,
                tm_wday: 0,
                tm_yday: 0,
                tm_isdst: 0,
                tm_gmtoff: 0,
                tm_zone: ::std::ptr::null(),
            };
            // Make libc compute tm_wday.
            let stamp = tm_to_stamp(&tm);
            stamp_to_tm(stamp)
        }

        for &(ref gen, ref tm) in &[(GenericDay::Julian1 { jday: 59 }, t(2016, 2, 28)),
                                    (GenericDay::Julian1 { jday: 60 }, t(2016, 3, 1)),
                                    (GenericDay::Julian1 { jday: 365 }, t(2016, 12, 31)),
                                    (GenericDay::Julian1 { jday: 59 }, t(2015, 2, 28)),
                                    (GenericDay::Julian1 { jday: 60 }, t(2015, 3, 1)),
                                    (GenericDay::Julian1 { jday: 365 }, t(2015, 12, 31)),

                                    (GenericDay::Julian0 { jday: 58 }, t(2016, 2, 28)),
                                    (GenericDay::Julian0 { jday: 59 }, t(2016, 2, 29)),
                                    (GenericDay::Julian0 { jday: 60 }, t(2016, 3, 1)),
                                    (GenericDay::Julian0 { jday: 365 }, t(2016, 12, 31)),
                                    (GenericDay::Julian0 { jday: 58 }, t(2015, 2, 28)),
                                    (GenericDay::Julian0 { jday: 59 }, t(2015, 3, 1)),
                                    (GenericDay::Julian0 { jday: 364 }, t(2015, 12, 31)),

                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 1,
                                        wday: 0,
                                    },
                                     t(2016, 1, 3)),
                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 2,
                                        wday: 0,
                                    },
                                     t(2016, 1, 10)),
                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 5,
                                        wday: 0,
                                    },
                                     t(2016, 1, 31)),
                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 1,
                                        wday: 5,
                                    },
                                     t(2016, 1, 1)),
                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 5,
                                        wday: 4,
                                    },
                                     t(2016, 1, 28)),
                                    (GenericDay::MWDRule {
                                        month: 1,
                                        week: 4,
                                        wday: 4,
                                    },
                                     t(2016, 1, 28))] {
            if gen != tm {
                panic!("{:?} != {:04}-{:02}-{:02}",
                       gen,
                       tm.tm_year,
                       tm.tm_mon,
                       tm.tm_mday);
            }
        }
    }

    #[test]
    fn test_trans_rule() {
        fn s(y: i32, mo: i32, d: i32, h: i32, m: i32, s: i32) -> i64 {
            let tm = libc::tm {
                tm_sec: s,
                tm_min: m,
                tm_hour: h,
                tm_mday: d,
                tm_mon: mo - 1,
                tm_year: y - 1900,
                tm_wday: 0,
                tm_yday: 0,
                tm_isdst: 0,
                tm_gmtoff: 0,
                tm_zone: ::std::ptr::null(),
            };
            tm_to_stamp(&tm)
        }

        // Fixed offset rule. easy.
        let kst = Type {
            off: 9 * 3600,
            is_dst: false,
            abbr: "KST".to_owned(),
        };
        let seoul_rule = TransRule::Fixed(kst.clone());
        assert_eq!(seoul_rule.get_type(s(2016, 1, 1, 0, 0, 0)), &kst);
        assert_eq!(seoul_rule.get_type(s(2016, 7, 1, 0, 0, 0)), &kst);
        assert_eq!(seoul_rule.get_type(s(2016, 10, 1, 0, 0, 0)), &kst);

        // Alternate offset rule.
        // CET-1CEST,M3.5.0,M10.5.0/3
        let cet = Type {
            off: 1 * 3600,
            is_dst: false,
            abbr: "CET".to_owned(),
        };
        let cest = Type {
            off: 2 * 3600,
            is_dst: true,
            abbr: "CEST".to_owned(),
        };
        let paris_rule = TransRule::Alternate {
            dst_start: GenericDay::MWDRule {
                month: 3,
                week: 5,
                wday: 0,
            },
            dst_stime: 2 * 3600, // From std to dst at 2AM std tz
            dst_end: GenericDay::MWDRule {
                month: 10,
                week: 5,
                wday: 0,
            },
            dst_etime: 3 * 3600, // From dst to std at 3AM dst tz!
            std: cet.clone(),
            dst: cest.clone(),
        };
        assert_eq!(paris_rule.get_type(s(2016, 1, 1, 0, 0, 0)), &cet);
        assert_eq!(paris_rule.get_type(s(2016, 3, 27, 0, 59, 59)), &cet);
        assert_eq!(paris_rule.get_type(s(2016, 3, 27, 1, 0, 0)), &cest);
        assert_eq!(paris_rule.get_type(s(2016, 10, 30, 0, 59, 59)), &cest);
        assert_eq!(paris_rule.get_type(s(2016, 10, 30, 1, 0, 0)), &cet);
        assert_eq!(paris_rule.get_type(s(2016, 12, 31, 0, 0, 0)), &cet);

        // Alternate offset rule where dst is still
        // in use at the end of the year and stops at
        // the beginning of the year.
        // AEST-10AEDT,M10.1.0,M4.1.0/3
        let aest = Type {
            off: 10 * 3600,
            is_dst: false,
            abbr: "AEST".to_owned(),
        };
        let aedt = Type {
            off: 11 * 3600,
            is_dst: true,
            abbr: "AEDT".to_owned(),
        };
        let sydney_rule = TransRule::Alternate {
            dst_start: GenericDay::MWDRule {
                month: 10,
                week: 1,
                wday: 0,
            },
            dst_stime: 2 * 3600,
            dst_end: GenericDay::MWDRule {
                month: 4,
                week: 1,
                wday: 0,
            },
            dst_etime: 3 * 3600,
            std: aest.clone(),
            dst: aedt.clone(),
        };
        assert_eq!(sydney_rule.get_type(s(2016, 1, 1, 0, 0, 0)), &aedt);
        assert_eq!(sydney_rule.get_type(s(2016, 4, 2, 15, 59, 59)), &aedt);
        assert_eq!(sydney_rule.get_type(s(2016, 4, 2, 16, 0, 0)), &aest);
        assert_eq!(sydney_rule.get_type(s(2016, 10, 1, 15, 59, 59)), &aest);
        assert_eq!(sydney_rule.get_type(s(2016, 10, 1, 16, 0, 0)), &aedt);
        assert_eq!(sydney_rule.get_type(s(2016, 12, 31, 0, 0, 0)), &aedt);

        // Alternative offset with negative UTC offset
        // EST5EDT,M3.2.0,M11.1.0
        let est = Type {
            off: -5 * 3600,
            is_dst: false,
            abbr: "EST".to_owned(),
        };
        let edt = Type {
            off: -4 * 3600,
            is_dst: true,
            abbr: "EDT".to_owned(),
        };
        let newyork_rule = TransRule::Alternate {
            dst_start: GenericDay::MWDRule {
                month: 3,
                week: 2,
                wday: 0,
            },
            dst_stime: 2 * 3600,
            dst_end: GenericDay::MWDRule {
                month: 11,
                week: 1,
                wday: 0,
            },
            dst_etime: 2 * 3600,
            std: est.clone(),
            dst: edt.clone(),
        };
        assert_eq!(newyork_rule.get_type(s(2016, 1, 1, 0, 0, 0)), &est);
        assert_eq!(newyork_rule.get_type(s(2016, 3, 13, 6, 59, 59)), &est);
        assert_eq!(newyork_rule.get_type(s(2016, 3, 13, 7, 0, 0)), &edt);
        assert_eq!(newyork_rule.get_type(s(2016, 11, 6, 5, 59, 59)), &edt);
        assert_eq!(newyork_rule.get_type(s(2016, 11, 6, 6, 0, 0)), &est);
        assert_eq!(newyork_rule.get_type(s(2016, 12, 31, 0, 0, 0)), &est);
    }

    #[test]
    fn test_add_deltatime() {
        let utc = Timezone::utc();

        // nano
        let t = utc.datetime(2015, 6, 30, 23, 59, 59, 999_999_999).unwrap();
        let t = t + Deltatime::nanoseconds(2);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 1));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 1).unwrap();
        let t = t + Deltatime::nanoseconds(-2);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 59, 999_999_999));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 200_000_000).unwrap();
        let t = t + Deltatime::nanoseconds(-300_000_000);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 59, 900_000_000));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 1).unwrap();
        let t = t + Deltatime::nanoseconds(-1_000_000_002);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 58, 999_999_999));

        // second regular -> leap
        let t = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t = t + Deltatime::seconds(1);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 0));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::seconds(-1);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 59, 0));

        // second leap -> regular
        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::seconds(1);
        assert_eq!(t.date(), (2015, 7, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::seconds(-1);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 0));

        // second regular -> regular
        let t = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t = t + Deltatime::seconds(2);
        assert_eq!(t.date(), (2015, 7, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::seconds(-2);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 59, 0));

        let t = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::seconds(1);
        assert_eq!(t.date(), (2015, 7, 1));
        assert_eq!(t.time(), (0, 0, 1, 0));

        let t = utc.datetime(2015, 7, 1, 0, 0, 1, 0).unwrap();
        let t = t + Deltatime::seconds(-1);
        assert_eq!(t.date(), (2015, 7, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t = t + Deltatime::seconds(3);
        assert_eq!(t.date(), (2015, 7, 1));
        assert_eq!(t.time(), (0, 0, 1, 0));

        let t = utc.datetime(2015, 7, 1, 0, 0, 1, 0).unwrap();
        let t = t + Deltatime::seconds(-3);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 59, 0));

        let t = utc.datetime(2012, 1, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::seconds(126230402); // 4 years, 2 leaps
        assert_eq!(t.date(), (2016, 1, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2016, 1, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::seconds(-126230402);
        assert_eq!(t.date(), (2012, 1, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        // second leap -> leap
        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::seconds(0);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 0));

        let t = utc.datetime(2012, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::seconds(94608001);
        assert_eq!(t.date(), (2015, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 0));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::seconds(-94608001);
        assert_eq!(t.date(), (2012, 6, 30));
        assert_eq!(t.time(), (23, 59, 60, 0));

        // days
        let t = utc.datetime(2016, 2, 29, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::days(1);
        assert_eq!(t.date(), (2016, 3, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2016, 3, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::days(-1);
        assert_eq!(t.date(), (2016, 2, 29));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2016, 1, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::days(366);
        assert_eq!(t.date(), (2017, 1, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2017, 1, 1, 0, 0, 0, 0).unwrap();
        let t = t + Deltatime::days(-366);
        assert_eq!(t.date(), (2016, 1, 1));
        assert_eq!(t.time(), (0, 0, 0, 0));

        let t = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t = t + Deltatime::days(1);
        assert_eq!(t.date(), (2015, 7, 2));
        assert_eq!(t.time(), (0, 0, 0, 0));
    }

    #[test]
    fn test_delta_conversion() {
        let d = Deltatime::nanoseconds(1);
        assert_eq!(d.as_nanoseconds(), 1);
        assert_eq!(d.as_microseconds(), 0);
        assert_eq!(d.as_milliseconds(), 0);
        assert_eq!(d.as_seconds(), 0);
        assert_eq!(d.as_minutes(), 0);
        assert_eq!(d.as_hours(), 0);
        assert_eq!(d.as_days(), 0);

        let d = Deltatime::seconds(1);
        assert_eq!(d.as_nanoseconds(), 1_000_000_000);
        assert_eq!(d.as_microseconds(), 1_000_000);
        assert_eq!(d.as_milliseconds(), 1_000);
        assert_eq!(d.as_seconds(), 1);
        assert_eq!(d.as_minutes(), 0);
        assert_eq!(d.as_hours(), 0);
        assert_eq!(d.as_days(), 0);

        let d = Deltatime::days(1);
        assert_eq!(d.as_nanoseconds(), 1_000_000_000 * 86400);
        assert_eq!(d.as_microseconds(), 1_000_000 * 86400);
        assert_eq!(d.as_milliseconds(), 1_000 * 86400);
        assert_eq!(d.as_seconds(), 1 * 86400);
        assert_eq!(d.as_minutes(), 1440);
        assert_eq!(d.as_hours(), 24);
        assert_eq!(d.as_days(), 1);
    }

    #[test]
    fn test_cmp_datetimes() {
        let utc = Timezone::utc();
        let t0 = utc.datetime(2015, 1, 1, 0, 0, 0, 0).unwrap();
        let t1 = utc.datetime(2015, 1, 1, 0, 0, 0, 1).unwrap();
        assert!(t0 != t1);
        assert!(t0 < t1);
        assert!(t0 <= t1);

        let t0 = utc.datetime(2015, 1, 1, 0, 0, 0, 0).unwrap();
        let t1 = utc.datetime(2015, 1, 1, 0, 0, 1, 0).unwrap();
        assert!(t0 < t1);

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 60, 1).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        assert!(t0 < t1);
    }

    #[test]
    fn test_sub_datetimes() {
        let utc = Timezone::utc();
        let t0 = utc.datetime(2015, 1, 1, 0, 0, 0, 0).unwrap();
        let t1 = utc.datetime(2015, 1, 2, 0, 0, 0, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::days(1));
        assert_eq!(t0 - t1, Deltatime::days(-1));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 1, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(3));
        assert_eq!(t0 - t1, Deltatime::seconds(-3));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t1 = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(1));
        assert_eq!(t0 - t1, Deltatime::seconds(-1));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 59, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(2));
        assert_eq!(t0 - t1, Deltatime::seconds(-2));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 1, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(2));
        assert_eq!(t0 - t1, Deltatime::seconds(-2));

        let t0 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 1, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(1));
        assert_eq!(t0 - t1, Deltatime::seconds(-1));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(1));
        assert_eq!(t0 - t1, Deltatime::seconds(-1));

        let t0 = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        let t1 = utc.datetime(2015, 6, 30, 23, 59, 60, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(0));
        assert_eq!(t0 - t1, Deltatime::seconds(0));

        let t0 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        let t1 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
        assert_eq!(t1 - t0, Deltatime::seconds(0));
        assert_eq!(t0 - t1, Deltatime::seconds(0));
    }
}