1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
extern crate time;

use time::Duration;

/// How the data may be cached.
#[derive(Eq, PartialEq, Debug)]
pub enum Cachability {
    /// Any cache can cache this data.
    Public,

    /// Data cannot be cached in shared caches.
    Private,

    /// No one can cache this data.
    NoCache,

    /// Cache the data the first time, and use the cache from then on.
    OnlyIfCached,
}

/// Represents a Cache-Control header
/// # Example
/// ```
/// extern crate cache_control;
/// extern crate time;
/// use cache_control::CacheControl;
/// use time::Duration;
///
/// let cache_control = CacheControl::from_header("Cache-Control: max-age=60").unwrap();
/// assert_eq!(cache_control.max_age, Some(Duration::seconds(60)));
/// ```
///
#[derive(Eq, PartialEq, Debug)]
pub struct CacheControl {
    pub cachability: Option<Cachability>,
    pub max_age: Option<Duration>,
    pub s_max_age: Option<Duration>,
    pub max_stale: Option<Duration>,
    pub min_fresh: Option<Duration>,
    pub must_revalidate: bool,
    pub proxy_revalidate: bool,
    pub immutable: bool,
    pub no_store: bool,
    pub no_transform: bool,
}

impl CacheControl {
    fn new() -> CacheControl {
        CacheControl::default()
    }

    /// Parses the value of the Cache-Control header (i.e. everything after "Cache-Control:").
    pub fn from_value(value: &str) -> Option<CacheControl> {
        let mut ret = CacheControl::new();
        let tokens: Vec<&str> = value.split(",").collect();
        for token in tokens {
            let key_value: Vec<&str> = token.split("=").map(|s| s.trim()).collect();
            let key = key_value.first().unwrap();
            let val = key_value.get(1);

            match *key {
                "public" => ret.cachability = Some(Cachability::Public),
                "private" => ret.cachability = Some(Cachability::Private),
                "no-cache" => ret.cachability = Some(Cachability::NoCache),
                "only-if-cached" => ret.cachability = Some(Cachability::OnlyIfCached),
                "max-age" => {
                    if let None = val {
                        return None;
                    }
                    let val_d = *(val.unwrap());
                    let p_val = val_d.parse();
                    if let Err(_) = p_val {
                        return None;
                    }
                    ret.max_age = Some(Duration::seconds(p_val.unwrap()));
                },
                "max-stale" => {
                    if let None = val {
                        return None;
                    }
                    let val_d = *(val.unwrap());
                    let p_val = val_d.parse();
                    if let Err(_) = p_val {
                        return None;
                    }
                    ret.max_stale = Some(Duration::seconds(p_val.unwrap()));
                },
                "min-fresh" => {
                    if let None = val {
                        return None;
                    }
                    let val_d = *(val.unwrap());
                    let p_val = val_d.parse();
                    if let Err(_) = p_val {
                        return None;
                    }
                    ret.min_fresh = Some(Duration::seconds(p_val.unwrap()));
                },
                "must-revalidate" => ret.must_revalidate = true,
                "proxy-revalidate" => ret.proxy_revalidate = true,
                "immutable" => ret.immutable = true,
                "no-store" => ret.no_store = true,
                "no-transform" => ret.no_transform = true,
                _ => (),
            };
        }
        Some(ret)
    }

    /// Parses a Cache-Control header.
    pub fn from_header(value: &str) -> Option<CacheControl> {
        let header_value: Vec<&str> = value.split(":").map(|s| s.trim()).collect();
        if header_value.len() != 2 || header_value.first().unwrap() != &"Cache-Control" {
            return None;
        }
        let val = header_value.get(1).unwrap();
        CacheControl::from_value(val)
    }
}

impl Default for CacheControl {
    fn default() -> Self {
        CacheControl {
            cachability: None,
            max_age: None,
            s_max_age: None,
            max_stale: None,
            min_fresh: None,
            must_revalidate: false,
            proxy_revalidate: false,
            immutable: false,
            no_store: false,
            no_transform: false,
        }
    }
}

#[cfg(test)]
mod test {
    use super::{CacheControl, Cachability};
    use time::Duration;

    #[test]
    fn test_from_value() {
        assert_eq!(CacheControl::from_value("").unwrap(), CacheControl::default());
        assert_eq!(CacheControl::from_value("private").unwrap().cachability.unwrap(), Cachability::Private);
        assert_eq!(CacheControl::from_value("max-age=60").unwrap().max_age.unwrap(), Duration::seconds(60));
    }

    #[test]
    fn test_from_value_multi() {
        let test1 = &CacheControl::from_value("no-cache, no-store, must-revalidate").unwrap();
        assert_eq!(test1.cachability, Some(Cachability::NoCache));
        assert_eq!(test1.no_store, true);
        assert_eq!(test1.must_revalidate, true);
        assert_eq!(*test1, CacheControl {
            cachability: Some(Cachability::NoCache),
            max_age: None,
            s_max_age: None,
            max_stale: None,
            min_fresh: None,
            must_revalidate: true,
            proxy_revalidate: false,
            immutable: false,
            no_store: true,
            no_transform: false,
        });
    }

    #[test]
    fn test_from_header() {
        assert_eq!(CacheControl::from_header("Cache-Control: ").unwrap(), CacheControl::default());
        assert_eq!(CacheControl::from_header("Cache-Control: private").unwrap().cachability.unwrap(), Cachability::Private);
        assert_eq!(CacheControl::from_header("Cache-Control: max-age=60").unwrap().max_age.unwrap(), Duration::seconds(60));
        assert_eq!(CacheControl::from_header("foo"), None);
        assert_eq!(CacheControl::from_header("bar: max-age=60"), None);
    }

    #[test]
    fn test_from_header_multi() {
        let test1 = &CacheControl::from_header("Cache-Control: public, max-age=600").unwrap();
        assert_eq!(test1.cachability, Some(Cachability::Public));
        assert_eq!(test1.max_age, Some(Duration::seconds(600)));
        assert_eq!(*test1, CacheControl {
            cachability: Some(Cachability::Public),
            max_age: Some(Duration::seconds(600)),
            s_max_age: None,
            max_stale: None,
            min_fresh: None,
            must_revalidate: false,
            proxy_revalidate: false,
            immutable: false,
            no_store: false,
            no_transform: false,
        });
    }
}