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#[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#[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 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 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}