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