Uri

Struct Uri 

Source
pub struct Uri { /* private fields */ }
Expand description

This type is used to parse and generate URI strings to and from their various components. Components are percent-encoded as necessary during generation, and percent encodings are decoded during parsing.

Since most URI components, once decoded, may include non-UTF8 byte sequences (which are always percent-encoded), getter methods such as path and query return byte array slice references (&[u8]) rather than string or string slice references. Fallible convenience methods ending in _to_string, such as path_to_string and query_to_string, are provided to convert these to strings.

The “Authority” part of the Uri is represented by the Authority type. Although the Uri type provides userinfo, host, and port methods for convenience, Uri holds these components through the Authority type, which can be accessed via authority and set_authority. To set or change the userinfo, host, or port of a Uri, construct a new Authority value and set it in the Uri with set_authority.

§Examples

§Parsing a URI into its components

use uris::Uri;

let uri = Uri::parse("http://www.example.com/foo?bar#baz")?;
let authority = uri.authority().unwrap();
assert_eq!("www.example.com".as_bytes(), authority.host());
assert_eq!(Some("www.example.com"), uri.host_to_string()?.as_deref());
assert_eq!("/foo", uri.path_to_string()?);
assert_eq!(Some("bar"), uri.query_to_string()?.as_deref());
assert_eq!(Some("baz"), uri.fragment_to_string()?.as_deref());

Implementations are provided for the TryFrom trait, so that TryFrom::try_from or TryInto::try_into may be used as alternatives to parse.

§Generating a URI from its components

use uris::{
    Authority,
    Uri,
};

let mut uri = Uri::default();
assert!(uri.set_scheme(String::from("http")).is_ok());
let mut authority = Authority::default();
authority.set_host("www.example.com");
uri.set_authority(Some(authority));
uri.set_path_from_str("/foo");
uri.set_query(Some("bar".into()));
uri.set_fragment(Some("baz".into()));
assert_eq!("http://www.example.com/foo?bar#baz", uri.to_string());

Implementations§

Source§

impl Uri

Source

pub fn authority(&self) -> Option<&Authority>

Borrow the authority (if any) of the URI.

Source

pub fn contains_relative_path(&self) -> bool

Determines if the URI contains a relative path rather than an absolute path.

Source

pub fn fragment(&self) -> Option<&[u8]>

Borrow the fragment (if any) of the URI.

Source

pub fn fragment_to_string(&self) -> Result<Option<String>, Error>

Convert the fragment (if any) into a string.

§Errors

Since fragments may contain non-UTF8 byte sequences, this function may return Error::CannotExpressAsUtf8.

Source

pub fn host(&self) -> Option<&[u8]>

Borrow the host portion of the Authority (if any) of the URI.

Source

pub fn host_to_string(&self) -> Result<Option<String>, Error>

Convert the host portion of the Authority (if any) into a string.

§Errors

Since host names may contain non-UTF8 byte sequences, this function may return Error::CannotExpressAsUtf8.

Source

pub fn is_relative_reference(&self) -> bool

Determines if the URI is a relative-ref (relative reference), as defined in RFC 3986 section 4.2. A relative reference has no scheme, but may still have an authority.

Source

pub fn normalize(&mut self)

Apply the remove_dot_segments routine talked about in RFC 3986 section 5.2 to the path segments of the URI, in order to normalize the path (apply and remove “.” and “..” segments).

§Examples
use uris::Uri;

let mut uri = Uri::parse("/a/b/c/./../../g")?;
uri.normalize();
assert_eq!("/a/g", uri.path_to_string()?);
Source

pub fn parse<T>(uri_string: T) -> Result<Self, Error>
where T: AsRef<str>,

Interpret the given string as a URI, separating its various components, returning a Uri value containing them.

§Errors

There are many ways to screw up a URI string, and this function will let you know what’s up by returning a variant of the Error type.

Source

pub fn path(&self) -> &Vec<Vec<u8>>

Borrow the path component of the URI.

The path is represented as a two-dimensional vector:

  • the “segments” or pieces of the path between the slashes
  • the bytes that make up each segment

Byte vectors are used instead of strings because segments may contain non-UTF8 sequences.

Leading and trailing slashes in the path are special cases represented by extra empty segments at the beginning and/or end of the path.

§Examples

(Note: the examples below show strings, not byte vectors, simply to be more readable.)

