Skip to main content

rama_http_headers/util/
http_date.rs

1use std::fmt;
2use std::str::FromStr;
3use std::time::SystemTime;
4
5use rama_core::bytes::Bytes;
6use rama_core::error::{BoxError, ErrorContext as _};
7use rama_http_types::header::HeaderValue;
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 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
43impl super::TryFromValues for HttpDate {
44    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, crate::Error>
45    where
46        I: Iterator<Item = &'i HeaderValue>,
47    {
48        values
49            .just_one()
50            .and_then(Self::from_val)
51            .ok_or_else(crate::Error::invalid)
52    }
53}
54
55impl TryFrom<HttpDate> for HeaderValue {
56    type Error = BoxError;
57
58    fn try_from(date: HttpDate) -> Result<Self, Self::Error> {
59        (&date).try_into()
60    }
61}
62
63impl TryFrom<&HttpDate> for HeaderValue {
64    type Error = BoxError;
65
66    fn try_from(date: &HttpDate) -> Result<Self, Self::Error> {
67        let s = date.to_string();
68        let bytes = Bytes::from(s);
69        Self::from_maybe_shared(bytes).context("parse HttpDate as header value")
70    }
71}
72
73impl FromStr for HttpDate {
74    type Err = BoxError;
75
76    fn from_str(s: &str) -> Result<Self, BoxError> {
77        Ok(Self(s.parse().context("invalid http date")?))
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) -> Self {
95        Self(sys.into())
96    }
97}
98
99impl From<HttpDate> for SystemTime {
100    fn from(date: HttpDate) -> Self {
101        Self::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        "this-is-no-date".parse::<HttpDate>().unwrap_err();
151    }
152}