      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
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303

    use std;
    use std::ops::Index;
    use std::path::PathBuf;
    use std::rc::Rc;
    use std::str::FromStr;

    use http::StatusCode;
    use smallvec::SmallVec;

    use error::{InternalError, ResponseError, UriSegmentError};
    use uri::Url;

    /// A trait to abstract the idea of creating a new instance of a type from a
    /// path parameter.
    pub trait FromParam: Sized {
        /// The associated error which can be returned from parsing.
        type Err: ResponseError;

        /// Parses a string `s` to return a value of this type.
        fn from_param(s: &str) -> Result<Self, Self::Err>;
    }

    #[derive(Debug, Clone)]
    pub(crate) enum ParamItem {
        Static(&'static str),
        UrlSegment(u16, u16),
    }

    /// Route match information
    ///
    /// If resource path contains variable patterns, `Params` stores this variables.
    #[derive(Debug, Clone)]
    pub struct Params {
        url: Url,
        pub(crate) tail: u16,
        pub(crate) segments: SmallVec<[(Rc<String>, ParamItem); 3]>,
    }

    impl Params {
        pub(crate) fn new() -> Params {
            Params {
                url: Url::default(),
                tail: 0,
                segments: SmallVec::new(),
            }
        }

        pub(crate) fn with_url(url: &Url) -> Params {
            Params {
                url: url.clone(),
                tail: 0,
                segments: SmallVec::new(),
            }
        }

        pub(crate) fn clear(&mut self) {
            self.segments.clear();
        }

        pub(crate) fn set_tail(&mut self, tail: u16) {
            self.tail = tail;
        }

        pub(crate) fn set_url(&mut self, url: Url) {
            self.url = url;
        }

        pub(crate) fn add(&mut self, name: Rc<String>, value: ParamItem) {
            self.segments.push((name, value));
        }

        pub(crate) fn add_static(&mut self, name: &str, value: &'static str) {
            self.segments
                .push((Rc::new(name.to_string()), ParamItem::Static(value)));
        }

        /// Check if there are any matched patterns
        pub fn is_empty(&self) -> bool {
            self.segments.is_empty()
        }

        /// Check number of extracted parameters
        pub fn len(&self) -> usize {
            self.segments.len()
        }

        /// Get matched parameter by name without type conversion
        pub fn get(&self, key: &str) -> Option<&str> {
            for item in self.segments.iter() {
                if key == item.0.as_str() {
                    return match item.1 {
                        ParamItem::Static(ref s) => Some(&s),
                        ParamItem::UrlSegment(s, e) => {
                            Some(&self.url.path()[(s as usize)..(e as usize)])
                        }
                    };
                }
            }
            if key == "tail" {
                Some(&self.url.path()[(self.tail as usize)..])
            } else {
                None
            }
        }

        /// Get unprocessed part of path
        pub fn unprocessed(&self) -> &str {
            &self.url.path()[(self.tail as usize)..]
        }

        /// Get matched `FromParam` compatible parameter by name.
        ///
        /// If keyed parameter is not available empty string is used as default
        /// value.
        ///
        /// ```rust
        /// # extern crate actix_web;
        /// # use actix_web::*;
        /// fn index(req: HttpRequest) -> Result<String> {
        ///     let ivalue: isize = req.match_info().query("val")?;
        ///     Ok(format!("isuze value: {:?}", ivalue))
        /// }
        /// # fn main() {}
        /// ```
        pub fn query<T: FromParam>(&self, key: &str) -> Result<T, <T as FromParam>::Err> {
            if let Some(s) = self.get(key) {
                T::from_param(s)
            } else {
                T::from_param("")
            }
        }

        /// Return iterator to items in parameter container
        pub fn iter(&self) -> ParamsIter {
            ParamsIter {
                idx: 0,
                params: self,
            }
        }
    }

    #[derive(Debug)]
    pub struct ParamsIter<'a> {
        idx: usize,
        params: &'a Params,
    }

    impl<'a> Iterator for ParamsIter<'a> {
        type Item = (&'a str, &'a str);

        #[inline]
        fn next(&mut self) -> Option<(&'a str, &'a str)> {
            if self.idx < self.params.len() {
                let idx = self.idx;
                let res = match self.params.segments[idx].1 {
                    ParamItem::Static(ref s) => &s,
                    ParamItem::UrlSegment(s, e) => {
                        &self.params.url.path()[(s as usize)..(e as usize)]
                    }
                };
                self.idx += 1;
                return Some((&self.params.segments[idx].0, res));
            }
            None
        }
    }

    impl<'a> Index<&'a str> for Params {
        type Output = str;

        fn index(&self, name: &'a str) -> &str {
            self.get(name)
                .expect("Value for parameter is not available")
        }
    }

    impl Index<usize> for Params {
        type Output = str;

        fn index(&self, idx: usize) -> &str {
            match self.segments[idx].1 {
                ParamItem::Static(ref s) => &s,
                ParamItem::UrlSegment(s, e) => &self.url.path()[(s as usize)..(e as usize)],
            }
        }
    }

    /// Creates a `PathBuf` from a path parameter. The returned `PathBuf` is
    /// percent-decoded. If a segment is equal to "..", the previous segment (if
    /// any) is skipped.
    ///
    /// For security purposes, if a segment meets any of the following conditions,
    /// an `Err` is returned indicating the condition met:
    ///
    ///   * Decoded segment starts with any of: `.` (except `..`), `*`
    ///   * Decoded segment ends with any of: `:`, `>`, `<`
    ///   * Decoded segment contains any of: `/`
    ///   * On Windows, decoded segment contains any of: '\'
    ///   * Percent-encoding results in invalid UTF8.
    ///
    /// As a result of these conditions, a `PathBuf` parsed from request path
    /// parameter is safe to interpolate within, or use as a suffix of, a path
    /// without additional checks.
    impl FromParam for PathBuf {
        type Err = UriSegmentError;

        fn from_param(val: &str) -> Result<PathBuf, UriSegmentError> {
            let mut buf = PathBuf::new();
            for segment in val.split('/') {
                if segment == ".." {
                    buf.pop();
                } else if segment.starts_with('.') {
                    return Err(UriSegmentError::BadStart('.'));
                } else if segment.starts_with('*') {
                    return Err(UriSegmentError::BadStart('*'));
                } else if segment.ends_with(':') {
                    return Err(UriSegmentError::BadEnd(':'));
                } else if segment.ends_with('>') {
                    return Err(UriSegmentError::BadEnd('>'));
                } else if segment.ends_with('<') {
                    return Err(UriSegmentError::BadEnd('<'));
                } else if segment.is_empty() {
                    continue;
                } else if cfg!(windows) && segment.contains('\\') {
                    return Err(UriSegmentError::BadChar('\\'));
                } else {
                    buf.push(segment)
                }
            }

            Ok(buf)
        }
    }

    macro_rules! FROM_STR {
        ($type:ty) => {
            impl FromParam for $type {
                type Err = InternalError<<$type as FromStr>::Err>;
                fn from_param(val: &str) -> Result<Self, Self::Err> {
                    <$type as FromStr>::from_str(val)
                        .map_err(|e| InternalError::new(e, StatusCode::BAD_REQUEST))
                }
            }
        };
    }

    FROM_STR!(u8);
    FROM_STR!(u16);
    FROM_STR!(u32);
    FROM_STR!(u64);
    FROM_STR!(usize);
    FROM_STR!(i8);
    FROM_STR!(i16);
    FROM_STR!(i32);
    FROM_STR!(i64);
    FROM_STR!(isize);
    FROM_STR!(f32);
    FROM_STR!(f64);
    FROM_STR!(String);
    FROM_STR!(std::net::IpAddr);
    FROM_STR!(std::net::Ipv4Addr);
    FROM_STR!(std::net::Ipv6Addr);
    FROM_STR!(std::net::SocketAddr);
    FROM_STR!(std::net::SocketAddrV4);
    FROM_STR!(std::net::SocketAddrV6);

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::iter::FromIterator;

        #[test]
        fn test_path_buf() {
            assert_eq!(
                PathBuf::from_param("/test/.tt"),
                Err(UriSegmentError::BadStart('.'))
            );
            assert_eq!(
                PathBuf::from_param("/test/*tt"),
                Err(UriSegmentError::BadStart('*'))
            );
            assert_eq!(
                PathBuf::from_param("/test/tt:"),
                Err(UriSegmentError::BadEnd(':'))
            );
            assert_eq!(
                PathBuf::from_param("/test/tt<"),
                Err(UriSegmentError::BadEnd('<'))
            );
            assert_eq!(
                PathBuf::from_param("/test/tt>"),
                Err(UriSegmentError::BadEnd('>'))
            );
            assert_eq!(
                PathBuf::from_param("/seg1/seg2/"),
                Ok(PathBuf::from_iter(vec!["seg1", "seg2"]))
            );
            assert_eq!(
                PathBuf::from_param("/seg1/../seg2/"),
                Ok(PathBuf::from_iter(vec!["seg2"]))
            );
        }
    }

# 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`)