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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use std::hash::Hash;
use std::borrow::Cow;
use std::fmt::Write;

use state::Storage;

use crate::{RawStr, ext::IntoOwned};
use crate::uri::Segments;
use crate::uri::fmt::{self, Part};
use crate::parse::{IndexedStr, Extent};

// INTERNAL DATA STRUCTURE.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct Data<'a, P: Part> {
    pub(crate) value: IndexedStr<'a>,
    pub(crate) decoded_segments: Storage<Vec<P::Raw>>,
}

impl<'a, P: Part> Data<'a, P> {
    pub(crate) fn raw(value: Extent<&'a [u8]>) -> Self {
        Data { value: value.into(), decoded_segments: Storage::new() }
    }

    // INTERNAL METHOD.
    #[doc(hidden)]
    pub fn new<S: Into<Cow<'a, str>>>(value: S) -> Self {
        Data {
            value: IndexedStr::from(value.into()),
            decoded_segments: Storage::new(),
        }
    }
}

/// A URI path: `/foo/bar`, `foo/bar`, etc.
#[derive(Debug, Clone, Copy)]
pub struct Path<'a> {
    pub(crate) source: &'a Option<Cow<'a, str>>,
    pub(crate) data: &'a Data<'a, fmt::Path>,
}

/// A URI query: `?foo&bar`.
#[derive(Debug, Clone, Copy)]
pub struct Query<'a> {
    pub(crate) source: &'a Option<Cow<'a, str>>,
    pub(crate) data: &'a Data<'a, fmt::Query>,
}

fn decode_to_indexed_str<P: fmt::Part>(
    value: &RawStr,
    (indexed, source): (&IndexedStr<'_>, &RawStr)
) -> IndexedStr<'static> {
    let decoded = match P::KIND {
        fmt::Kind::Path => value.percent_decode_lossy(),
        fmt::Kind::Query => value.url_decode_lossy(),
    };

    match decoded {
        Cow::Borrowed(b) if indexed.is_indexed() => {
            let indexed = IndexedStr::checked_from(b, source.as_str());
            debug_assert!(indexed.is_some());
            indexed.unwrap_or(IndexedStr::from(Cow::Borrowed("")))
        }
        cow => IndexedStr::from(Cow::Owned(cow.into_owned())),
    }
}

