Skip to main content

Url

Struct Url 

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

Normalized URL reference.

The URL is stored in a single shared ByteString; accessors return borrowed, percent-encoded components. Parsing is lenient and normalizes the input the same way Python’s yarl does:

  • leading and trailing whitespace and C0 controls, tabs and newlines are removed
  • scheme and host are lowercased, non-ASCII hosts are punycode-encoded
  • percent-encoding is normalized: invalid characters are encoded, escapes of unreserved characters are decoded, hex digits are uppercased
  • dot segments are removed from absolute paths
  • an empty path of http, https, ws and wss URLs becomes /

The normalized URL always passes strict Url::validate.

use urly::Url;

let url: Url = "HTTPS://[email protected]:8443/a/./b/../c d?q=1#frag".parse().unwrap();
assert_eq!(url, "https://[email protected]:8443/a/c%20d?q=1#frag");
assert_eq!(url.scheme_str(), Some("https"));
assert_eq!(url.host(), Some("example.com"));
assert_eq!(url.port_u16(), Some(8443));
assert_eq!(url.path(), "/a/c%20d");
assert_eq!(url.path().decode(), "/a/c d");
assert_eq!(url.query().unwrap().get("q").unwrap(), "1");
assert_eq!(url.fragment().unwrap(), "frag");

URLs are limited to 65535 bytes; operations that can’t return an error panic if the result exceeds the limit.

Implementations§

Source§

impl Url

Source

pub fn from_parts(parts: Parts) -> Result<Url, InvalidUrlParts>

Creates a URL from strictly validated parts.

use urly::{Parts, Url};

let url = Url::from_static("http://example.com/a?b#c");
let mut parts = url.into_parts();
assert_eq!(parts.path_and_query, "/a?b");
parts.fragment = None;
assert_eq!(Url::from_parts(parts).unwrap(), "http://example.com/a?b");

let parts = Parts { path_and_query: "a b".into(), ..Parts::default() };
assert!(Url::from_parts(parts).is_err());
Source§

impl Url

Source

pub const fn new() -> Url

Returns the relative URL /.

Source

pub fn parse<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl>

Parses and normalizes an authority-form [userinfo@]host[:port], like http::Uri does for a string without a scheme or a leading /.

The result is a network-path reference without a path. Use Url::parse_ref to parse any URL reference, it treats such a string as a relative path.

use urly::Url;

let url = Url::parse("Custom.Domain:8080").unwrap();
assert_eq!(url, "//custom.domain:8080");
assert_eq!(url.host(), Some("custom.domain"));
assert_eq!(url.port_u16(), Some(8080));
assert_eq!(url.path(), "");

assert!(Url::parse("custom.domain/path").is_err());
assert_eq!(Url::parse_ref("custom.domain").unwrap().host(), None);
Source

pub fn parse_ref<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl>

Parses and normalizes a URL reference.

Same as Url::try_from() and str::parse().

Source

pub fn validate<T: AsRef<[u8]>>(src: T) -> Result<(), InvalidUrl>

Strictly validates a URI reference according to RFC 3986.

Unlike parsing, validation does not normalize: whitespace, non-ASCII characters and invalid escapes are errors. The error position is a byte offset into src. Input that is not valid UTF-8 is rejected with ErrorKind::InvalidChar at its first non-ASCII byte.

use urly::{ErrorKind, Url};

assert!(Url::validate("https://example.com/a%20b?q#f").is_ok());
assert!(Url::validate(b"/path?q").is_ok());

let err = Url::validate("http://ex ample.com").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidChar(' '));
assert_eq!(err.position(), Some(9));

let err = Url::validate(b"/a\xff").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidChar(char::REPLACEMENT_CHARACTER));
assert_eq!(err.position(), Some(2));
Source

