Struct rocket::http::uri::Origin

pub struct Origin<'a> { /* private fields */ }
Expand description

A URI with an absolute path and optional query: /path?query.

Origin URIs are the primary type of URI encountered in Rocket applications. They are also the simplest type of URIs, made up of only a path and an optional query.

§Structure

The following diagram illustrates the syntactic structure of an origin URI:

/first_segment/second_segment/third?optional=query
|---------------------------------| |------------|
                path                    query

The URI must begin with a /, can be followed by any number of segments, and an optional ? query separator and query string.

§Normalization

Rocket prefers, and will sometimes require, origin URIs to be normalized. A normalized origin URI is a valid origin URI that contains zero empty segments except when there are no segments.

As an example, the following URIs are all valid, normalized URIs:

"/",
"/a/b/c",
"/a/b/c?q",
"/some%20thing"

By contrast, the following are valid but abnormal URIs:

"//",               // one empty segment
"/a/b/",            // trailing empty segment
"/a/ab//c//d"       // two empty segments

The Origin::to_normalized() method can be used to normalize any Origin:

// abnormal versions
"//", "/a/b/", "/a/ab//c//d"

// normalized versions
"/",  "/a/b",  "/a/ab/c/d"

Implementations§

§

impl<'a> Origin<'a>

pub fn parse(string: &'a str) -> Result<Origin<'a>, Error<'a>>

Parses the string string into an Origin. Parsing will never allocate. Returns an Error if string is not a valid origin URI.

§Example
use rocket::http::uri::Origin;

// Parse a valid origin URI.
let uri = Origin::parse("/a/b/c?query").expect("valid URI");
assert_eq!(uri.path(), "/a/b/c");
assert_eq!(uri.query(), Some("query"));

// Invalid URIs fail to parse.
Origin::parse("foo bar").expect_err("invalid URI");

pub fn parse_owned(string: String) -> Result<Origin<'static>, Error<'static>>

Parses the string string into an Origin. Parsing will never allocate on success. May allocate on error.

This method should be used instead of Origin::parse() when the source URI is already a String. Returns an Error if string is not a valid origin URI.

§Example
use rocket::http::uri::Origin;

let source = format!("/foo/{}/three", 2);
let uri = Origin::parse_owned(source).expect("valid URI");
assert_eq!(uri.path(), "/foo/2/three");
assert_eq!(uri.query(), None);

pub fn is_normalized(&self) -> bool

Returns true if self is normalized. Otherwise, returns false.

See Normalization for more information on what it means for an origin URI to be normalized.

§Example
use rocket::http::uri::Origin;

let normal = Origin::parse("/").unwrap();
assert!(normal.is_normalized());

let normal = Origin::parse("/a/b/c").unwrap();
assert!(normal.is_normalized());

let abnormal = Origin::parse("/a/b/c//d").unwrap();
assert!(!abnormal.is_normalized());

pub fn to_normalized(&self) -> Origin<'_>

Normalizes self.

See Normalization for more information on what it means for an origin URI to be normalized.

§Example
use rocket::http::uri::Origin;

let abnormal = Origin::parse("/a/b/c//d").unwrap();
assert!(!abnormal.is_normalized());

let normalized = abnormal.to_normalized();
assert!(normalized.is_normalized());
assert_eq!(normalized, Origin::parse("/a/b/c/d").unwrap());

pub fn path(&self) -> &str

Returns the path part of this URI.

§Examples

A URI with only a path:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c").unwrap();
assert_eq!(uri.path(), "/a/b/c");

A URI with a query:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c?name=bob").unwrap();
assert_eq!(uri.path(), "/a/b/c");

pub fn map_path<F>(&self, f: F) -> Option<Origin<'a>>
where F: FnOnce(&str) -> String,

Applies the function f to the internal path and returns a new Origin with the new path. If the path returned from f is invalid, returns None. Otherwise, returns Some, even if the new path is abnormal.

§Examples

Affix a trailing slash if one isn’t present.

use rocket::http::uri::Origin;

let old_uri = Origin::parse("/a/b/c").unwrap();
let expected_uri = Origin::parse("/a/b/c/").unwrap();
assert_eq!(old_uri.map_path(|p| p.to_owned() + "/"), Some(expected_uri));

let old_uri = Origin::parse("/a/b/c/").unwrap();
let expected_uri = Origin::parse("/a/b/c//").unwrap();
assert_eq!(old_uri.map_path(|p| p.to_owned() + "/"), Some(expected_uri));

pub fn query(&self) -> Option<&str>

Returns the query part of this URI without the question mark, if there is any.

§Examples

A URI with a query part:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c?alphabet=true").unwrap();
assert_eq!(uri.query(), Some("alphabet=true"));

A URI without the query part:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c").unwrap();
assert_eq!(uri.query(), None);

pub fn clear_query(&mut self)

Removes the query part of this URI, if there is any.

§Example
use rocket::http::uri::Origin;

let mut uri = Origin::parse("/a/b/c?query=some").unwrap();
assert_eq!(uri.query(), Some("query=some"));

uri.clear_query();
assert_eq!(uri.query(), None);

pub fn segments(&self) -> Segments<'_>

Returns an iterator over the segments of the path in this URI. Skips empty segments.

§Examples

A valid URI with only non-empty segments:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c?a=true").unwrap();
for (i, segment) in uri.segments().enumerate() {
    match i {
        0 => assert_eq!(segment, "a"),
        1 => assert_eq!(segment, "b"),
        2 => assert_eq!(segment, "c"),
        _ => unreachable!("only three segments")
    }
}

A URI with empty segments:

use rocket::http::uri::Origin;

let uri = Origin::parse("///a//b///c////d?query&param").unwrap();
for (i, segment) in uri.segments().enumerate() {
    match i {
        0 => assert_eq!(segment, "a"),
        1 => assert_eq!(segment, "b"),
        2 => assert_eq!(segment, "c"),
        3 => assert_eq!(segment, "d"),
        _ => unreachable!("only four segments")
    }
}

pub fn segment_count(&self) -> usize

Returns the number of segments in the URI. Empty segments, which are invalid according to RFC#3986, are not counted.

The segment count is cached after the first invocation. As a result, this function is O(1) after the first invocation, and O(n) before.

§Examples

A valid URI with only non-empty segments:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b/c").unwrap();
assert_eq!(uri.segment_count(), 3);

A URI with empty segments:

use rocket::http::uri::Origin;

let uri = Origin::parse("/a/b//c/d///e").unwrap();
assert_eq!(uri.segment_count(), 5);

Trait Implementations§

§

impl<'a> Clone for Origin<'a>

§

fn clone(&self) -> Origin<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<'a> Debug for Origin<'a>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a> Display for Origin<'a>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a> From<Origin<'a>> for Uri<'a>

§

fn from(other: Origin<'a>) -> Uri<'a>

Converts to this type from the input type.
source§

impl<'a, 'r> FromRequest<'a, 'r> for &'a Origin<'a>

source§

type Error = !

The associated error to be returned if derivation fails.
source§

fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error>

Derives an instance of Self from the incoming request metadata. Read more
§

impl<'a> IntoOwned for Origin<'a>

§

type Owned = Origin<'static>

The owned version of the type.
§

fn into_owned(self) -> Origin<'static>

Converts self into an owned version of itself.
§

impl<'a, 'b> PartialEq<Origin<'b>> for Origin<'a>

§

fn eq(&self, other: &Origin<'b>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<'a> !Freeze for Origin<'a>

§

impl<'a> !RefUnwindSafe for Origin<'a>

§

impl<'a> Send for Origin<'a>

§

impl<'a> Sync for Origin<'a>

§

impl<'a> Unpin for Origin<'a>

§

impl<'a> UnwindSafe for Origin<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, I> AsResult<T, I> for T
where I: Input,

source§

fn as_result(self) -> Result<T, ParseErr<I>>

source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> IntoCollection<T> for T

§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

source§

impl<T> Same for T

source§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Typeable for T
where T: Any,

source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V