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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use std::borrow::Cow;

use crate::RawStr;
use crate::ext::IntoOwned;
use crate::uri::{Authority, Data, Origin, Absolute, Asterisk};
use crate::uri::{Path, Query, Error, as_utf8_unchecked, fmt};
use crate::parse::{Extent, IndexedStr};

/// A URI-reference with optional scheme, authority, relative path, query, and
/// fragment parts.
///
/// # Structure
///
/// The following diagram illustrates the syntactic structure of a URI reference
/// with all optional parts:
///
/// ```text
///  http://user:pass@domain.com:4444/foo/bar?some=query#and-fragment
///  |--|  |------------------------||------| |--------| |----------|
/// scheme          authority          path      query     fragment
/// ```
///
/// All parts are optional. When a scheme and authority are not present, the
/// path may be relative: `foo/bar?baz#cat`.
///
/// # Conversion
///
/// All other URI types ([`Origin`], [`Absolute`], and so on) are valid URI
/// references. As such, conversion between the types is lossless:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::http::uri::Reference;
///
/// let absolute = uri!("http://rocket.rs");
/// let reference: Reference = absolute.into();
/// assert_eq!(reference.scheme(), Some("http"));
/// assert_eq!(reference.authority().unwrap().host(), "rocket.rs");
///
/// let origin = uri!("/foo/bar");
/// let reference: Reference = origin.into();
/// assert_eq!(reference.path(), "/foo/bar");
/// ```
///
/// Note that `uri!()` macro _always_ prefers the more specific URI variant to
/// `Reference` when possible, as is demonstrated above for `absolute` and
/// `origin`.
///
/// # (De)serialization
///
/// `Reference` is both `Serialize` and `Deserialize`:
///
/// ```rust
/// # #[cfg(feature = "serde")] mod serde {
/// # use serde_ as serde;
/// use serde::{Serialize, Deserialize};
/// use rocket::http::uri::Reference;
///
/// #[derive(Deserialize, Serialize)]
/// # #[serde(crate = "serde_")]
/// struct UriOwned {
///     uri: Reference<'static>,
/// }
///
/// #[derive(Deserialize, Serialize)]
/// # #[serde(crate = "serde_")]
/// struct UriBorrowed<'a> {
///     uri: Reference<'a>,
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Reference<'a> {
    source: Option<Cow<'a, str>>,
    scheme: Option<IndexedStr<'a>>,
    authority: Option<Authority<'a>>,
    path: Data<'a, fmt::Path>,
    query: Option<Data<'a, fmt::Query>>,
    fragment: Option<IndexedStr<'a>>,
}

