rama_http_headers/common/
if_modified_since.rs1use rama_core::telemetry::tracing;
2use rama_http_types::HeaderValue;
3
4use crate::util::HttpDate;
5use std::time::SystemTime;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct IfModifiedSince(HttpDate);
37
38impl crate::TypedHeader for IfModifiedSince {
39 fn name() -> &'static ::rama_http_types::header::HeaderName {
40 &::rama_http_types::header::IF_MODIFIED_SINCE
41 }
42}
43
44impl crate::HeaderDecode for IfModifiedSince {
45 fn decode<'i, I>(values: &mut I) -> Result<Self, crate::Error>
46 where
47 I: Iterator<Item = &'i ::rama_http_types::header::HeaderValue>,
48 {
49 crate::util::TryFromValues::try_from_values(values).map(IfModifiedSince)
50 }
51}
52
53impl crate::HeaderEncode for IfModifiedSince {
54 fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
55 match HeaderValue::try_from(&self.0) {
56 Ok(value) => values.extend(::std::iter::once(value)),
57 Err(err) => {
58 tracing::debug!("failed to encode if-modified-since value as header: {err}");
59 }
60 }
61 }
62}
63
64impl IfModifiedSince {
65 #[must_use]
67 pub fn is_modified(&self, last_modified: SystemTime) -> bool {
68 self.0 < last_modified.into()
69 }
70}
71
72impl From<SystemTime> for IfModifiedSince {
73 fn from(time: SystemTime) -> Self {
74 Self(time.into())
75 }
76}
77
78impl From<IfModifiedSince> for SystemTime {
79 fn from(date: IfModifiedSince) -> Self {
80 date.0.into()
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use std::time::Duration;
88
89 #[test]
90 fn is_modified() {
91 let newer = SystemTime::now();
92 let exact = newer - Duration::from_secs(2);
93 let older = newer - Duration::from_secs(4);
94
95 let if_mod = IfModifiedSince::from(exact);
96 assert!(if_mod.is_modified(newer));
97 assert!(!if_mod.is_modified(exact));
98 assert!(!if_mod.is_modified(older));
99 }
100}