      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
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254

    use header::{Header, IntoHeaderValue, Writer};
    use header::{fmt_comma_delimited, from_comma_delimited};
    use http::header;
    use std::fmt::{self, Write};
    use std::str::FromStr;

    /// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2)
    ///
    /// The `Cache-Control` header field is used to specify directives for
    /// caches along the request/response chain.  Such cache directives are
    /// unidirectional in that the presence of a directive in a request does
    /// not imply that the same directive is to be given in the response.
    ///
    /// # ABNF
    ///
    /// ```text
    /// Cache-Control   = 1#cache-directive
    /// cache-directive = token [ "=" ( token / quoted-string ) ]
    /// ```
    ///
    /// # Example values
    ///
    /// * `no-cache`
    /// * `private, community="UCI"`
    /// * `max-age=30`
    ///
    /// # Examples
    /// ```rust
    /// use actix_web::HttpResponse;
    /// use actix_web::http::header::{CacheControl, CacheDirective};
    ///
    /// let mut builder = HttpResponse::Ok();
    /// builder.set(CacheControl(vec![CacheDirective::MaxAge(86400u32)]));
    /// ```
    ///
    /// ```rust
    /// use actix_web::HttpResponse;
    /// use actix_web::http::header::{CacheControl, CacheDirective};
    ///
    /// let mut builder = HttpResponse::Ok();
    /// builder.set(CacheControl(vec![
    ///     CacheDirective::NoCache,
    ///     CacheDirective::Private,
    ///     CacheDirective::MaxAge(360u32),
    ///     CacheDirective::Extension("foo".to_owned(), Some("bar".to_owned())),
    /// ]));
    /// ```
    #[derive(PartialEq, Clone, Debug)]
    pub struct CacheControl(pub Vec<CacheDirective>);

    __hyper__deref!(CacheControl => Vec<CacheDirective>);

    //TODO: this could just be the header! macro
    impl Header for CacheControl {
        fn name() -> header::HeaderName {
            header::CACHE_CONTROL
        }

        #[inline]
        fn parse<T>(msg: &T) -> Result<Self, ::error::ParseError>
        where
            T: ::HttpMessage,
        {
            let directives = from_comma_delimited(msg.headers().get_all(Self::name()))?;
            if !directives.is_empty() {
                Ok(CacheControl(directives))
            } else {
                Err(::error::ParseError::Header)
            }
        }
    }

    impl fmt::Display for CacheControl {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            fmt_comma_delimited(f, &self[..])
        }
    }

    impl IntoHeaderValue for CacheControl {
        type Error = header::InvalidHeaderValueBytes;

        fn try_into(self) -> Result<header::HeaderValue, Self::Error> {
            let mut writer = Writer::new();
            let _ = write!(&mut writer, "{}", self);
            header::HeaderValue::from_shared(writer.take())
        }
    }

    /// `CacheControl` contains a list of these directives.
    #[derive(PartialEq, Clone, Debug)]
    pub enum CacheDirective {
        /// "no-cache"
        NoCache,
        /// "no-store"
        NoStore,
        /// "no-transform"
        NoTransform,
        /// "only-if-cached"
        OnlyIfCached,

        // request directives
        /// "max-age=delta"
        MaxAge(u32),
        /// "max-stale=delta"
        MaxStale(u32),
        /// "min-fresh=delta"
        MinFresh(u32),

        // response directives
        /// "must-revalidate"
        MustRevalidate,
        /// "public"
        Public,
        /// "private"
        Private,
        /// "proxy-revalidate"
        ProxyRevalidate,
        /// "s-maxage=delta"
        SMaxAge(u32),

        /// Extension directives. Optionally include an argument.
        Extension(String, Option<String>),
    }

    impl fmt::Display for CacheDirective {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use self::CacheDirective::*;
            fmt::Display::fmt(
                match *self {
                    NoCache => "no-cache",
                    NoStore => "no-store",
                    NoTransform => "no-transform",
                    OnlyIfCached => "only-if-cached",

                    MaxAge(secs) => return write!(f, "max-age={}", secs),
                    MaxStale(secs) => return write!(f, "max-stale={}", secs),
                    MinFresh(secs) => return write!(f, "min-fresh={}", secs),

                    MustRevalidate => "must-revalidate",
                    Public => "public",
                    Private => "private",
                    ProxyRevalidate => "proxy-revalidate",
                    SMaxAge(secs) => return write!(f, "s-maxage={}", secs),

                    Extension(ref name, None) => &name[..],
                    Extension(ref name, Some(ref arg)) => {
                        return write!(f, "{}={}", name, arg)
                    }
                },
                f,
            )
        }
    }

    impl FromStr for CacheDirective {
        type Err = Option<<u32 as FromStr>::Err>;
        fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> {
            use self::CacheDirective::*;
            match s {
                "no-cache" => Ok(NoCache),
                "no-store" => Ok(NoStore),
                "no-transform" => Ok(NoTransform),
                "only-if-cached" => Ok(OnlyIfCached),
                "must-revalidate" => Ok(MustRevalidate),
                "public" => Ok(Public),
                "private" => Ok(Private),
                "proxy-revalidate" => Ok(ProxyRevalidate),
                "" => Err(None),
                _ => match s.find('=') {
                    Some(idx) if idx + 1 < s.len() => {
                        match (&s[..idx], (&s[idx + 1..]).trim_matches('"')) {
                            ("max-age", secs) => secs.parse().map(MaxAge).map_err(Some),
                            ("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
                            ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
                            ("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
                            (left, right) => {
                                Ok(Extension(left.to_owned(), Some(right.to_owned())))
                            }
                        }
                    }
                    Some(_) => Err(None),
                    None => Ok(Extension(s.to_owned(), None)),
                },
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use header::Header;
        use test::TestRequest;

        #[test]
        fn test_parse_multiple_headers() {
            let req = TestRequest::with_header(header::CACHE_CONTROL, "no-cache, private")
                .finish();
            let cache = Header::parse(&req);
            assert_eq!(
                cache.ok(),
                Some(CacheControl(vec![
                    CacheDirective::NoCache,
                    CacheDirective::Private,
                ]))
            )
        }

        #[test]
        fn test_parse_argument() {
            let req =
                TestRequest::with_header(header::CACHE_CONTROL, "max-age=100, private")
                    .finish();
            let cache = Header::parse(&req);
            assert_eq!(
                cache.ok(),
                Some(CacheControl(vec![
                    CacheDirective::MaxAge(100),
                    CacheDirective::Private,
                ]))
            )
        }

        #[test]
        fn test_parse_quote_form() {
            let req =
                TestRequest::with_header(header::CACHE_CONTROL, "max-age=\"200\"").finish();
            let cache = Header::parse(&req);
            assert_eq!(
                cache.ok(),
                Some(CacheControl(vec![CacheDirective::MaxAge(200)]))
            )
        }

        #[test]
        fn test_parse_extension() {
            let req =
                TestRequest::with_header(header::CACHE_CONTROL, "foo, bar=baz").finish();
            let cache = Header::parse(&req);
            assert_eq!(
                cache.ok(),
                Some(CacheControl(vec![
                    CacheDirective::Extension("foo".to_owned(), None),
                    CacheDirective::Extension("bar".to_owned(), Some("baz".to_owned())),
                ]))
            )
        }

        #[test]
        fn test_parse_bad_syntax() {
            let req = TestRequest::with_header(header::CACHE_CONTROL, "foo=").finish();
            let cache: Result<CacheControl, _> = Header::parse(&req);
            assert_eq!(cache.ok(), None)
        }
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)