impl<'a> Reference<'a> {
    #[inline]
    pub(crate) unsafe fn raw(
        source: Cow<'a, [u8]>,
        scheme: Option<Extent<&'a [u8]>>,
        authority: Option<Authority<'a>>,
        path: Extent<&'a [u8]>,
        query: Option<Extent<&'a [u8]>>,
        fragment: Option<Extent<&'a [u8]>>,
    ) -> Reference<'a> {
        Reference {
            source: Some(as_utf8_unchecked(source)),
            scheme: scheme.map(|s| s.into()),
            authority,
            path: Data::raw(path),
            query: query.map(Data::raw),
            fragment: fragment.map(|f| f.into()),
        }
    }

    /// PRIVATE. Used during test.
    #[cfg(test)]
    pub fn new(
        scheme: impl Into<Option<&'a str>>,
        auth: impl Into<Option<Authority<'a>>>,
        path: &'a str,
        query: impl Into<Option<&'a str>>,
        frag: impl Into<Option<&'a str>>,
    ) -> Reference<'a> {
        Reference::const_new(scheme.into(), auth.into(), path, query.into(), frag.into())
    }

    /// PRIVATE. Used by codegen.
    #[doc(hidden)]
    pub const fn const_new(
        scheme: Option<&'a str>,
        authority: Option<Authority<'a>>,
        path: &'a str,
        query: Option<&'a str>,
        fragment: Option<&'a str>,
    ) -> Reference<'a> {
        Reference {
            source: None,
            scheme: match scheme {
                Some(scheme) => Some(IndexedStr::Concrete(Cow::Borrowed(scheme))),
                None => None
            },
            authority,
            path: Data {
                value: IndexedStr::Concrete(Cow::Borrowed(path)),
                decoded_segments: state::InitCell::new(),
            },
            query: match query {
                Some(query) => Some(Data {
                    value: IndexedStr::Concrete(Cow::Borrowed(query)),
                    decoded_segments: state::InitCell::new(),
                }),
                None => None,
            },
            fragment: match fragment {
                Some(frag) => Some(IndexedStr::Concrete(Cow::Borrowed(frag))),
                None => None,
            },
        }
    }

    /// Parses the string `string` into an `Reference`. Parsing will never
    /// allocate. Returns an `Error` if `string` is not a valid origin URI.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Reference;
    ///
    /// // Parse a valid URI reference.
    /// let uri = Reference::parse("/a/b/c?query").expect("valid URI");
    /// assert_eq!(uri.path(), "/a/b/c");
    /// assert_eq!(uri.query().unwrap(), "query");
    ///
    /// // Invalid URIs fail to parse.
    /// Reference::parse("foo bar").expect_err("invalid URI");
    ///
    /// // Prefer to use `uri!()` when the input is statically known:
    /// let uri = uri!("/a/b/c?query#fragment");
    /// assert_eq!(uri.path(), "/a/b/c");
    /// assert_eq!(uri.query().unwrap(), "query");
    /// assert_eq!(uri.fragment().unwrap(), "fragment");
    /// ```
    pub fn parse(string: &'a str) -> Result<Reference<'a>, Error<'a>> {
        crate::parse::uri::reference_from_str(string)
    }

    /// Parses the string `string` into a `Reference`. Allocates minimally on
    /// success and error.
    ///
    /// This method should be used instead of [`Reference::parse()`] when the
    /// source URI is already a `String`. Returns an `Error` if `string` is not
    /// a valid URI reference.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate rocket;
    /// use rocket::http::uri::Reference;
    ///
    /// let source = format!("/foo?{}#3", 2);
    /// let uri = Reference::parse_owned(source).unwrap();
    /// assert_eq!(uri.path(), "/foo");
    /// assert_eq!(uri.query().unwrap(), "2");
    /// assert_eq!(uri.fragment().unwrap(), "3");
    /// ```
    // TODO: Avoid all allocations.
    pub fn parse_owned(string: String) -> Result<Reference<'static>, Error<'static>> {
        let uri_ref = Reference::parse(&string).map_err(|e| e.into_owned())?;
        debug_assert!(uri_ref.source.is_some(), "Reference parsed w/o source");

        Ok(Reference {
            scheme: uri_ref.scheme.into_owned(),
            authority: uri_ref.authority.into_owned(),
            path: uri_ref.path.into_owned(),
            query: uri_ref.query.into_owned(),
            fragment: uri_ref.fragment.into_owned(),
            source: Some(Cow::Owned(string)),
        })
    }

    /// Returns the scheme. If `Some`, is non-empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("http://rocket.rs?foo#bar");
    /// assert_eq!(uri.scheme(), Some("http"));
    ///
    /// let uri = uri!("ftp:/?foo#bar");
    /// assert_eq!(uri.scheme(), Some("ftp"));
    ///
    /// let uri = uri!("?foo#bar");
    /// assert_eq!(uri.scheme(), None);
    /// ```
    #[inline]
    pub fn scheme(&self) -> Option<&str> {
        self.scheme.as_ref().map(|s| s.from_cow_source(&self.source))
    }

    /// Returns the authority part.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("http://rocket.rs:4444?foo#bar");
    /// let auth = uri!("rocket.rs:4444");
    /// assert_eq!(uri.authority().unwrap(), &auth);
    ///
    /// let uri = uri!("?foo#bar");
    /// assert_eq!(uri.authority(), None);
    /// ```
    #[inline(always)]
    pub fn authority(&self) -> Option<&Authority<'a>> {
        self.authority.as_ref()
    }

    /// Returns the path part. May be empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("http://rocket.rs/guide?foo#bar");
    /// assert_eq!(uri.path(), "/guide");
    /// ```
    #[inline(always)]
    pub fn path(&self) -> Path<'_> {
        Path { source: &self.source, data: &self.path }
    }

    /// Returns the query part. May be empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("http://rocket.rs/guide");
    /// assert!(uri.query().is_none());
    ///
    /// let uri = uri!("http://rocket.rs/guide?");
    /// assert_eq!(uri.query().unwrap(), "");
    ///
    /// let uri = uri!("http://rocket.rs/guide?foo#bar");
    /// assert_eq!(uri.query().unwrap(), "foo");
    ///
    /// let uri = uri!("http://rocket.rs/guide?q=bar");
    /// assert_eq!(uri.query().unwrap(), "q=bar");
    /// ```
    #[inline(always)]
    pub fn query(&self) -> Option<Query<'_>> {
        self.query.as_ref().map(|data| Query { source: &self.source, data })
    }

    /// Returns the fragment part, if any.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// let uri = uri!("http://rocket.rs/guide?foo#bar");
    /// assert_eq!(uri.fragment().unwrap(), "bar");
    ///
    /// // Fragment parts aren't normalized away, unlike query parts.
    /// let uri = uri!("http://rocket.rs/guide?foo#");
    /// assert_eq!(uri.fragment().unwrap(), "");
    /// ```
    #[inline(always)]
    pub fn fragment(&self) -> Option<&RawStr> {
        self.fragment.as_ref()
            .map(|frag| frag.from_cow_source(&self.source).into())
    }

    /// Returns `true` if `self` is normalized. Otherwise, returns `false`.
    ///
    /// Normalization for a URI reference is equivalent to normalization for an
    /// absolute URI. See [`Absolute#normalization`] for more information on
    /// what it means for an absolute URI to be normalized.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate rocket;
    /// use rocket::http::uri::Reference;
    ///
    /// assert!(Reference::parse("foo/bar").unwrap().is_normalized());
    /// assert!(Reference::parse("foo/bar#").unwrap().is_normalized());
    /// assert!(Reference::parse("http://").unwrap().is_normalized());
    /// assert!(Reference::parse("http://foo.rs/foo/bar").unwrap().is_normalized());
    /// assert!(Reference::parse("foo:bar#baz").unwrap().is_normalized());
    /// assert!(Reference::parse("http://rocket.rs#foo").unwrap().is_normalized());
    /// assert!(Reference::parse("http://?").unwrap().is_normalized());
    /// assert!(Reference::parse("git://rocket.rs/").unwrap().is_normalized());
    /// assert!(Reference::parse("http://rocket.rs?#foo").unwrap().is_normalized());
    /// assert!(Reference::parse("http://rocket.rs#foo").unwrap().is_normalized());
    ///
    /// assert!(!Reference::parse("http:/foo//bar").unwrap().is_normalized());
    /// assert!(!Reference::parse("foo:bar?baz&&bop#c").unwrap().is_normalized());
    ///
    /// // Recall that `uri!()` normalizes static input.
    /// assert!(uri!("http:/foo//bar").is_normalized());
    /// assert!(uri!("foo:bar?baz&&bop#c").is_normalized());
    /// assert!(uri!("http://rocket.rs///foo////bar#cat").is_normalized());
    /// ```
    pub fn is_normalized(&self) -> bool {
        let normalized_query = self.query().map_or(true, |q| q.is_normalized());
        if self.authority().is_some() && !self.path().is_empty() {
            self.path().is_normalized(true) && normalized_query
        } else {
            self.path().is_normalized(false) && normalized_query
        }
    }

    /// Normalizes `self` in-place. Does nothing if `self` is already
    /// normalized.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::http::uri::Reference;
    ///
    /// let mut uri = Reference::parse("git://rocket.rs/").unwrap();
    /// assert!(uri.is_normalized());
    ///
    /// let mut uri = Reference::parse("http:/foo//bar?baz&&#cat").unwrap();
    /// assert!(!uri.is_normalized());
    /// uri.normalize();
    /// assert!(uri.is_normalized());
    ///
    /// let mut uri = Reference::parse("foo:bar?baz&&bop").unwrap();
    /// assert!(!uri.is_normalized());
    /// uri.normalize();
    /// assert!(uri.is_normalized());
    /// ```
    pub fn normalize(&mut self) {
        if self.authority().is_some() && !self.path().is_empty() {
            if !self.path().is_normalized(true) {
                self.path = self.path().to_normalized(true, true);
            }
        } else {
            if !self.path().is_normalized(false) {
                self.path = self.path().to_normalized(false, true);
            }
        }

        if let Some(query) = self.query() {
            if !query.is_normalized() {
                self.query = Some(query.to_normalized());
            }
        }
    }

    /// Normalizes `self`. This is a no-op if `self` is already normalized.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::http::uri::Reference;
    ///
    /// let mut uri = Reference::parse("git://rocket.rs/").unwrap();
    /// assert!(uri.is_normalized());
    /// assert!(uri.into_normalized().is_normalized());
    ///
    /// let mut uri = Reference::parse("http:/foo//bar?baz&&#cat").unwrap();
    /// assert!(!uri.is_normalized());
    /// assert!(uri.into_normalized().is_normalized());
    ///
    /// let mut uri = Reference::parse("foo:bar?baz&&bop").unwrap();
    /// assert!(!uri.is_normalized());
    /// assert!(uri.into_normalized().is_normalized());
    /// ```
    pub fn into_normalized(mut self) -> Self {
        self.normalize();
        self
    }

    #[allow(unused)]
    pub(crate) fn set_path<P>(&mut self, path: P)
        where P: Into<Cow<'a, str>>
    {
        self.path = Data::new(path.into());
    }

    /// Returns the concrete path and query.
    pub(crate) fn with_query_fragment_of(mut self, other: Reference<'a>) -> Self {
        if let Some(query) = other.query {
            if self.query().is_none() {
                self.query = Some(Data::new(query.value.into_concrete(&self.source)));
            }
        }

        if let Some(frag) = other.fragment {
            if self.fragment().is_none() {
                self.fragment = Some(IndexedStr::from(frag.into_concrete(&self.source)));
            }
        }

        self
    }
}

