rama_http_headers/util/
http_date.rs1use 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#[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 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}