Struct fluent_uri::Uri

source ·
#[repr(C)]
pub struct Uri<T: Storage> { /* private fields */ }
Expand description

A URI reference defined in RFC 3986.

Variants

There are three variants of Uri in total:

  • Uri<&str>: borrowed; immutable.
  • Uri<&mut [u8]>: borrowed; in-place mutable.
  • Uri<String>: owned; immutable.

Lifetimes are correctly handled in a way that Uri<&'a str> and Uri<&'a mut [u8]> both output references with lifetime 'a where appropriate. This allows you to drop a temporary Uri while keeping the output references:

use fluent_uri::Uri;

let mut bytes = *b"foo:bar";

let uri = Uri::parse(&bytes)?;
let path = uri.path();
drop(uri);
assert_eq!(path.as_str(), "bar");

let mut uri = Uri::parse_mut(&mut bytes)?;
let path = uri.take_path();
drop(uri);
assert_eq!(path.as_str(), "bar");

Examples

Create and convert between Uri<&str> and Uri<String>:

use fluent_uri::Uri;

let uri_str = "http://example.com/";

// Create a `Uri<&str>` from a string slice.
let uri_a: Uri<&str> = Uri::parse(uri_str)?;

// Create a `Uri<String>` from an owned string.
let uri_b: Uri<String> = Uri::parse_from(uri_str.to_owned()).map_err(|e| e.1)?;

// Convert a `Uri<&str>` to a `Uri<String>`.
let uri_c: Uri<String> = uri_a.to_owned();

// Borrow a `Uri<String>` as a `Uri<&str>`.
let uri_d: &Uri<&str> = uri_b.borrow();

Decode and extract query parameters in-place from a URI reference:

use fluent_uri::{ParseError, Uri};
use std::collections::HashMap;

fn decode_and_extract_query(
    bytes: &mut [u8],
) -> Result<(Uri<&mut [u8]>, HashMap<&str, &str>), ParseError> {
    let mut uri = Uri::parse_mut(bytes)?;
    let map = if let Some(query) = uri.take_query() {
        query
            .split_view('&')
            .flat_map(|pair| pair.split_once_view('='))
            .map(|(k, v)| (k.decode_in_place(), v.decode_in_place()))
            .flat_map(|(k, v)| k.into_str().ok().zip(v.into_str().ok()))
            .collect()
    } else {
        HashMap::new()
    };
    Ok((uri, map))
}

let mut bytes = *b"?lang=Rust&mascot=Ferris%20the%20crab";
let (uri, query) = decode_and_extract_query(&mut bytes)?;

assert_eq!(query["lang"], "Rust");
assert_eq!(query["mascot"], "Ferris the crab");

// The query is taken from the `Uri`.
assert!(uri.query().is_none());
// In-place decoding is like this if you're interested:
assert_eq!(&bytes, b"?lang=Rust&mascot=Ferris the crabcrab");

Implementations§

source§

impl<'a> Uri<&'a str>

source

pub fn parse<S: AsRef<[u8]> + ?Sized>(s: &S) -> Result<Uri<&str>, ParseError>

Parses a URI reference from a byte sequence into a Uri<&str>.

This function validates the input strictly except that UTF-8 validation is not performed on a percent-encoded registered name (see Section 3.2.2, RFC 3986). Care should be taken when dealing with such cases.

Panics

Panics if the input length is greater than i32::MAX.

Examples found in repository?
examples/parser.rs (line 19)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let mut buf = String::new();
    loop {
        buf.clear();
        io::stdin()
            .read_line(&mut buf)
            .expect("failed to read line");
        if buf.ends_with('\n') {
            buf.pop();
            if buf.ends_with('\r') {
                buf.pop();
            }
        }

        match Uri::parse(&buf) {
            Ok(u) => println!("{u:#?}"),
            Err(e) => println!("Error: {e}"),
        };
    }
}
source

pub fn dup(&self) -> Uri<&'a str>

Duplicates this Uri<&str>.

source

pub fn to_owned(&self) -> Uri<String>

Creates a new Uri<String> by cloning the contents of this Uri<&str>.

source§

impl<'i, 'o, T: Io<'i, 'o> + AsRef<str>> Uri<T>

