pub struct Url2(/* private fields */);
Expand description

Ergonomic wrapper around the popular Url crate

Implementations§

source§

impl Url2

source

pub fn try_parse<S>(s: S) -> Result<Url2, Url2Error>
where S: AsRef<str>,

Try to parse a utf8 slice into a Url2 instance. May result in a UrlParseError

Example
use url2::prelude::*;

assert_eq!(
    "Err(Url2Error(UrlParseError(RelativeUrlWithoutBase)))",
    &format!("{:?}", Url2::try_parse("")),
);
assert_eq!(
    "Ok(Url2 { url: \"none:\" })",
    &format!("{:?}", Url2::try_parse("none:")),
);
source

pub fn parse<S>(s: S) -> Url2
where S: AsRef<str>,

Try to parse a utf8 slice into a Url2 instance. If this results in a UrlParseError, this method will panic!

Example
use url2::prelude::*;

assert_eq!("none:", Url2::parse("none:").as_str());
source

pub fn into_string(self) -> String

convert this Url2 instance into a string

Example
use url2::prelude::*;

assert_eq!("none:", Url2::default().as_str());
source

pub fn query_unique(&mut self) -> Url2QueryUnique<'_>

Access query string entries as a unique key map.

Url query strings support multiple instances of the same key However, many common use-cases treat the query string keys as unique entries in a map. An optional API viewing the query string in this manner can be more ergonomic.

The HashMap that backs this view is only created the first time this function (or the following query_unique_* functions) are invoked. If you do not use them, there is no additional overhead.

Example
use url2::prelude::*;

let mut url = Url2::default();
url.query_unique().set_pair("a", "1").set_pair("a", "2");

assert_eq!("none:?a=2", url.as_str());
source

pub fn query_unique_contains_key(&mut self, key: &str) -> bool

When parsed as a unique map, does the query string contain given key?

Example
use url2::prelude::*;

let mut url = Url2::parse("none:?a=1");

assert!(url.query_unique_contains_key("a"));
assert!(!url.query_unique_contains_key("b"));
source

pub fn query_unique_get(&mut self, key: &str) -> Option<&str>

When parsed as a unique map, get the value for given key

Example
use url2::prelude::*;

let mut url = Url2::parse("none:?a=1");

assert_eq!(
    "Some(\"1\")",
    &format!("{:?}", url.query_unique_get("a")),
);
assert_eq!(
    "None",
    &format!("{:?}", url.query_unique_get("b")),
);

Methods from Deref<Target = Url>§

source

pub fn join(&self, input: &str) -> Result<Url, ParseError>

Parse a string as an URL, with this URL as the base URL.

The inverse of this is make_relative.

Note: a trailing slash is significant. Without it, the last path component is considered to be a “file” name to be removed to get at the “directory” that is used as the base:

Examples
use url::Url;

let base = Url::parse("https://example.net/a/b.html")?;
let url = base.join("c.png")?;
assert_eq!(url.as_str(), "https://example.net/a/c.png");  // Not /a/b.html/c.png

let base = Url::parse("https://example.net/a/b/")?;
let url = base.join("c.png")?;
assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
Errors

If the function can not parse an URL from the given string with this URL as the base URL, a ParseError variant will be returned.

source

pub fn make_relative(&self, url: &Url) -> Option<String>

Creates a relative URL if possible, with this URL as the base URL.

This is the inverse of join.

Examples
use url::Url;

let base = Url::parse("https://example.net/a/b.html")?;
let url = Url::parse("https://example.net/a/c.png")?;
let relative = base.make_relative(&url);
assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));

let base = Url::parse("https://example.net/a/b/")?;
let url = Url::parse("https://example.net/a/b/c.png")?;
let relative = base.make_relative(&url);
assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));

let base = Url::parse("https://example.net/a/b/")?;
let url = Url::parse("https://example.net/a/d/c.png")?;
let relative = base.make_relative(&url);
assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("../d/c.png"));

let base = Url::parse("https://example.net/a/b.html?c=d")?;
let url = Url::parse("https://example.net/a/b.html?e=f")?;
let relative = base.make_relative(&url);
assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("?e=f"));
Errors

If this URL can’t be a base for the given URL, None is returned. This is for example the case if the scheme, host or port are not the same.

source

pub fn as_str(&self) -> &str

Return the serialization of this URL.