impl<'a> Path<'a> {
    /// Returns the raw path value.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("/foo%20bar%2dbaz");
    /// assert_eq!(uri.path(), "/foo%20bar%2dbaz");
    /// assert_eq!(uri.path().raw(), "/foo%20bar%2dbaz");
    /// ```
    pub fn raw(&self) -> &'a RawStr {
        self.data.value.from_cow_source(&self.source).into()
    }

    /// Returns the raw, undecoded path value as an `&str`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("/foo%20bar%2dbaz");
    /// assert_eq!(uri.path(), "/foo%20bar%2dbaz");
    /// assert_eq!(uri.path().as_str(), "/foo%20bar%2dbaz");
    /// ```
    pub fn as_str(&self) -> &'a str {
        self.raw().as_str()
    }

    /// Whether `self` is normalized, i.e, it has no empty segments.
    ///
    /// If `absolute`, then a starting  `/` is required.
    pub(crate) fn is_normalized(&self, absolute: bool) -> bool {
        (!absolute || self.raw().starts_with('/'))
            && self.raw_segments().all(|s| !s.is_empty())
    }

    /// Normalizes `self`. If `absolute`, a starting  `/` is required.
    pub(crate) fn to_normalized(&self, absolute: bool) -> Data<'static, fmt::Path> {
        let mut path = String::with_capacity(self.raw().len());
        let absolute = absolute || self.raw().starts_with('/');
        for (i, seg) in self.raw_segments().filter(|s| !s.is_empty()).enumerate() {
            if absolute || i != 0 { path.push('/'); }
            let _ = write!(path, "{}", seg);
        }

        if path.is_empty() && absolute {
            path.push('/');
        }

        Data {
            value: IndexedStr::from(Cow::Owned(path)),
            decoded_segments: Storage::new(),
        }
    }

    /// Returns an iterator over the raw, undecoded segments. Segments may be
    /// empty.
    ///
    /// ### Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Origin;
    ///
    /// let uri = Origin::parse("/").unwrap();
    /// assert_eq!(uri.path().raw_segments().count(), 0);
    ///
    /// let uri = Origin::parse("//").unwrap();
    /// let segments: Vec<_> = uri.path().raw_segments().collect();
    /// assert_eq!(segments, &["", ""]);
    ///
    /// // Recall that `uri!()` normalizes static inputs.
    /// let uri = uri!("//");
    /// assert_eq!(uri.path().raw_segments().count(), 0);
    ///
    /// let uri = Origin::parse("/a").unwrap();
    /// let segments: Vec<_> = uri.path().raw_segments().collect();
    /// assert_eq!(segments, &["a"]);
    ///
    /// let uri = Origin::parse("/a//b///c/d?query&param").unwrap();
    /// let segments: Vec<_> = uri.path().raw_segments().collect();
    /// assert_eq!(segments, &["a", "", "b", "", "", "c", "d"]);
    /// ```
    #[inline(always)]
    pub fn raw_segments(&self) -> impl Iterator<Item = &'a RawStr> {
        let path = match self.raw() {
            p if p.is_empty() || p == "/" => None,
            p if p.starts_with(fmt::Path::DELIMITER) => Some(&p[1..]),
            p => Some(p)
        };

        path.map(|p| p.split(fmt::Path::DELIMITER))
            .into_iter()
            .flatten()
    }

    /// Returns a (smart) iterator over the non-empty, percent-decoded segments.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Origin;
    ///
    /// let uri = Origin::parse("/a%20b/b%2Fc/d//e?query=some").unwrap();
    /// let path_segs: Vec<&str> = uri.path().segments().collect();
    /// assert_eq!(path_segs, &["a b", "b/c", "d", "e"]);
    /// ```
    pub fn segments(&self) -> Segments<'a, fmt::Path> {
        let cached = self.data.decoded_segments.get_or_set(|| {
            let (indexed, path) = (&self.data.value, self.raw());
            self.raw_segments()
                .filter(|r| !r.is_empty())
                .map(|s| decode_to_indexed_str::<fmt::Path>(s, (indexed, path)))
                .collect()
        });

        Segments::new(self.raw(), cached)
    }
}

