actix_http/header/shared/
http_date.rs1use std::{fmt, io::Write, str::FromStr, time::SystemTime};
2
3use bytes::BytesMut;
4use http::header::{HeaderValue, InvalidHeaderValue};
5
6use crate::{
7 date::DATE_VALUE_LENGTH, error::ParseError, header::TryIntoHeaderValue, helpers::MutWriter,
8};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
12pub struct HttpDate(SystemTime);
13
14impl_more::impl_newtype_from_into!(HttpDate [<=>] SystemTime);
15
16impl FromStr for HttpDate {
17 type Err = ParseError;
18
19 fn from_str(s: &str) -> Result<HttpDate, ParseError> {
20 match httpdate::parse_http_date(s) {
21 Ok(sys_time) => Ok(HttpDate(sys_time)),
22 Err(_) => Err(ParseError::Header),
23 }
24 }
25}
26
27impl fmt::Display for HttpDate {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 httpdate::HttpDate::from(self.0).fmt(f)
30 }
31}
32
33impl TryIntoHeaderValue for HttpDate {
34 type Error = InvalidHeaderValue;
35
36 fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
37 let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH);
38 let mut wrt = MutWriter(&mut buf);
39
40 write!(wrt, "{}", self).unwrap();
42
43 HeaderValue::from_maybe_shared(buf.split().freeze())
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use std::time::Duration;
50
51 use super::*;
52
53 #[test]
54 fn date_header() {
55 macro_rules! assert_parsed_date {
56 ($case:expr, $exp:expr) => {
57 assert_eq!($case.parse::<HttpDate>().unwrap(), $exp);
58 };
59 }
60
61 let nov_07 = HttpDate(SystemTime::UNIX_EPOCH + Duration::from_secs(784198117));
63
64 assert_parsed_date!("Mon, 07 Nov 1994 08:48:37 GMT", nov_07);
65 assert_parsed_date!("Monday, 07-Nov-94 08:48:37 GMT", nov_07);
66 assert_parsed_date!("Mon Nov 7 08:48:37 1994", nov_07);
67
68 assert!("this-is-no-date".parse::<HttpDate>().is_err());
69 }
70}