headers/common/
if_unmodified_since.rs

1use crate::util::HttpDate;
2use std::time::SystemTime;
3
4/// `If-Unmodified-Since` header, defined in
5/// [RFC7232](https://datatracker.ietf.org/doc/html/rfc7232#section-3.4)
6///
7/// The `If-Unmodified-Since` header field makes the request method
8/// conditional on the selected representation's last modification date
9/// being earlier than or equal to the date provided in the field-value.
10/// This field accomplishes the same purpose as If-Match for cases where
11/// the user agent does not have an entity-tag for the representation.
12///
13/// # ABNF
14///
15/// ```text
16/// If-Unmodified-Since = HTTP-date
17/// ```
18///
19/// # Example values
20///
21/// * `Sat, 29 Oct 1994 19:43:31 GMT`
22///
23/// # Example
24///
25/// ```
26/// use headers::IfUnmodifiedSince;
27/// use std::time::{SystemTime, Duration};
28///
29/// let time = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
30/// let if_unmod = IfUnmodifiedSince::from(time);
31/// ```
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
33pub struct IfUnmodifiedSince(HttpDate);
34
35derive_header! {
36    IfUnmodifiedSince(_),
37    name: IF_UNMODIFIED_SINCE
38}
39
40impl IfUnmodifiedSince {
41    /// Check if the supplied time passes the precondtion.
42    pub fn precondition_passes(&self, last_modified: SystemTime) -> bool {
43        self.0 >= last_modified.into()
44    }
45}
46
47impl From<SystemTime> for IfUnmodifiedSince {
48    fn from(time: SystemTime) -> IfUnmodifiedSince {
49        IfUnmodifiedSince(time.into())
50    }
51}
52
53impl From<IfUnmodifiedSince> for SystemTime {
54    fn from(date: IfUnmodifiedSince) -> SystemTime {
55        date.0.into()
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use std::time::Duration;
63
64    #[test]
65    fn precondition_passes() {
66        let newer = SystemTime::now();
67        let exact = newer - Duration::from_secs(2);
68        let older = newer - Duration::from_secs(4);
69
70        let if_unmod = IfUnmodifiedSince::from(exact);
71        assert!(!if_unmod.precondition_passes(newer));
72        assert!(if_unmod.precondition_passes(exact));
73        assert!(if_unmod.precondition_passes(older));
74    }
75}