"foo/bar"   -> ["foo", "bar"]
"/foo/bar"  -> ["", "foo", "bar"]
"foo/bar/"  -> ["foo", "bar", ""]
"/foo/bar/" -> ["", "foo", "bar", ""]
"/"         -> [""]
""          -> []
Source

pub fn path_to_string(&self) -> Result<String, Error>

Convert the path portion of the URI into a string.

§Errors

Since path segments may contain non-UTF8 byte sequences, this function may return Error::CannotExpressAsUtf8.

Source

pub fn port(&self) -> Option<u16>

Return a copy of the port (if any) contained in the URI.

Source

pub fn query(&self) -> Option<&[u8]>

Borrow the query (if any) of the URI.

Source

pub fn query_to_string(&self) -> Result<Option<String>, Error>

Convert the query (if any) into a string.

§Errors

Since queries may contain non-UTF8 byte sequences, this function may return Error::CannotExpressAsUtf8.

Source

pub fn resolve(&self, relative_reference: &Self) -> Self

Return a new URI which is the result of applying the given relative reference to the URI, following the algorithm from RFC 3986 section 5.2.2.

§Examples
use uris::Uri;

let base = Uri::parse("http://a/b/c/d;p?q")?;
let relative_reference = Uri::parse("g;x?y#s")?;
let resolved = base.resolve(&relative_reference);
assert_eq!("http://a/b/c/g;x?y#s", resolved.to_string());
Source

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

Borrow the scheme (if any) component of the URI.

Source

pub fn set_authority<T>(&mut self, authority: T)
where T: Into<Option<Authority>>,

Change the authority of the URI.

Source

pub fn set_fragment<T>(&mut self, fragment: T)
where T: Into<Option<Vec<u8>>>,

Change the fragment of the URI.

Source

pub fn set_path<T>(&mut self, path: T)
where T: Into<Vec<Vec<u8>>>,

Change the path of the URI.

Note: See path for special notes about what the segments of the path mean.

Source

pub fn set_path_from_str<T>(&mut self, path: T)
where T: AsRef<str>,

Change the path of the URI using a string which is split by its slash (/) characters to determine the path segments.

Note: See path for special notes about what the segments of the path mean.

Source

pub fn set_query<T>(&mut self, query: T)
where T: Into<Option<Vec<u8>>>,

Change the query of the URI.

Source

pub fn set_scheme<T>(&mut self, scheme: T) -> Result<(), Error>
where T: Into<Option<String>>,

Change the scheme of the URI.

§Errors

The set of characters allowed in the scheme of a URI is limited. Error::IllegalCharacter is returned if you try to use a character that isn’t allowed.

Source

pub fn take_authority(&mut self) -> Option<Authority>

Remove and return the authority portion (if any) of the URI.

Source

pub fn take_fragment(&mut self) -> Option<Vec<u8>>

Remove and return the fragment portion (if any) of the URI.

Source

pub fn take_query(&mut self) -> Option<Vec<u8>>

Remove and return the query portion (if any) of the URI.

Source

pub fn take_scheme(&mut self) -> Option<String>

Remove and return the scheme portion (if any) of the URI.

Source

pub fn userinfo(&self) -> Option<&[u8]>

Borrow the userinfo portion (if any) of the Authority (if any) of the URI.

Note that you can get None if there is either no Authority in the URI or there is an Authority in the URI but it has no userinfo in it.

Source

pub fn userinfo_to_string(&self) -> Result<Option<String>, Error>

Convert the fragment (if any) into a string.

§Errors

Since fragments may contain non-UTF8 byte sequences, this function may return Error::CannotExpressAsUtf8.

Trait Implementations§

Source§

impl Clone for Uri

Source§

fn clone(&self) -> Uri

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Uri

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for Uri

Source§

fn default() -> Uri

Returns the “default value” for a type. Read more
Source§

impl Display for Uri

Source§

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

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Uri

Source§

fn eq(&self, other: &Uri) -> 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.
Source§

impl TryFrom<&str> for Uri

Source§

type Error = Error

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

fn try_from(uri_string: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<String> for Uri

Source§

type Error = Error

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

fn try_from(uri_string: String) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl StructuralPartialEq for Uri

Auto Trait Implementations§

§

impl Freeze for Uri

§

impl RefUnwindSafe for Uri

§

impl Send for Uri

§

impl Sync for Uri

§

impl Unpin for Uri

§

impl UnwindSafe for Uri

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> 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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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.

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§

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.