source

pub fn as_str(&'i self) -> &'o str

Returns the URI reference as a string slice.

source§

impl<'i, 'o, T: Io<'i, 'o>> Uri<T>

source

pub fn scheme(&'i self) -> Option<&'o Scheme>

Returns the scheme component.

source

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

Returns the authority component.

source

pub fn path(&'i self) -> &'o Path

Returns the path component.

Panics

Panics if the path component is already taken.

source

pub fn query(&'i self) -> Option<&'o EStr>

Returns the query component.

source

pub fn fragment(&'i self) -> Option<&'o EStr>

Returns the fragment component.

source

pub fn is_relative(&self) -> bool

Returns true if the URI reference is relative, i.e., without a scheme.

Note that this method is not the opposite of is_absolute.

Examples
use fluent_uri::Uri;

let uri = Uri::parse("/path/to/file")?;
assert!(uri.is_relative());
let uri = Uri::parse("http://example.com/")?;
assert!(!uri.is_relative());
source

pub fn is_absolute(&self) -> bool

Returns true if the URI reference is absolute, i.e., with a scheme and without a fragment.

Note that this method is not the opposite of is_relative.

Examples
use fluent_uri::Uri;

let uri = Uri::parse("http://example.com/")?;
assert!(uri.is_absolute());
let uri = Uri::parse("http://example.com/#title1")?;
assert!(!uri.is_absolute());
let uri = Uri::parse("/path/to/file")?;
assert!(!uri.is_absolute());
source§

impl<'a> Uri<&'a mut [u8]>

source

pub fn parse_mut<S: AsMut<[u8]> + ?Sized>( s: &mut S ) -> Result<Uri<&mut [u8]>, ParseError>

Parses a URI reference from a mutable byte sequence into a Uri<&mut [u8]>.

See the parse function for more details.

Panics

Panics if the input length is greater than i32::MAX.

source

pub fn take_scheme(&mut self) -> Option<View<'a, Scheme>>

Takes a view of the scheme component, leaving a None in its place.

source

pub fn take_authority(&mut self) -> Option<View<'_, Authority<&'a mut [u8]>>>

Takes a view of the authority component, leaving a None in its place.

source

pub fn take_path(&mut self) -> View<'a, Path>

Takes a view of the path component.

Panics

Panics if the path component is already taken.

source

pub fn take_query(&mut self) -> Option<View<'a, EStr>>

Takes a view of the query component, leaving a None in its place.

source

pub fn take_fragment(&mut self) -> Option<View<'a, EStr>>

Takes a view of the fragment component, leaving a None in its place.

source§

impl Uri<String>

source

pub fn parse_from<T: IntoOwnedUri>(t: T) -> Result<Uri<String>, (T, ParseError)>

Parses a URI reference from a String or Vec<u8> into a Uri<String>.

See the parse function for more details.

Panics

Panics if the input capacity is greater than i32::MAX.

source

pub fn into_string(self) -> String

Consumes this Uri and yields the underlying String storage.

Examples
use fluent_uri::Uri;

let uri = Uri::parse("https://www.rust-lang.org/")?.to_owned();
let string = uri.into_string();
source

pub fn borrow(&self) -> &Uri<&str>

Borrows this Uri<String> as a reference to Uri<&str>.

Trait Implementations§

source§

impl Clone for Uri<String>

source§

fn clone(&self) -> Self

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
source§

impl Debug for Uri<&mut [u8]>

source§

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

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

impl Debug for Uri<&str>

source§

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

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

impl Debug for Uri<String>

source§

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

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

impl<T: Storage> Default for Uri<T>

source§

fn default() -> Self

Creates an empty Uri.

source§

impl Display for Uri<&str>

source§

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

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

impl Display for Uri<String>

source§

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

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

impl<T: Storage> Send for Uri<T>

source§

impl<T: Storage> Sync for Uri<T>

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Uri<T>

§

impl<T> Unpin for Uri<T>where T: Unpin, <T as Storage>::Ptr: Unpin,

§

impl<T> UnwindSafe for Uri<T>where T: UnwindSafe, <T as Storage>::Ptr: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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 Twhere T: Clone,

§

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 Twhere 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.