httpdate/
lib.rs

1//! Date and time utils for HTTP.
2//!
3//! Multiple HTTP header fields store timestamps.
4//! For example a response created on May 15, 2015 may contain the header
5//! `Date: Fri, 15 May 2015 15:34:21 GMT`. Since the timestamp does not
6//! contain any timezone or leap second information it is equvivalent to
7//! writing 1431696861 Unix time. Rust’s `SystemTime` is used to store
8//! these timestamps.
9//!
10//! This crate provides two public functions:
11//!
12//! * `parse_http_date` to parse a HTTP datetime string to a system time
13//! * `fmt_http_date` to format a system time to a IMF-fixdate
14//!
15//! In addition it exposes the `HttpDate` type that can be used to parse
16//! and format timestamps. Convert a sytem time to `HttpDate` and vice versa.
17//! The `HttpType` (8 bytes) is smaller than `SystemTime` (16 bytes) and
18//! using the display impl avoids a temporary allocation.
19#![forbid(unsafe_code)]
20
21use std::error;
22use std::fmt::{self, Display, Formatter};
23use std::io;
24use std::time::SystemTime;
25
26pub use date::HttpDate;
27
28mod date;
29
30/// An opaque error type for all parsing errors.
31#[derive(Debug)]
32pub struct Error(());
33
34impl error::Error for Error {}
35
36impl Display for Error {
37    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
38        f.write_str("string contains no or an invalid date")
39    }
40}
41
42impl From<Error> for io::Error {
43    fn from(e: Error) -> io::Error {
44        io::Error::new(io::ErrorKind::Other, e)
45    }
46}
47
48/// Parse a date from an HTTP header field.
49///
50/// Supports the preferred IMF-fixdate and the legacy RFC 805 and
51/// ascdate formats. Two digit years are mapped to dates between
52/// 1970 and 2069.
53pub fn parse_http_date(s: &str) -> Result<SystemTime, Error> {
54    s.parse::<HttpDate>().map(|d| d.into())
55}
56
57/// Format a date to be used in a HTTP header field.
58///
59/// Dates are formatted as IMF-fixdate: `Fri, 15 May 2015 15:34:21 GMT`.
60pub fn fmt_http_date(d: SystemTime) -> String {
61    format!("{}", HttpDate::from(d))
62}
63
64#[cfg(test)]
65mod tests {
66    use std::str;
67    use std::time::{Duration, UNIX_EPOCH};
68
69    use super::{fmt_http_date, parse_http_date, HttpDate};
70
71    #[test]
72    fn test_rfc_example() {
73        let d = UNIX_EPOCH + Duration::from_secs(784111777);
74        assert_eq!(
75            d,
76            parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT").expect("#1")
77        );
78        assert_eq!(
79            d,
80            parse_http_date("Sunday, 06-Nov-94 08:49:37 GMT").expect("#2")
81        );
82        assert_eq!(d, parse_http_date("Sun Nov  6 08:49:37 1994").expect("#3"));
83    }
84
85    #[test]
86    fn test2() {
87        let d = UNIX_EPOCH + Duration::from_secs(1475419451);
88        assert_eq!(
89            d,
90            parse_http_date("Sun, 02 Oct 2016 14:44:11 GMT").expect("#1")
91        );
92        assert!(parse_http_date("Sun Nov 10 08:00:00 1000").is_err());
93        assert!(parse_http_date("Sun Nov 10 08*00:00 2000").is_err());
94        assert!(parse_http_date("Sunday, 06-Nov-94 08+49:37 GMT").is_err());
95    }
96
97    #[test]
98    fn test3() {
99        let mut d = UNIX_EPOCH;
100        assert_eq!(d, parse_http_date("Thu, 01 Jan 1970 00:00:00 GMT").unwrap());
101        d += Duration::from_secs(3600);
102        assert_eq!(d, parse_http_date("Thu, 01 Jan 1970 01:00:00 GMT").unwrap());
103        d += Duration::from_secs(86400);
104        assert_eq!(d, parse_http_date("Fri, 02 Jan 1970 01:00:00 GMT").unwrap());
105        d += Duration::from_secs(2592000);
106        assert_eq!(d, parse_http_date("Sun, 01 Feb 1970 01:00:00 GMT").unwrap());
107        d += Duration::from_secs(2592000);
108        assert_eq!(d, parse_http_date("Tue, 03 Mar 1970 01:00:00 GMT").unwrap());
109        d += Duration::from_secs(31536005);
110        assert_eq!(d, parse_http_date("Wed, 03 Mar 1971 01:00:05 GMT").unwrap());
111        d += Duration::from_secs(15552000);
112        assert_eq!(d, parse_http_date("Mon, 30 Aug 1971 01:00:05 GMT").unwrap());
113        d += Duration::from_secs(6048000);
114        assert_eq!(d, parse_http_date("Mon, 08 Nov 1971 01:00:05 GMT").unwrap());
115        d += Duration::from_secs(864000000);
116        assert_eq!(d, parse_http_date("Fri, 26 Mar 1999 01:00:05 GMT").unwrap());
117    }
118
119    #[test]
120    fn test_fmt() {
121        let d = UNIX_EPOCH;
122        assert_eq!(fmt_http_date(d), "Thu, 01 Jan 1970 00:00:00 GMT");
123        let d = UNIX_EPOCH + Duration::from_secs(1475419451);
124        assert_eq!(fmt_http_date(d), "Sun, 02 Oct 2016 14:44:11 GMT");
125    }
126
127    #[allow(dead_code)]
128    fn testcase(data: &[u8]) {
129        if let Ok(s) = str::from_utf8(data) {
130            println!("{:?}", s);
131            if let Ok(d) = parse_http_date(s) {
132                let o = fmt_http_date(d);
133                assert!(!o.is_empty());
134            }
135        }
136    }
137
138    #[test]
139    fn size_of() {
140        assert_eq!(::std::mem::size_of::<HttpDate>(), 8);
141    }
142
143    #[test]
144    fn test_date_comparison() {
145        let a = UNIX_EPOCH + Duration::from_secs(784111777);
146        let b = a + Duration::from_secs(30);
147        assert!(a < b);
148        let a_date: HttpDate = a.into();
149        let b_date: HttpDate = b.into();
150        assert!(a_date < b_date);
151        assert_eq!(a_date.cmp(&b_date), ::std::cmp::Ordering::Less)
152    }
153
154    #[test]
155    fn test_parse_bad_date() {
156        // 1994-11-07 is actually a Monday
157        let parsed = "Sun, 07 Nov 1994 08:48:37 GMT".parse::<HttpDate>();
158        assert!(parsed.is_err())
159    }
160}