headers/util/
http_date.rs1use std::fmt;
2use std::str::FromStr;
3use std::time::SystemTime;
4
5use bytes::Bytes;
6use http::header::HeaderValue;
7
8use super::IterExt;
9
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub(crate) struct HttpDate(httpdate::HttpDate);
35
36impl HttpDate {
37 pub(crate) fn from_val(val: &HeaderValue) -> Option<Self> {
38 val.to_str().ok()?.parse().ok()
39 }
40}
41
42#[derive(Debug)]
44pub struct Error(());
45
46impl super::TryFromValues for HttpDate {
47 fn try_from_values<'i, I>(values: &mut I) -> Result<Self, crate::Error>
48 where
49 I: Iterator<Item = &'i HeaderValue>,
50 {
51 values
52 .just_one()
53 .and_then(HttpDate::from_val)
54 .ok_or_else(crate::Error::invalid)
55 }
56}
57
58impl From<HttpDate> for HeaderValue {
59 fn from(date: HttpDate) -> HeaderValue {
60 (&date).into()
61 }
62}
63
64impl<'a> From<&'a HttpDate> for HeaderValue {
65 fn from(date: &'a HttpDate) -> HeaderValue {
66 let s = date.to_string();
68 let bytes = Bytes::from(s);
69 HeaderValue::from_maybe_shared(bytes).expect("HttpDate always is a valid value")
70 }
71}
72
73impl FromStr for HttpDate {
74 type Err = Error;
75 fn from_str(s: &str) -> Result<HttpDate, Error> {
76 Ok(HttpDate(s.parse().map_err(|_| Error(()))?))
77 }
78}
79
80impl fmt::Debug for HttpDate {
81 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 fmt::Display::fmt(&self.0, f)
83 }
84}
85
86impl fmt::Display for HttpDate {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 fmt::Display::fmt(&self.0, f)
89 }
90}
91
92impl From<SystemTime> for HttpDate {
93 fn from(sys: SystemTime) -> HttpDate {
94 HttpDate(sys.into())
95 }
96}
97
98impl From<HttpDate> for SystemTime {
99 fn from(date: HttpDate) -> SystemTime {
100 SystemTime::from(date.0)
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::HttpDate;
107
108 use std::time::{Duration, UNIX_EPOCH};
109
110 fn nov_07() -> HttpDate {
113 HttpDate((UNIX_EPOCH + Duration::new(784198117, 0)).into())
114 }
115
116 #[test]
117 fn test_display_is_imf_fixdate() {
118 assert_eq!("Mon, 07 Nov 1994 08:48:37 GMT", &nov_07().to_string());
119 }
120
121 #[test]
122 fn test_imf_fixdate() {
123 assert_eq!(
124 "Mon, 07 Nov 1994 08:48:37 GMT".parse::<HttpDate>().unwrap(),
125 nov_07()
126 );
127 }
128
129 #[test]
130 fn test_rfc_850() {
131 assert_eq!(
132 "Monday, 07-Nov-94 08:48:37 GMT"
133 .parse::<HttpDate>()
134 .unwrap(),
135 nov_07()
136 );
137 }
138
139 #[test]
140 fn test_asctime() {
141 assert_eq!(
142 "Mon Nov 7 08:48:37 1994".parse::<HttpDate>().unwrap(),
143 nov_07()
144 );
145 }
146
147 #[test]
148 fn test_no_date() {
149 assert!("this-is-no-date".parse::<HttpDate>().is_err());
150 }
151}