rama_http_headers/util/
http_date.rs1use std::fmt;
2use std::str::FromStr;
3use std::time::SystemTime;
4
5use bytes::Bytes;
6use rama_error::OpaqueError;
7use rama_http_types::header::HeaderValue;
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
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(HttpDate::from_val)
51 .ok_or_else(crate::Error::invalid)
52 }
53}
54
55impl From<HttpDate> for HeaderValue {
56 fn from(date: HttpDate) -> HeaderValue {
57 (&date).into()
58 }
59}
60
61impl<'a> From<&'a HttpDate> for HeaderValue {
62 fn from(date: &'a HttpDate) -> HeaderValue {
63 let s = date.to_string();
65 let bytes = Bytes::from(s);
66 HeaderValue::from_maybe_shared(bytes).expect("HttpDate always is a valid value")
67 }
68}
69
70impl FromStr for HttpDate {
71 type Err = OpaqueError;
72 fn from_str(s: &str) -> Result<HttpDate, OpaqueError> {
73 Ok(HttpDate(s.parse().map_err(|_| {
74 OpaqueError::from_display("invalid http date")
75 })?))
76 }
77}
78
79impl fmt::Debug for HttpDate {
80 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81 fmt::Display::fmt(&self.0, f)
82 }
83}
84
85impl fmt::Display for HttpDate {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87 fmt::Display::fmt(&self.0, f)
88 }
89}
90
91impl From<SystemTime> for HttpDate {
92 fn from(sys: SystemTime) -> HttpDate {
93 HttpDate(sys.into())
94 }
95}
96
97impl From<HttpDate> for SystemTime {
98 fn from(date: HttpDate) -> SystemTime {
99 SystemTime::from(date.0)
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::HttpDate;
106
107 use std::time::{Duration, UNIX_EPOCH};
108
109 fn nov_07() -> HttpDate {
112 HttpDate((UNIX_EPOCH + Duration::new(784198117, 0)).into())
113 }
114
115 #[test]
116 fn test_display_is_imf_fixdate() {
117 assert_eq!("Mon, 07 Nov 1994 08:48:37 GMT", &nov_07().to_string());
118 }
119
120 #[test]
121 fn test_imf_fixdate() {
122 assert_eq!(
123 "Mon, 07 Nov 1994 08:48:37 GMT".parse::<HttpDate>().unwrap(),
124 nov_07()
125 );
126 }
127
128 #[test]
129 fn test_rfc_850() {
130 assert_eq!(
131 "Monday, 07-Nov-94 08:48:37 GMT"
132 .parse::<HttpDate>()
133 .unwrap(),
134 nov_07()
135 );
136 }
137
138 #[test]
139 fn test_asctime() {
140 assert_eq!(
141 "Mon Nov 7 08:48:37 1994".parse::<HttpDate>().unwrap(),
142 nov_07()
143 );
144 }
145
146 #[test]
147 fn test_no_date() {
148 assert!("this-is-no-date".parse::<HttpDate>().is_err());
149 }
150}