headers/util/
http_date.rs

1use std::fmt;
2use std::str::FromStr;
3use std::time::SystemTime;
4
5use bytes::Bytes;
6use http::header::HeaderValue;
7use httpdate;
8
9use super::IterExt;
10
11/// A timestamp with HTTP formatting and parsing
12//   Prior to 1995, there were three different formats commonly used by
13//   servers to communicate timestamps.  For compatibility with old
14//   implementations, all three are defined here.  The preferred format is
15//   a fixed-length and single-zone subset of the date and time
16//   specification used by the Internet Message Format [RFC5322].
17//
18//     HTTP-date    = IMF-fixdate / obs-date
19//
20//   An example of the preferred format is
21//
22//     Sun, 06 Nov 1994 08:49:37 GMT    ; IMF-fixdate
23//
24//   Examples of the two obsolete formats are
25//
26//     Sunday, 06-Nov-94 08:49:37 GMT   ; obsolete RFC 850 format
27//     Sun Nov  6 08:49:37 1994         ; ANSI C's asctime() format
28//
29//   A recipient that parses a timestamp value in an HTTP header field
30//   MUST accept all three HTTP-date formats.  When a sender generates a
31//   header field that contains one or more timestamps defined as
32//   HTTP-date, the sender MUST generate those timestamps in the
33//   IMF-fixdate format.
34#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub(crate) struct HttpDate(httpdate::HttpDate);
36
37impl HttpDate {
38    pub(crate) fn from_val(val: &HeaderValue) -> Option<Self> {
39        val.to_str().ok()?.parse().ok()
40    }
41}
42
43// TODO: remove this and FromStr?
44#[derive(Debug)]
45pub struct Error(());
46
47impl super::TryFromValues for HttpDate {
48    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, ::Error>
49    where
50        I: Iterator<Item = &'i HeaderValue>,
51    {
52        values
53            .just_one()
54            .and_then(HttpDate::from_val)
55            .ok_or_else(::Error::invalid)
56    }
57}
58
59impl From<HttpDate> for HeaderValue {
60    fn from(date: HttpDate) -> HeaderValue {
61        (&date).into()
62    }
63}
64
65impl<'a> From<&'a HttpDate> for HeaderValue {
66    fn from(date: &'a HttpDate) -> HeaderValue {
67        // TODO: could be just BytesMut instead of String
68        let s = date.to_string();
69        let bytes = Bytes::from(s);
70        HeaderValue::from_maybe_shared(bytes).expect("HttpDate always is a valid value")
71    }
72}
73
74impl FromStr for HttpDate {
75    type Err = Error;
76    fn from_str(s: &str) -> Result<HttpDate, Error> {
77        Ok(HttpDate(s.parse().map_err(|_| Error(()))?))
78    }
79}
80
81impl fmt::Debug for HttpDate {
82    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83        fmt::Display::fmt(&self.0, f)
84    }
85}
86
87impl fmt::Display for HttpDate {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        fmt::Display::fmt(&self.0, f)
90    }
91}
92
93impl From<SystemTime> for HttpDate {
94    fn from(sys: SystemTime) -> HttpDate {
95        HttpDate(sys.into())
96    }
97}
98
99impl From<HttpDate> for SystemTime {
100    fn from(date: HttpDate) -> SystemTime {
101        SystemTime::from(date.0)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::HttpDate;
108
109    use std::time::{Duration, UNIX_EPOCH};
110
111    // The old tests had Sunday, but 1994-11-07 is a Monday.
112    // See https://github.com/pyfisch/httpdate/pull/6#issuecomment-846881001
113    fn nov_07() -> HttpDate {
114        HttpDate((UNIX_EPOCH + Duration::new(784198117, 0)).into())
115    }
116
117    #[test]
118    fn test_display_is_imf_fixdate() {
119        assert_eq!("Mon, 07 Nov 1994 08:48:37 GMT", &nov_07().to_string());
120    }
121
122    #[test]
123    fn test_imf_fixdate() {
124        assert_eq!(
125            "Mon, 07 Nov 1994 08:48:37 GMT".parse::<HttpDate>().unwrap(),
126            nov_07()
127        );
128    }
129
130    #[test]
131    fn test_rfc_850() {
132        assert_eq!(
133            "Monday, 07-Nov-94 08:48:37 GMT"
134                .parse::<HttpDate>()
135                .unwrap(),
136            nov_07()
137        );
138    }
139
140    #[test]
141    fn test_asctime() {
142        assert_eq!(
143            "Mon Nov  7 08:48:37 1994".parse::<HttpDate>().unwrap(),
144            nov_07()
145        );
146    }
147
148    #[test]
149    fn test_no_date() {
150        assert!("this-is-no-date".parse::<HttpDate>().is_err());
151    }
152}