headers/common/
if_modified_since.rs

1use crate::util::HttpDate;
2use std::time::SystemTime;
3
4/// `If-Modified-Since` header, defined in
5/// [RFC7232](https://datatracker.ietf.org/doc/html/rfc7232#section-3.3)
6///
7/// The `If-Modified-Since` header field makes a GET or HEAD request
8/// method conditional on the selected representation's modification date
9/// being more recent than the date provided in the field-value.
10/// Transfer of the selected representation's data is avoided if that
11/// data has not changed.
12///
13/// # ABNF
14///
15/// ```text
16/// If-Modified-Since = HTTP-date
17/// ```
18///
19/// # Example values
20/// * `Sat, 29 Oct 1994 19:43:31 GMT`
21///
22/// # Example
23///
24/// ```
25/// use headers::IfModifiedSince;
26/// use std::time::{Duration, SystemTime};
27///
28/// let time = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
29/// let if_mod = IfModifiedSince::from(time);
30/// ```
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub struct IfModifiedSince(HttpDate);
33
34derive_header! {
35    IfModifiedSince(_),
36    name: IF_MODIFIED_SINCE
37}
38
39impl IfModifiedSince {
40    /// Check if the supplied time means the resource has been modified.
41    pub fn is_modified(&self, last_modified: SystemTime) -> bool {
42        self.0 < last_modified.into()
43    }
44}
45
46impl From<SystemTime> for IfModifiedSince {
47    fn from(time: SystemTime) -> IfModifiedSince {
48        IfModifiedSince(time.into())
49    }
50}
51
52impl From<IfModifiedSince> for SystemTime {
53    fn from(date: IfModifiedSince) -> SystemTime {
54        date.0.into()
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use std::time::Duration;
62
63    #[test]
64    fn is_modified() {
65        let newer = SystemTime::now();
66        let exact = newer - Duration::from_secs(2);
67        let older = newer - Duration::from_secs(4);
68
69        let if_mod = IfModifiedSince::from(exact);
70        assert!(if_mod.is_modified(newer));
71        assert!(!if_mod.is_modified(exact));
72        assert!(!if_mod.is_modified(older));
73    }
74}