This is fast since that serialization is already stored in the Url struct.

Examples
use url::Url;

let url_str = "https://example.net/";
let url = Url::parse(url_str)?;
assert_eq!(url.as_str(), url_str);
source

pub fn origin(&self) -> Origin

Return the origin of this URL (https://url.spec.whatwg.org/#origin)

Note: this returns an opaque origin for file: URLs, which causes url.origin() != url.origin().

Examples

URL with ftp scheme:

use url::{Host, Origin, Url};

let url = Url::parse("ftp://example.com/foo")?;
assert_eq!(url.origin(),
           Origin::Tuple("ftp".into(),
                         Host::Domain("example.com".into()),
                         21));

URL with blob scheme:

use url::{Host, Origin, Url};

let url = Url::parse("blob:https://example.com/foo")?;
assert_eq!(url.origin(),
           Origin::Tuple("https".into(),
                         Host::Domain("example.com".into()),
                         443));

URL with file scheme:

use url::{Host, Origin, Url};

let url = Url::parse("file:///tmp/foo")?;
assert!(!url.origin().is_tuple());

let other_url = Url::parse("file:///tmp/foo")?;
assert!(url.origin() != other_url.origin());

URL with other scheme:

use url::{Host, Origin, Url};

let url = Url::parse("foo:bar")?;
assert!(!url.origin().is_tuple());
source

pub fn scheme(&self) -> &str

Return the scheme of this URL, lower-cased, as an ASCII string without the ‘:’ delimiter.

Examples
use url::Url;

let url = Url::parse("file:///tmp/foo")?;
assert_eq!(url.scheme(), "file");
source

pub fn is_special(&self) -> bool

Return whether the URL is special (has a special scheme)

Examples
use url::Url;

assert!(Url::parse("http:///tmp/foo")?.is_special());
assert!(Url::parse("file:///tmp/foo")?.is_special());
assert!(!Url::parse("moz:///tmp/foo")?.is_special());
source

pub fn has_authority(&self) -> bool

Return whether the URL has an ‘authority’, which can contain a username, password, host, and port number.

URLs that do not are either path-only like unix:/run/foo.socket or cannot-be-a-base like data:text/plain,Stuff.

See also the authority method.

Examples
use url::Url;

let url = Url::parse("ftp://rms@example.com")?;
assert!(url.has_authority());

let url = Url::parse("unix:/run/foo.socket")?;
assert!(!url.has_authority());

let url = Url::parse("data:text/plain,Stuff")?;
assert!(!url.has_authority());
source

pub fn authority(&self) -> &str

Return the authority of this URL as an ASCII string.

Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs. IPv6 addresses are given between [ and ] brackets. Ports are omitted if they match the well known port of a special URL.

Username and password are percent-encoded.

See also the has_authority method.

Examples
use url::Url;

let url = Url::parse("unix:/run/foo.socket")?;
assert_eq!(url.authority(), "");
let url = Url::parse("file:///tmp/foo")?;
assert_eq!(url.authority(), "");
let url = Url::parse("https://user:password@example.com/tmp/foo")?;
assert_eq!(url.authority(), "user:password@example.com");
let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?;
assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667");
let url = Url::parse("http://àlex.рф.example.com:80/foo")?;
assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com");
source

pub fn cannot_be_a_base(&self) -> bool

Return whether this URL is a cannot-be-a-base URL, meaning that parsing a relative URL string with this URL as the base will return an error.

This is the case if the scheme and : delimiter are not followed by a / slash, as is typically the case of data: and mailto: URLs.

Examples
use url::Url;

let url = Url::parse("ftp://rms@example.com")?;
assert!(!url.cannot_be_a_base());

let url = Url::parse("unix:/run/foo.socket")?;
assert!(!url.cannot_be_a_base());

let url = Url::parse("data:text/plain,Stuff")?;
assert!(url.cannot_be_a_base());
source

pub fn username(&self) -> &str

Return the username for this URL (typically the empty string) as a percent-encoded ASCII string.

Examples
use url::Url;

let url = Url::parse("ftp://rms@example.com")?;
assert_eq!(url.username(), "rms");

let url = Url::parse("ftp://:secret123@example.com")?;
assert_eq!(url.username(), "");

let url = Url::parse("https://example.com")?;
assert_eq!(url.username(), "");
source

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

Return the password for this URL, if any, as a percent-encoded ASCII string.

Examples
use url::Url;

let url = Url::parse("ftp://rms:secret123@example.com")?;
assert_eq!(url.password(), Some("secret123"));

let url = Url::parse("ftp://:secret123@example.com")?;
assert_eq!(url.password(), Some("secret123"));

let url = Url::parse("ftp://rms@example.com")?;
assert_eq!(url.password(), None);

let url = Url::parse("https://example.com")?;
assert_eq!(url.password(), None);
source

pub fn has_host(&self) -> bool

Equivalent to url.host().is_some().

Examples
use url::Url;

let url = Url::parse("ftp://rms@example.com")?;
assert!(url.has_host());

let url = Url::parse("unix:/run/foo.socket")?;
assert!(!url.has_host());

let url = Url::parse("data:text/plain,Stuff")?;
assert!(!url.has_host());
source

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

Return the string representation of the host (domain or IP address) for this URL, if any.

Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs. IPv6 addresses are given between [ and ] brackets.

Cannot-be-a-base URLs (typical of data: and mailto:) and some file: URLs don’t have a host.

See also the host method.

Examples
use url::Url;

let url = Url::parse("https://127.0.0.1/index.html")?;
assert_eq!(url.host_str(), Some("127.0.0.1"));

let url = Url::parse("ftp://rms@example.com")?;
assert_eq!(url.host_str(), Some("example.com"));

let url = Url::parse("unix:/run/foo.socket")?;
assert_eq!(url.host_str(), None);

let url = Url::parse("data:text/plain,Stuff")?;
assert_eq!(url.host_str(), None);
source

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

Return the parsed representation of the host for this URL. Non-ASCII domain labels are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs.

Cannot-be-a-base URLs (typical of data: and mailto:) and some file: URLs don’t have a host.

See also the host_str method.

Examples
use url::Url;

let url = Url::parse("https://127.0.0.1/index.html")?;
assert!(url.host().is_some());

let url = Url::parse("ftp://rms@example.com")?;
assert!(url.host().is_some());

let url = Url::parse("unix:/run/foo.socket")?;
assert!(url.host().is_none());

let url = Url::parse("data:text/plain,Stuff")?;
assert!(url.host().is_none());
source

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

If this URL has a host and it is a domain name (not an IP address), return it. Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs.

Examples
use url::Url;

let url = Url::parse("https://127.0.0.1/")?;
assert_eq!(url.domain(), None);

let url = Url::parse("mailto:rms@example.net")?;
assert_eq!(url.domain(), None);

let url = Url::parse("https://example.com/")?;
assert_eq!(url.domain(), Some("example.com"));
source

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

Return the port number for this URL, if any.

Note that default port numbers are never reflected by the serialization, use the port_or_known_default() method if you want a default port number returned.

Examples
use url::Url;

let url = Url::parse("https://example.com")?;
assert_eq!(url.port(), None);

let url = Url::parse("https://example.com:443/")?;
assert_eq!(url.port(), None);

let url = Url::parse("ssh://example.com:22")?;
assert_eq!(url.port(), Some(22));
source

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

Return the port number for this URL, or the default port number if it is known.

This method only knows the default port number of the http, https, ws, wss and ftp schemes.

For URLs in these schemes, this method always returns Some(_). For other schemes, it is the same as Url::port().

Examples
use url::Url;

let url = Url::parse("foo://example.com")?;
assert_eq!(url.port_or_known_default(), None);

let url = Url::parse("foo://example.com:1456")?;
assert_eq!(url.port_or_known_default(), Some(1456));

let url = Url::parse("https://example.com")?;
assert_eq!(url.port_or_known_default(), Some(443));
source

pub fn socket_addrs( &self, default_port_number: impl Fn() -> Option<u16> ) -> Result<Vec<SocketAddr>, Error>

Resolve a URL’s host and port number to SocketAddr.

If the URL has the default port number of a scheme that is unknown to this library, default_port_number provides an opportunity to provide the actual port number. In non-example code this should be implemented either simply as || None, or by matching on the URL’s .scheme().

If the host is a domain, it is resolved using the standard library’s DNS support.

Examples
let url = url::Url::parse("https://example.net/").unwrap();
let addrs = url.socket_addrs(|| None).unwrap();
std::net::TcpStream::connect(&*addrs)
/// With application-specific known default port numbers
fn socket_addrs(url: url::Url) -> std::io::Result<Vec<std::net::SocketAddr>> {
    url.socket_addrs(|| match url.scheme() {
        "socks5" | "socks5h" => Some(1080),
        _ => None,
    })
}
source

pub fn path(&self) -> &str

Return the path for this URL, as a percent-encoded ASCII string. For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with ‘/’. For other URLs, this starts with a ‘/’ slash and continues with slash-separated path segments.

Examples
use url::{Url, ParseError};

let url = Url::parse("https://example.com/api/versions?page=2")?;
assert_eq!(url.path(), "/api/versions");

let url = Url::parse("https://example.com")?;
assert_eq!(url.path(), "/");

let url = Url::parse("https://example.com/countries/việt nam")?;
assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
source

pub fn path_segments(&self) -> Option<Split<'_, char>>

Unless this URL is cannot-be-a-base, return an iterator of ‘/’ slash-separated path segments, each as a percent-encoded ASCII string.

Return None for cannot-be-a-base URLs.

When Some is returned, the iterator always contains at least one string (which may be empty).

Examples
use url::Url;

let url = Url::parse("https://example.com/foo/bar")?;
let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
assert_eq!(path_segments.next(), Some("foo"));
assert_eq!(path_segments.next(), Some("bar"));
assert_eq!(path_segments.next(), None);

let url = Url::parse("https://example.com")?;
let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
assert_eq!(path_segments.next(), Some(""));
assert_eq!(path_segments.next(), None);

let url = Url::parse("data:text/plain,HelloWorld")?;
assert!(url.path_segments().is_none());

let url = Url::parse("https://example.com/countries/việt nam")?;
let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
assert_eq!(path_segments.next(), Some("countries"));
assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
source

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

Return this URL’s query string, if any, as a percent-encoded ASCII string.

Examples
use url::Url;

fn run() -> Result<(), ParseError> {
let url = Url::parse("https://example.com/products?page=2")?;
let query = url.query();
assert_eq!(query, Some("page=2"));

let url = Url::parse("https://example.com/products")?;
let query = url.query();
assert!(query.is_none());

let url = Url::parse("https://example.com/?country=español")?;
let query = url.query();
assert_eq!(query, Some("country=espa%C3%B1ol"));
source

pub fn query_pairs(&self) -> Parse<'_>

Parse the URL’s query string, if any, as application/x-www-form-urlencoded and return an iterator of (key, value) pairs.

Examples
use std::borrow::Cow;

use url::Url;

let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
let mut pairs = url.query_pairs();

assert_eq!(pairs.count(), 2);

assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
source

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

Return this URL’s fragment identifier, if any.

A fragment is the part of the URL after the # symbol. The fragment is optional and, if present, contains a fragment identifier that identifies a secondary resource, such as a section heading of a document.

In HTML, the fragment identifier is usually the id attribute of a an element that is scrolled to on load. Browsers typically will not send the fragment portion of a URL to the server.

Note: the parser did not percent-encode this component, but the input may have been percent-encoded already.

Examples
use url::Url;

let url = Url::parse("https://example.com/data.csv#row=4")?;

assert_eq!(url.fragment(), Some("row=4"));

let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;

assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
source

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

Change this URL’s fragment identifier.

Examples
use url::Url;

let mut url = Url::parse("https://example.com/data.csv")?;
assert_eq!(url.as_str(), "https://example.com/data.csv");
url.set_fragment(Some("cell=4,1-6,2"));
assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
assert_eq!(url.fragment(), Some("cell=4,1-6,2"));

url.set_fragment(None);
assert_eq!(url.as_str(), "https://example.com/data.csv");
assert!(url.fragment().is_none());
source

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

Change this URL’s query string.

Examples
use url::Url;

let mut url = Url::parse("https://example.com/products")?;
assert_eq!(url.as_str(), "https://example.com/products");

url.set_query(Some("page=2"));
assert_eq!(url.as_str(), "https://example.com/products?page=2");
assert_eq!(url.query(), Some("page=2"));
source

pub fn query_pairs_mut(&mut self) -> Serializer<'_, UrlQuery<'_>>

Manipulate this URL’s query string, viewed as a sequence of name/value pairs in application/x-www-form-urlencoded syntax.

The return value has a method-chaining API:


let mut url = Url::parse("https://example.net?lang=fr#nav")?;
assert_eq!(url.query(), Some("lang=fr"));

url.query_pairs_mut().append_pair("foo", "bar");
assert_eq!(url.query(), Some("lang=fr&foo=bar"));
assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");

url.query_pairs_mut()
    .clear()
    .append_pair("foo", "bar & baz")
    .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
assert_eq!(url.as_str(),
           "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");

Note: url.query_pairs_mut().clear(); is equivalent to url.set_query(Some("")), not url.set_query(None).

The state of Url is unspecified if this return value is leaked without being dropped.

source

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

Change this URL’s path.

Examples
use url::Url;

let mut url = Url::parse("https://example.com")?;
url.set_path("api/comments");
assert_eq!(url.as_str(), "https://example.com/api/comments");
assert_eq!(url.path(), "/api/comments");

let mut url = Url::parse("https://example.com/api")?;
url.set_path("data/report.csv");
assert_eq!(url.as_str(), "https://example.com/data/report.csv");
assert_eq!(url.path(), "/data/report.csv");

// `set_path` percent-encodes the given string if it's not already percent-encoded.
let mut url = Url::parse("https://example.com")?;
url.set_path("api/some comments");
assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
assert_eq!(url.path(), "/api/some%20comments");

// `set_path` will not double percent-encode the string if it's already percent-encoded.
let mut url = Url::parse("https://example.com")?;
url.set_path("api/some%20comments");
assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
assert_eq!(url.path(), "/api/some%20comments");
source

pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut<'_>, ()>

Return an object with methods to manipulate this URL’s path segments.

Return Err(()) if this URL is cannot-be-a-base.

source

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

Change this URL’s port number.

Note that default port numbers are not reflected in the serialization.

If this URL is cannot-be-a-base, does not have a host, or has the file scheme; do nothing and return Err.

Examples
use url::Url;

let mut url = Url::parse("ssh://example.net:2048/")?;

url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
assert_eq!(url.as_str(), "ssh://example.net:4096/");

url.set_port(None).map_err(|_| "cannot be base")?;
assert_eq!(url.as_str(), "ssh://example.net/");

Known default port numbers are not reflected:

use url::Url;

let mut url = Url::parse("https://example.org/")?;

url.set_port(Some(443)).map_err(|_| "cannot be base")?;
assert!(url.port().is_none());

Cannot set port for cannot-be-a-base URLs:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net")?;

let result = url.set_port(Some(80));
assert!(result.is_err());

let result = url.set_port(None);
assert!(result.is_err());
source

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

Change this URL’s host.

Removing the host (calling this with None) will also remove any username, password, and port number.

Examples

Change host:

use url::Url;

let mut url = Url::parse("https://example.net")?;
let result = url.set_host(Some("rust-lang.org"));
assert!(result.is_ok());
assert_eq!(url.as_str(), "https://rust-lang.org/");

Remove host:

use url::Url;

let mut url = Url::parse("foo://example.net")?;
let result = url.set_host(None);
assert!(result.is_ok());
assert_eq!(url.as_str(), "foo:/");

Cannot remove host for ‘special’ schemes (e.g. http):

use url::Url;

let mut url = Url::parse("https://example.net")?;
let result = url.set_host(None);
assert!(result.is_err());
assert_eq!(url.as_str(), "https://example.net/");

Cannot change or remove host for cannot-be-a-base URLs:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net")?;

let result = url.set_host(Some("rust-lang.org"));
assert!(result.is_err());
assert_eq!(url.as_str(), "mailto:rms@example.net");

let result = url.set_host(None);
assert!(result.is_err());
assert_eq!(url.as_str(), "mailto:rms@example.net");
Errors

If this URL is cannot-be-a-base or there is an error parsing the given host, a ParseError variant will be returned.

source

pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()>

Change this URL’s host to the given IP address.

If this URL is cannot-be-a-base, do nothing and return Err.

Compared to Url::set_host, this skips the host parser.

Examples
use url::{Url, ParseError};

let mut url = Url::parse("http://example.com")?;
url.set_ip_host("127.0.0.1".parse().unwrap());
assert_eq!(url.host_str(), Some("127.0.0.1"));
assert_eq!(url.as_str(), "http://127.0.0.1/");

Cannot change URL’s from mailto(cannot-be-base) to ip:

use url::{Url, ParseError};

let mut url = Url::parse("mailto:rms@example.com")?;
let result = url.set_ip_host("127.0.0.1".parse().unwrap());

assert_eq!(url.as_str(), "mailto:rms@example.com");
assert!(result.is_err());
source

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

Change this URL’s password.

If this URL is cannot-be-a-base or does not have a host, do nothing and return Err.

Examples
use url::{Url, ParseError};

let mut url = Url::parse("mailto:rmz@example.com")?;
let result = url.set_password(Some("secret_password"));
assert!(result.is_err());

let mut url = Url::parse("ftp://user1:secret1@example.com")?;
let result = url.set_password(Some("secret_password"));
assert_eq!(url.password(), Some("secret_password"));

let mut url = Url::parse("ftp://user2:@example.com")?;
let result = url.set_password(Some("secret2"));
assert!(result.is_ok());
assert_eq!(url.password(), Some("secret2"));
source

pub fn set_username(&mut self, username: &str) -> Result<(), ()>

Change this URL’s username.

If this URL is cannot-be-a-base or does not have a host, do nothing and return Err.

Examples

Cannot setup username from mailto(cannot-be-base)

use url::{Url, ParseError};

let mut url = Url::parse("mailto:rmz@example.com")?;
let result = url.set_username("user1");
assert_eq!(url.as_str(), "mailto:rmz@example.com");
assert!(result.is_err());

Setup username to user1

use url::{Url, ParseError};

let mut url = Url::parse("ftp://:secre1@example.com/")?;
let result = url.set_username("user1");
assert!(result.is_ok());
assert_eq!(url.username(), "user1");
assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
source

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

Change this URL’s scheme.

Do nothing and return Err under the following circumstances:

  • If the new scheme is not in [a-zA-Z][a-zA-Z0-9+.-]+
  • If this URL is cannot-be-a-base and the new scheme is one of http, https, ws, wss or ftp
  • If either the old or new scheme is http, https, ws, wss or ftp and the other is not one of these
  • If the new scheme is file and this URL includes credentials or has a non-null port
  • If this URL’s scheme is file and its host is empty or null

See also the URL specification’s section on legal scheme state overrides.

Examples

Change the URL’s scheme from https to http:

use url::Url;

let mut url = Url::parse("https://example.net")?;
let result = url.set_scheme("http");
assert_eq!(url.as_str(), "http://example.net/");
assert!(result.is_ok());

Change the URL’s scheme from foo to bar:

use url::Url;

let mut url = Url::parse("foo://example.net")?;
let result = url.set_scheme("bar");
assert_eq!(url.as_str(), "bar://example.net");
assert!(result.is_ok());

Cannot change URL’s scheme from https to foõ:

use url::Url;

let mut url = Url::parse("https://example.net")?;
let result = url.set_scheme("foõ");
assert_eq!(url.as_str(), "https://example.net/");
assert!(result.is_err());

Cannot change URL’s scheme from mailto (cannot-be-a-base) to https:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net")?;
let result = url.set_scheme("https");
assert_eq!(url.as_str(), "mailto:rms@example.net");
assert!(result.is_err());

Cannot change the URL’s scheme from foo to https:

use url::Url;

let mut url = Url::parse("foo://example.net")?;
let result = url.set_scheme("https");
assert_eq!(url.as_str(), "foo://example.net");
assert!(result.is_err());

Cannot change the URL’s scheme from http to foo:

use url::Url;

let mut url = Url::parse("http://example.net")?;
let result = url.set_scheme("foo");
assert_eq!(url.as_str(), "http://example.net/");
assert!(result.is_err());
source

pub fn serialize_internal<S>( &self, serializer: S ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize with Serde using the internal representation of the Url struct.

The corresponding deserialize_internal method sacrifices some invariant-checking for speed, compared to the Deserialize trait impl.

This method is only available if the serde Cargo feature is enabled.

source

pub fn to_file_path(&self) -> Result<PathBuf, ()>

Assuming the URL is in the file scheme or similar, convert its path to an absolute std::path::Path.

Note: This does not actually check the URL’s scheme, and may give nonsensical results for other schemes. It is the user’s responsibility to check the URL’s scheme before calling this.

let path = url.to_file_path();

Returns Err if the host is neither empty nor "localhost" (except on Windows, where file: URLs may have a non-local host), or if Path::new_opt() returns None. (That is, if the percent-decoded path contains a NUL byte or, for a Windows path, is not UTF-8.)

Trait Implementations§

source§

impl AsMut<Url> for Url2

source§

fn as_mut(&mut self) -> &mut Url

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<Url> for Url2

source§

fn as_ref(&self) -> &Url

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

impl AsRef<Url2> for ProxyUrl

§

fn as_ref(&self) -> &Url2

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

impl AsRef<str> for Url2

source§

fn as_ref(&self) -> &str

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

impl Borrow<Url> for Url2

source§

fn borrow(&self) -> &Url

Immutably borrows from an owned value. Read more
source§

impl Borrow<str> for Url2

source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
source§

impl BorrowMut<Url> for Url2

source§

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

Mutably borrows from an owned value. Read more
source§

impl Clone for Url2

source§

fn clone(&self) -> Url2

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 Url2

source§

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

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

impl Default for Url2

source§

fn default() -> Url2

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

impl Deref for Url2

§

type Target = Url

The resulting type after dereferencing.
source§

fn deref(&self) -> &<Url2 as Deref>::Target

Dereferences the value.
source§

impl DerefMut for Url2

source§

fn deref_mut(&mut self) -> &mut <Url2 as Deref>::Target

Mutably dereferences the value.
source§

impl<'de> Deserialize<'de> for Url2

source§

fn deserialize<D>( deserializer: D ) -> Result<Url2, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Url2

source§

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

Formats the value using the given formatter. Read more
§

impl From<&ProxyUrl> for Url2

§

fn from(url: &ProxyUrl) -> Url2

Converts to this type from the input type.
source§

impl From<&Url> for Url2

source§

fn from(url: &Url) -> Url2

Converts to this type from the input type.
§

impl From<&Url2> for ProxyUrl

§

fn from(url: &Url2) -> ProxyUrl

Converts to this type from the input type.
§

impl From<ProxyUrl> for Url2

§

fn from(url: ProxyUrl) -> Url2

Converts to this type from the input type.
source§

impl From<TxUrl> for Url2

source§

fn from(u: TxUrl) -> Url2

Converts to this type from the input type.
source§

impl From<Url> for Url2

source§

fn from(url: Url) -> Url2

Converts to this type from the input type.
§

impl From<Url2> for ProxyUrl

§

fn from(url: Url2) -> ProxyUrl

Converts to this type from the input type.
source§

impl From<Url2> for String

source§

fn from(url: Url2) -> String

Converts to this type from the input type.
source§

impl From<Url2> for TxUrl

source§

fn from(r: Url2) -> TxUrl

Converts to this type from the input type.
source§

impl From<Url2> for Url

source§

fn from(url: Url2) -> Url

Converts to this type from the input type.
source§

impl Hash for Url2

source§

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

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 Url2

source§

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

This method returns an Ordering between self and other. Read more
1.21.0 · source§

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

Compares and returns the maximum of two values. Read more
1.21.0 · source§

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

Compares and returns the minimum of two values. Read more
1.50.0 · source§

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

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

impl PartialEq<Url> for Url2

source§

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

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

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq for Url2

source§

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

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

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<Url> for Url2

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

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

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

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

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

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

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl PartialOrd for Url2

source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

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

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

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

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

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

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for Url2

source§

fn serialize<S>( &self, serializer: S ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Eq for Url2

Auto Trait Implementations§

§

impl RefUnwindSafe for Url2

§

impl Send for Url2

§

impl Sync for Url2

§

impl Unpin for Url2

§

impl UnwindSafe for Url2

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
§

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

§

fn into_any(self: Box<T>) -> Box<dyn Any>

§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
§

impl<S> AsComponentExternName for S
where S: AsRef<str>,

§

fn as_component_extern_name(&self) -> ComponentExternName<'_>

Converts this receiver into a ComponentExternName.
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
§

impl<T> CallHasher for T
where T: Hash + ?Sized,

§

default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64
where H: Hash + ?Sized, B: BuildHasher,

§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<S> ParseFormatted for S
where S: AsRef<str>,

source§

fn parse_formatted<F, N>(&self, format: &F) -> Result<N, Error>
where F: Format, N: FromFormattedStr,

Converts self (typically a formatted string) into a number (see Examples above).
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for T
where 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 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>,

§

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>,

§

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

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
§

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

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> AutoBTreeMapKey for T

§

impl<T> AutoHashMapKey for T

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

§

impl<T> Sequence for T
where T: Eq + Hash,