impl<'a> Query<'a> {
    /// Returns the raw, undecoded query value.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("/foo?baz+bar");
    /// assert_eq!(uri.query().unwrap(), "baz+bar");
    /// assert_eq!(uri.query().unwrap().raw(), "baz+bar");
    /// ```
    pub fn raw(&self) -> &'a RawStr {
        self.data.value.from_cow_source(&self.source).into()
    }

    /// Returns the raw, undecoded query value as an `&str`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("/foo/bar?baz+bar");
    /// assert_eq!(uri.query().unwrap(), "baz+bar");
    /// assert_eq!(uri.query().unwrap().as_str(), "baz+bar");
    /// ```
    pub fn as_str(&self) -> &'a str {
        self.raw().as_str()
    }

    /// Whether `self` is normalized, i.e, it has no empty segments.
    pub(crate) fn is_normalized(&self) -> bool {
        !self.is_empty() && self.raw_segments().all(|s| !s.is_empty())
    }

    /// Normalizes `self`.
    pub(crate) fn to_normalized(&self) -> Option<Data<'static, fmt::Query>> {
        let mut query = String::with_capacity(self.raw().len());
        for (i, seg) in self.raw_segments().filter(|s| !s.is_empty()).enumerate() {
            if i != 0 { query.push('&'); }
            let _ = write!(query, "{}", seg);
        }

        if query.is_empty() {
            return None;
        }

        Some(Data {
            value: IndexedStr::from(Cow::Owned(query)),
            decoded_segments: Storage::new(),
        })
    }

    /// Returns an iterator over the non-empty, undecoded `(name, value)` pairs
    /// of this query. If there is no query, the iterator is empty. Segments may
    /// be empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Origin;
    ///
    /// let uri = Origin::parse("/").unwrap();
    /// assert!(uri.query().is_none());
    ///
    /// let uri = Origin::parse("/?a=b&dog").unwrap();
    /// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
    /// assert_eq!(query_segs, &["a=b", "dog"]);
    ///
    /// // This is not normalized, so the query is `""`, the empty string.
    /// let uri = Origin::parse("/?&").unwrap();
    /// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
    /// assert_eq!(query_segs, &["", ""]);
    ///
    /// // Recall that `uri!()` normalizes.
    /// let uri = uri!("/?&");
    /// assert!(uri.query().is_none());
    ///
    /// // These are raw and undecoded. Use `segments()` for decoded variant.
    /// let uri = Origin::parse("/foo/bar?a+b%2F=some+one%40gmail.com&&%26%3D2").unwrap();
    /// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
    /// assert_eq!(query_segs, &["a+b%2F=some+one%40gmail.com", "", "%26%3D2"]);
    /// ```
    #[inline]
    pub fn raw_segments(&self) -> impl Iterator<Item = &'a RawStr> {
        let query = match self.raw() {
            q if q.is_empty() => None,
            q => Some(q)
        };

        query.map(|p| p.split(fmt::Query::DELIMITER))
            .into_iter()
            .flatten()
    }

    /// Returns a (smart) iterator over the non-empty, url-decoded `(name,
    /// value)` pairs of this query. If there is no query, the iterator is
    /// empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Origin;
    ///
    /// let uri = Origin::parse("/").unwrap();
    /// assert!(uri.query().is_none());
    ///
    /// let uri = Origin::parse("/foo/bar?a+b%2F=some+one%40gmail.com&&%26%3D2").unwrap();
    /// let query_segs: Vec<_> = uri.query().unwrap().segments().collect();
    /// assert_eq!(query_segs, &[("a b/", "some one@gmail.com"), ("&=2", "")]);
    /// ```
    pub fn segments(&self) -> Segments<'a, fmt::Query> {
        let cached = self.data.decoded_segments.get_or_set(|| {
            let (indexed, query) = (&self.data.value, self.raw());
            self.raw_segments()
                .filter(|s| !s.is_empty())
                .map(|s| s.split_at_byte(b'='))
                .map(|(k, v)| {
                    let key = decode_to_indexed_str::<fmt::Query>(k, (indexed, query));
                    let val = decode_to_indexed_str::<fmt::Query>(v, (indexed, query));
                    (key, val)
                })
                .collect()
        });

        Segments::new(self.raw(), cached)
    }
}

macro_rules! impl_partial_eq {
    ($A:ty = $B:ty) => (
        impl PartialEq<$A> for $B {
            #[inline(always)]
            fn eq(&self, other: &$A) -> bool {
                let left: &RawStr = self.as_ref();
                let right: &RawStr = other.as_ref();
                left == right
            }
        }
    )
}

macro_rules! impl_traits {
    ($T:ident) => (
        impl Hash for $T<'_> {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.raw().hash(state);
            }
        }

        impl Eq for $T<'_> { }

        impl IntoOwned for Data<'_, fmt::$T> {
            type Owned = Data<'static, fmt::$T>;

            fn into_owned(self) -> Self::Owned {
                Data {
                    value: self.value.into_owned(),
                    decoded_segments: self.decoded_segments.map(|v| v.into_owned()),
                }
            }
        }

        impl std::ops::Deref for $T<'_> {
            type Target = RawStr;

            fn deref(&self) -> &Self::Target {
                self.raw()
            }
        }

        impl AsRef<RawStr> for $T<'_> {
            fn as_ref(&self) -> &RawStr {
                self.raw()
            }
        }

        impl std::fmt::Display for $T<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.raw())
            }
        }

        impl_partial_eq!($T<'_> = $T<'_>);
        impl_partial_eq!(str = $T<'_>);
        impl_partial_eq!(&str = $T<'_>);
        impl_partial_eq!($T<'_> = str);
        impl_partial_eq!($T<'_> = &str);
        impl_partial_eq!(RawStr = $T<'_>);
        impl_partial_eq!(&RawStr = $T<'_>);
        impl_partial_eq!($T<'_> = RawStr);
        impl_partial_eq!($T<'_> = &RawStr);
    )
}

impl_traits!(Path);
impl_traits!(Query);