pub fn from_static(src: &'static str) -> Url

Converts a static string to a URL. The string is not copied if it is already normalized.

§Panics

Panics if the URL is not valid.

Source

pub fn from_maybe_shared<T>(src: T) -> Result<Url, InvalidUrl>
where T: AsRef<[u8]> + 'static,

Converts a Bytes, String, Vec<u8> or any other byte buffer to a URL, reusing the buffer if possible.

Source

pub fn builder() -> Builder

Returns a new Builder.

Source

pub fn as_str(&self) -> &str

Returns the URL as a string.

Source

pub fn as_bytes(&self) -> &[u8] ⓘ

Returns the URL as bytes.

Source

pub fn as_byte_string(&self) -> &ByteString

Returns the underlying buffer.

Source

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

Returns the scheme, if present.

Source

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

Returns the scheme as a string, if present.

Source

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

Returns the authority, if present.

Source

pub fn userinfo(&self) -> Option<&UserInfo>

Returns the userinfo, if present.

Source

pub fn username(&self) -> Option<Cow<'_, str>>

Returns the decoded user name, if present.

Source

pub fn password(&self) -> Option<Cow<'_, str>>

Returns the decoded password, if present.

Source

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

Returns the host, if present and not empty. IPv6 addresses include the brackets, non-ASCII domains are punycode-encoded.

Source

pub fn host_parsed(&self) -> Option<Host<'_>>

Returns the parsed host, if present and not empty.

use std::net::Ipv4Addr;
use urly::{Host, Url};

let url = Url::from_static("http://127.0.0.1/");
assert_eq!(url.host_parsed(), Some(Host::Ipv4(Ipv4Addr::LOCALHOST)));

let url = Url::from_static("http://münchen.de/");
assert_eq!(url.host(), Some("xn--mnchen-3ya.de"));
assert_eq!(url.host_parsed().unwrap().to_unicode(), "münchen.de");
Source

pub fn port(&self) -> Option<Port<&str>>

Returns the explicit port, if present.

Source

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

Returns the explicit port as a number, if present.

Source

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

Returns the explicit port, or the default port of the scheme.

Source

pub fn path(&self) -> &Path

Returns the percent-encoded path.

A path starting with // in a URL without authority is serialized with a /. prefix, which is not part of the path.

use urly::Url;

let url = Url::from_static("/.//a?q");
assert_eq!(url.path(), "//a");
assert_eq!(url.path_and_query(), "//a?q");
Source

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

Returns the percent-encoded query, if present.

Source

pub fn path_and_query(&self) -> &PathAndQuery

Returns the path and query.

Source

pub fn fragment(&self) -> Option<&Fragment>

Returns the percent-encoded fragment, if present.

Source

pub fn is_absolute(&self) -> bool

Returns true if the URL has a scheme.

Source

pub fn is_default_port(&self) -> bool

Returns true if the port is absent or is the default port of the scheme.

Source

pub fn origin(&self) -> Option<Url>

Returns the origin: scheme, host and port.

use urly::Url;

let url = Url::from_static("https://user:[email protected]:8443/a?b#c");
assert_eq!(url.origin().unwrap(), "https://example.com:8443/");
assert!(Url::from_static("/a").origin().is_none());
Source

pub fn relative(&self) -> Url

Returns the relative part of the URL: path, query and fragment.

use urly::Url;

let url = Url::from_static("https://example.com/a?b#c");
assert_eq!(url.relative(), "/a?b#c");
Source

pub fn parent(&self) -> Url

Returns the URL with the last path segment removed, without query and fragment.

use urly::Url;

assert_eq!(Url::from_static("http://h/a/b?q").parent(), "http://h/a");
assert_eq!(Url::from_static("http://h/a/b/").parent(), "http://h/a");
assert_eq!(Url::from_static("http://h/a").parent(), "http://h/");
assert_eq!(Url::from_static("http://h/").parent(), "http://h/");
Source

pub fn push_segments<I, S>(&self, segments: I) -> Url
where I: IntoIterator<Item = S>, S: AsRef<str>,

Appends literal path segments, without query and fragment.

Segments are percent-encoded; / is kept and a leading / is ignored. The same operation is available as the / operator.

use urly::Url;

let url = Url::from_static("http://h/api?q");
assert_eq!(url.push_segments(["v1", "a b"]), "http://h/api/v1/a%20b");
assert_eq!(&url / "users/" / "1", "http://h/api/users/1");
Source

pub fn join(&self, reference: &str) -> Result<Url, InvalidUrl>

Resolves a reference against this URL, RFC 3986 section 5.2.

use urly::Url;

let base = Url::from_static("http://a/b/c/d;p?q");
assert_eq!(base.join("../g").unwrap(), "http://a/b/g");
assert_eq!(base.join("//g/x").unwrap(), "http://g/x");
assert_eq!(base.join("?y").unwrap(), "http://a/b/c/d;p?y");
Source

pub fn join_url(&self, r: &Url) -> Url

Resolves a parsed reference against this URL, RFC 3986 section 5.2.2.

The + and += operators are equivalent.

use urly::Url;

let base = Url::from_static("http://a/b/c/d;p?q");
let r = Url::from_static("../g");
assert_eq!(base.join_url(&r), "http://a/b/g");
assert_eq!(&base + &r, "http://a/b/g");

let mut url = base.clone();
url += r;
assert_eq!(url, "http://a/b/g");
Source

pub fn set_scheme(&mut self, scheme: &str) -> Result<(), InvalidUrl>

Sets the scheme.

Source

pub fn set_authority( &mut self, authority: Option<&str>, ) -> Result<(), InvalidUrl>

Sets or removes the raw authority: [userinfo "@"] host [":" port].

Source

pub fn set_userinfo( &mut self, username: Option<&str>, password: Option<&str>, ) -> Result<(), InvalidUrl>

Sets or removes the literal user name and password.

use urly::Url;

let mut url = Url::from_static("http://example.com/");
url.set_userinfo(Some("us@r"), Some("p:w")).unwrap();
assert_eq!(url, "http://us%40r:p%[email protected]/");
assert_eq!(url.password().unwrap(), "p:w");
Source

pub fn set_host(&mut self, host: &str) -> Result<(), InvalidUrl>

Sets the host. Escapes are decoded, non-ASCII domains are punycode-encoded, IPv6 addresses may be given without brackets.

An authority is added if the URL doesn’t have one.

use urly::Url;

let mut url = Url::from_static("http://[email protected]:8080/a");
url.set_host("::1").unwrap();
assert_eq!(url, "http://user@[::1]:8080/a");
url.set_host("Bücher.example").unwrap();
assert_eq!(url, "http://[email protected]:8080/a");
Source

pub fn set_port(&mut self, port: Option<u16>) -> Result<(), InvalidUrl>

Sets or removes the port.

Source

pub fn set_path(&mut self, path: &str)

Sets the percent-encoded path, keeping query and fragment.

Invalid characters are encoded and dot segments are removed.

use urly::Url;

let mut url = Url::from_static("http://h/a?q");
url.set_path("/b/../c d");
assert_eq!(url, "http://h/c%20d?q");
Source

pub fn set_file_name(&mut self, name: &str) -> Result<(), InvalidUrl>

Replaces the last path segment with a literal file name.

use urly::Url;

let mut url = Url::from_static("http://h/a/b.txt?q");
url.set_file_name("c d.html").unwrap();
assert_eq!(url, "http://h/a/c%20d.html?q");
Source

pub fn set_extension(&mut self, extension: &str) -> Result<(), InvalidUrl>

Replaces the extension of the file name; an empty extension removes it.

use urly::Url;

let mut url = Url::from_static("http://h/a/b.txt");
url.set_extension("tar.gz").unwrap();
assert_eq!(url, "http://h/a/b.tar.gz");
url.set_extension("").unwrap();
assert_eq!(url, "http://h/a/b.tar");
Source

pub fn set_query(&mut self, query: Option<&str>)

Sets or removes the percent-encoded query.

use urly::Url;

let mut url = Url::from_static("http://h/#f");
url.set_query(Some("a=b c&d"));
assert_eq!(url, "http://h/?a=b+c&d#f");
Source

pub fn set_query_pairs<I, K, V>(&mut self, pairs: I)
where I: IntoIterator<Item = (K, V)>, K: AsRef<str>, V: AsRef<str>,

Replaces the query with literal key-value pairs. Empty pairs remove the query.

use urly::Url;

let mut url = Url::from_static("http://h/?old");
url.set_query_pairs([("a", "1 2"), ("b&", "=")]);
assert_eq!(url, "http://h/?a=1+2&b%26=%3D");
Source

pub fn extend_query_pairs<I, K, V>(&mut self, pairs: I)
where I: IntoIterator<Item = (K, V)>, K: AsRef<str>, V: AsRef<str>,

Appends literal key-value pairs to the query.

Source

pub fn update_query_pairs<I, K, V>(&mut self, pairs: I)
where I: IntoIterator<Item = (K, V)>, K: AsRef<str>, V: AsRef<str>,

Replaces all values of the given keys, appending the new pairs.

use urly::Url;

let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
url.update_query_pairs([("a", "4")]);
assert_eq!(url, "http://h/?b=2&a=4");
Source

pub fn remove_query_params<I, K>(&mut self, keys: I)
where I: IntoIterator<Item = K>, K: AsRef<str>,

Removes all pairs with the given keys from the query.

use urly::Url;

let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
url.remove_query_params(["a"]);
assert_eq!(url, "http://h/?b=2");
url.remove_query_params(["b"]);
assert_eq!(url, "http://h/");
Source

pub fn set_fragment(&mut self, fragment: Option<&str>)

Sets or removes the percent-encoded fragment.

Source

pub fn into_parts(self) -> Parts

Splits the URL into its parts.

Source

pub fn into_byte_string(self) -> ByteString

Converts the URL into its buffer.

Trait Implementations§

Source§

impl<U: Borrow<Url>> Add<U> for &Url

Source§

type Output = Url

The resulting type after applying the + operator.
Source§

fn add(self, reference: U) -> Url

Performs the + operation. Read more
Source§

impl<U: Borrow<Url>> Add<U> for Url

Source§

type Output = Url

The resulting type after applying the + operator.
Source§

fn add(self, reference: U) -> Url

Performs the + operation. Read more
Source§

impl<U: Borrow<Url>> AddAssign<U> for Url

Source§

fn add_assign(&mut self, reference: U)

Performs the += operation. Read more
Source§

impl AsRef<str> for Url

Source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Url

Source§

fn clone(&self) -> Url

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Url

Source§

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

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

impl Default for Url

Returns the relative URL /, like http::Uri::default().

Source§

fn default() -> Url

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

impl Display for Url

Source§

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

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

impl<S: AsRef<str>> Div<S> for &Url

Source§

type Output = Url

The resulting type after applying the / operator.
Source§

fn div(self, segment: S) -> Url

Performs the / operation. Read more
Source§

impl<S: AsRef<str>> Div<S> for Url

Source§

type Output = Url

The resulting type after applying the / operator.
Source§

fn div(self, segment: S) -> Url

Performs the / operation. Read more
Source§

impl Eq for Url

Source§

impl From<Url> for Builder

Source§

fn from(url: Url) -> Self

Converts to this type from the input type.
Source§

impl From<Url> for ByteString

Source§

fn from(url: Url) -> ByteString

Converts to this type from the input type.
Source§

impl From<Url> for String

Source§

fn from(url: Url) -> String

Converts to this type from the input type.
Source§

impl FromStr for Url

Source§

type Err = InvalidUrl

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Url, InvalidUrl>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Url

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Url

Source§

fn cmp(&self, other: &Url) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Url

Source§

fn eq(&self, other: &Url) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialEq<&str> for Url

Source§

fn eq(&self, other: &&str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialEq<Url> for str

Source§

fn eq(&self, other: &Url) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialEq<Url> for &str

Source§

fn eq(&self, other: &Url) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialEq<str> for Url

Source§

fn eq(&self, other: &str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialOrd for Url

Source§

fn partial_cmp(&self, other: &Url) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl TryFrom<&ByteString> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: &ByteString) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<&String> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: &String) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<&Uri> for Url

Source§

type Error = InvalidUrl

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

fn try_from(uri: &Uri) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<&Url> for Uri

The fragment is removed, Uri doesn’t support it. A network-path reference converts to authority-form, it fails if it has a path or query.

Source§

type Error = InvalidUri

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

fn try_from(url: &Url) -> Result<Uri, InvalidUri>

Performs the conversion.
Source§

impl TryFrom<&[u8]> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: &[u8]) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<&str> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: &str) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<ByteString> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: ByteString) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<Bytes> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: Bytes) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<String> for Url

Source§

type Error = InvalidUrl

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

fn try_from(s: String) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<Uri> for Url

Source§

type Error = InvalidUrl

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

fn try_from(uri: Uri) -> Result<Url, InvalidUrl>

Performs the conversion.
Source§

impl TryFrom<Url> for Uri

The fragment is removed, Uri doesn’t support it.

Source§

type Error = InvalidUri

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

fn try_from(url: Url) -> Result<Uri, InvalidUri>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Url

§

impl RefUnwindSafe for Url

§

impl Send for Url

§

impl Sync for Url

§

impl Unpin for Url

§

impl UnsafeUnpin for Url

§

impl UnwindSafe for Url

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.