headers_ext/common/if_unmodified_since.rs
1use std::time::SystemTime;
2use util::HttpDate;
3
4/// `If-Unmodified-Since` header, defined in
5/// [RFC7232](http://tools.ietf.org/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/// # extern crate headers_ext as headers;
27/// use headers::IfUnmodifiedSince;
28/// use std::time::{SystemTime, Duration};
29///
30/// let time = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
31/// let if_unmod = IfUnmodifiedSince::from(time);
32/// ```
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Header)]
34pub struct IfUnmodifiedSince(HttpDate);
35
36impl IfUnmodifiedSince {
37 /// Check if the supplied time passes the precondtion.
38 pub fn precondition_passes(&self, last_modified: SystemTime) -> bool {
39 self.0 >= last_modified.into()
40 }
41}
42
43impl From<SystemTime> for IfUnmodifiedSince {
44 fn from(time: SystemTime) -> IfUnmodifiedSince {
45 IfUnmodifiedSince(time.into())
46 }
47}
48
49impl From<IfUnmodifiedSince> for SystemTime {
50 fn from(date: IfUnmodifiedSince) -> SystemTime {
51 date.0.into()
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use std::time::Duration;
58 use super::*;
59
60 #[test]
61 fn precondition_passes() {
62 let newer = SystemTime::now();
63 let exact = newer - Duration::from_secs(2);
64 let older = newer - Duration::from_secs(4);
65
66 let if_unmod = IfUnmodifiedSince::from(exact);
67 assert!(!if_unmod.precondition_passes(newer));
68 assert!(if_unmod.precondition_passes(exact));
69 assert!(if_unmod.precondition_passes(older));
70 }
71}