impl_traits!(Reference, authority, scheme, path, query, fragment);

impl_serde!(Reference<'a>, "a URI-reference");

impl<'a> From<Absolute<'a>> for Reference<'a> {
    fn from(absolute: Absolute<'a>) -> Self {
        Reference {
            source: absolute.source,
            scheme: Some(absolute.scheme),
            authority: absolute.authority,
            path: absolute.path,
            query: absolute.query,
            fragment: None,
        }
    }
}

impl<'a> From<Origin<'a>> for Reference<'a> {
    fn from(origin: Origin<'a>) -> Self {
        Reference {
            source: origin.source,
            scheme: None,
            authority: None,
            path: origin.path,
            query: origin.query,
            fragment: None,
        }
    }
}

impl<'a> From<Authority<'a>> for Reference<'a> {
    fn from(authority: Authority<'a>) -> Self {
        Reference {
            source: match authority.source {
                Some(Cow::Borrowed(b)) => Some(Cow::Borrowed(b)),
                _ => None
            },
            authority: Some(authority),
            scheme: None,
            path: Data::new(""),
            query: None,
            fragment: None,
        }
    }
}

impl From<Asterisk> for Reference<'_> {
    fn from(_: Asterisk) -> Self {
        Reference {
            source: None,
            authority: None,
            scheme: None,
            path: Data::new("*"),
            query: None,
            fragment: None,
        }
    }
}

impl std::fmt::Display for Reference<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(scheme) = self.scheme() {
            write!(f, "{}:", scheme)?;
        }

        if let Some(authority) = self.authority() {
            write!(f, "//{}", authority)?;
        }

        write!(f, "{}", self.path())?;

        if let Some(query) = self.query() {
            write!(f, "?{}", query)?;
        }

        if let Some(frag) = self.fragment() {
            write!(f, "#{}", frag)?;
        }

        Ok(())
    }
}