# url

rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
for the [Rust](http://rust-lang.org/) programming language.


# URL parsing and data structures

First, URL parsing may fail for various reasons and therefore returns a `Result`.

```
use url::{Url, ParseError};

assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
```

Let’s parse a valid URL and look at its components.

```
use url::{Url, Host, Position};
# use url::ParseError;
# fn run() -> Result<(), ParseError> {
let issue_list_url = Url::parse(
    "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
)?;


assert!(issue_list_url.scheme() == "https");
assert!(issue_list_url.username() == "");
assert!(issue_list_url.password() == None);
assert!(issue_list_url.host_str() == Some("github.com"));
assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
assert!(issue_list_url.port() == None);
assert!(issue_list_url.path() == "/rust-lang/rust/issues");
assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
        Some(vec!["rust-lang", "rust", "issues"]));
assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
assert!(issue_list_url.fragment() == None);
assert!(!issue_list_url.cannot_be_a_base());
# Ok(())
# }
# run().unwrap();
```

Some URLs are said to be *cannot-be-a-base*:
they don’t have a username, password, host, or port,
and their "path" is an arbitrary string rather than slash-separated segments:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let data_url = Url::parse("data:text/plain,Hello?World#")?;

assert!(data_url.cannot_be_a_base());
assert!(data_url.scheme() == "data");
assert!(data_url.path() == "text/plain,Hello");
assert!(data_url.path_segments().is_none());
assert!(data_url.query() == Some("World"));
assert!(data_url.fragment() == Some(""));
# Ok(())
# }
# run().unwrap();
```

## Default Features

Versions `<= 2.5.2` of the crate have no default features. Versions `> 2.5.2` have the default feature 'std'.
If you are upgrading across this boundary and you have specified `default-features = false`, then
you will need to add the 'std' feature or the 'alloc' feature to your dependency.
The 'std' feature has the same behavior as the previous versions. The 'alloc' feature
provides no_std support.

## Serde

Enable the `serde` feature to include `Deserialize` and `Serialize` implementations for `url::Url`.

# Base URL

Many contexts allow URL *references* that can be relative to a *base URL*:

```html
<link rel="stylesheet" href="../main.css">
```

Since parsed URLs are absolute, giving a base is required for parsing relative URLs:

```
use url::{Url, ParseError};

assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
```

Use the `join` method on an `Url` to use it as a base URL:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
let css_url = this_document.join("../main.css")?;
assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
# Ok(())
# }
# run().unwrap();
```

# Feature: `serde`

If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
[`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
[`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
See [serde documentation](https://serde.rs) for more information.

```toml
url = { version = "2", features = ["serde"] }
```

# Feature: `debugger_visualizer`

If you enable the `debugger_visualizer` feature, the `url` crate will include
a [natvis file](https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects)
for [Visual Studio](https://www.visualstudio.com/) that allows you to view
[`Url`](struct.Url.html) objects in the debugger.

This feature requires Rust 1.71 or later.

```toml
url = { version = "2", features = ["debugger_visualizer"] }
```

<a id="struct.Url"></a>

## Url

```rust
pub struct url::Url { /* ... */ }
```

A parsed URL record.

<a id="impl-Url"></a>

## impl Url

<a id="method.parse"></a>

## parse

```rust
fn parse(input: &str) -> Result<Self, crate::ParseError>
```

Parse an absolute URL from a string.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse("https://example.net")?;
# Ok(())
# }
# run().unwrap();
```

# Errors

If the function can not parse an absolute URL from the given string,
a [`ParseError`] variant will be returned.

[`ParseError`]: enum.ParseError.html

<a id="method.parse_with_params"></a>

## parse_with_params

```rust
fn parse_with_params(input: &str, iter: I) -> Result<Self, crate::ParseError>
```

Parse an absolute URL from a string and add params to its query string.

Existing params are not removed.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse_with_params("https://example.net?dont=clobberme",
                                 &[("lang", "rust"), ("browser", "servo")])?;
assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str());
# Ok(())
# }
# run().unwrap();
```

# Errors

If the function can not parse an absolute URL from the given string,
a [`ParseError`] variant will be returned.

[`ParseError`]: enum.ParseError.html

<a id="method.join"></a>

## join

```rust
fn join(self: &Self, input: &str) -> Result<Self, crate::ParseError>
```

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

The inverse of this is [`make_relative`].

# Notes

- 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.
- A [scheme relative special URL](https://url.spec.whatwg.org/#scheme-relative-special-url-string)
  as input replaces everything in the base URL after the scheme.
- An absolute URL (with a scheme) as input replaces the whole base URL (even the scheme).

# Examples

```rust
use url::Url;
# use url::ParseError;

// Base without a trailing slash
# fn run() -> Result<(), ParseError> {
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

// Base with a trailing slash
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");

// Input as scheme relative special URL
let base = Url::parse("https://alice.com/a")?;
let url = base.join("//eve.com/b")?;
assert_eq!(url.as_str(), "https://eve.com/b");

// Input as base url relative special URL
let base = Url::parse("https://alice.com/a")?;
let url = base.join("/v1/meta")?;
assert_eq!(url.as_str(), "https://alice.com/v1/meta");

// Input as absolute URL
let base = Url::parse("https://alice.com/a")?;
let url = base.join("http://eve.com/b")?;
assert_eq!(url.as_str(), "http://eve.com/b");  // http instead of https

# Ok(())
# }
# run().unwrap();
```

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

[`ParseError`]: enum.ParseError.html
[`make_relative`]: #method.make_relative

<a id="method.make_relative"></a>

## make_relative

```rust
fn make_relative(self: &Self, url: &Self) -> Option<String>
```

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

This is the inverse of [`join`].

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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"));
# Ok(())
# }
# run().unwrap();
```

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

[`join`]: #method.join

<a id="method.options"></a>

## options

```rust
fn options() -> ParseOptions<'a>
```

Return a default `ParseOptions` that can fully configure the URL parser.

# Examples

Get default `ParseOptions`, then change base url

```rust
use url::Url;
# use url::ParseError;
# fn run() -> Result<(), ParseError> {
let options = Url::options();
let api = Url::parse("https://api.example.com")?;
let base_url = options.base_url(Some(&api));
let version_url = base_url.parse("version.json")?;
assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
# Ok(())
# }
# run().unwrap();
```

<a id="method.as_str"></a>

## as_str

```rust
fn as_str(self: &Self) -> &str
```

Return the serialization of this URL.

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

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url_str = "https://example.net/";
let url = Url::parse(url_str)?;
assert_eq!(url.as_str(), url_str);
# Ok(())
# }
# run().unwrap();
```

<a id="method.into_string"></a>

## into_string

```rust
fn into_string(self: Self) -> String
```

Return the serialization of this URL.

This consumes the `Url` and takes ownership of the `String` stored in it.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url_str = "https://example.net/";
let url = Url::parse(url_str)?;
assert_eq!(String::from(url), url_str);
# Ok(())
# }
# run().unwrap();
```

<a id="method.origin"></a>

## origin

```rust
fn origin(self: &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:

```rust
use url::{Host, Origin, Url};
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse("ftp://example.com/foo")?;
assert_eq!(url.origin(),
           Origin::Tuple("ftp".into(),
                         Host::Domain("example.com".into()),
                         21));
# Ok(())
# }
# run().unwrap();
```

URL with `blob` scheme:

```rust
use url::{Host, Origin, Url};
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse("blob:https://example.com/foo")?;
assert_eq!(url.origin(),
           Origin::Tuple("https".into(),
                         Host::Domain("example.com".into()),
                         443));
# Ok(())
# }
# run().unwrap();
```

URL with `file` scheme:

```rust
use url::{Host, Origin, Url};
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

URL with other scheme:

```rust
use url::{Host, Origin, Url};
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse("foo:bar")?;
assert!(!url.origin().is_tuple());
# Ok(())
# }
# run().unwrap();
```

<a id="method.scheme"></a>

## scheme

```rust
fn scheme(self: &Self) -> &str
```

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

# Examples

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let url = Url::parse("file:///tmp/foo")?;
assert_eq!(url.scheme(), "file");
# Ok(())
# }
# run().unwrap();
```

<a id="method.is_special"></a>

## is_special

```rust
fn is_special(self: &Self) -> bool
```

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

# Examples

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
assert!(Url::parse("http:///tmp/foo")?.is_special());
assert!(Url::parse("file:///tmp/foo")?.is_special());
assert!(!Url::parse("moz:///tmp/foo")?.is_special());
# Ok(())
# }
# run().unwrap();
```

<a id="method.has_authority"></a>

## has_authority

```rust
fn has_authority(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.authority"></a>

## authority

```rust
fn authority(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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");
# Ok(())
# }
# run().unwrap();
```

<a id="method.cannot_be_a_base"></a>

## cannot_be_a_base

```rust
fn cannot_be_a_base(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.username"></a>

## username

```rust
fn username(self: &Self) -> &str
```

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

# Examples

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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(), "");
# Ok(())
# }
# run().unwrap();
```

<a id="method.password"></a>

## password

```rust
fn password(self: &Self) -> Option<&str>
```

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

# Examples

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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);
# Ok(())
# }
# run().unwrap();
```

<a id="method.has_host"></a>

## has_host

```rust
fn has_host(self: &Self) -> bool
```

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

# Examples

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.host_str"></a>

## host_str

```rust
fn host_str(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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("https://subdomain.example.com")?;
assert_eq!(url.host_str(), Some("subdomain.example.com"));

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);
# Ok(())
# }
# run().unwrap();
```

<a id="method.host"></a>

## host

```rust
fn host(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.domain"></a>

## domain

```rust
fn domain(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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"));

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

# Ok(())
# }
# run().unwrap();
```

<a id="method.port"></a>

## port

```rust
fn port(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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));
# Ok(())
# }
# run().unwrap();
```

<a id="method.port_or_known_default"></a>

## port_or_known_default

```rust
fn port_or_known_default(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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));
# Ok(())
# }
# run().unwrap();
```

<a id="method.socket_addrs"></a>

## socket_addrs

```rust
fn socket_addrs(self: &Self, default_port_number: impl Fn() -> Option<u16>) -> io::Result<alloc::vec::Vec<SocketAddr>>
```

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

```no_run
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,
    })
}
```

<a id="method.path"></a>

## path

```rust
fn path(self: &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

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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");
# Ok(())
# }
# run().unwrap();
```

<a id="method.path_segments"></a>

## path_segments

```rust
fn path_segments(self: &Self) -> Option<str::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;

# #[cfg(feature = "std")]
# use std::error::Error;
# #[cfg(not(feature = "std"))]
# use core::error::Error;

# fn run() -> Result<(), Box<dyn Error>> {
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"));
# Ok(())
# }
# run().unwrap();
```

<a id="method.query"></a>

## query

```rust
fn query(self: &Self) -> Option<&str>
```

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

# Examples

```rust
use url::Url;
# use url::ParseError;

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"));
# Ok(())
# }
# run().unwrap();
```

<a id="method.query_pairs"></a>

## query_pairs

```rust
fn query_pairs(self: &Self) -> form_urlencoded::Parse<'_>
```

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

# Examples

```rust
use std::borrow::Cow;

use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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"))));
# Ok(())
# }
# run().unwrap();
```

<a id="method.fragment"></a>

## fragment

```rust
fn fragment(self: &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

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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"));
# Ok(())
# }
# run().unwrap();
```

<a id="method.set_fragment"></a>

## set_fragment

```rust
fn set_fragment(self: &mut Self, fragment: Option<&str>)
```

Change this URL’s fragment identifier.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.set_query"></a>

## set_query

```rust
fn set_query(self: &mut Self, query: Option<&str>)
```

Change this URL’s query string. If `query` is `None`, this URL's
query string will be cleared.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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"));
# Ok(())
# }
# run().unwrap();
```

<a id="method.query_pairs_mut"></a>

## query_pairs_mut

```rust
fn query_pairs_mut(self: &mut Self) -> form_urlencoded::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:

```rust
# use url::{Url, ParseError};

# fn run() -> Result<(), ParseError> {
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");
# Ok(())
# }
# run().unwrap();
```

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.

<a id="method.set_path"></a>

## set_path

```rust
fn set_path(self: &mut Self, path: &str)
```

Change this URL’s path.

# Examples

```rust
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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");

# Ok(())
# }
# run().unwrap();
```

<a id="method.path_segments_mut"></a>

## path_segments_mut

```rust
fn path_segments_mut(self: &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.

<a id="method.set_port"></a>

## set_port

```rust
fn set_port(self: &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;

# #[cfg(feature = "std")]
# use std::error::Error;
# #[cfg(not(feature = "std"))]
# use core::error::Error;

# fn run() -> Result<(), Box<dyn Error>> {
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/");
# Ok(())
# }
# run().unwrap();
```

Known default port numbers are not reflected:

```rust
use url::Url;

# #[cfg(feature = "std")]
# use std::error::Error;
# #[cfg(not(feature = "std"))]
# use core::error::Error;

# fn run() -> Result<(), Box<dyn Error>> {
let mut url = Url::parse("https://example.org/")?;

url.set_port(Some(443)).map_err(|_| "cannot be base")?;
assert!(url.port().is_none());
# Ok(())
# }
# run().unwrap();
```

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

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.set_host"></a>

## set_host

```rust
fn set_host(self: &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;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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/");
# Ok(())
# }
# run().unwrap();
```

Remove host:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
let mut url = Url::parse("foo://example.net")?;
let result = url.set_host(None);
assert!(result.is_ok());
assert_eq!(url.as_str(), "foo:/");
# Ok(())
# }
# run().unwrap();
```

Cannot remove host for 'special' schemes (e.g. `http`):

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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/");
# Ok(())
# }
# run().unwrap();
```

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

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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");
# Ok(())
# }
# run().unwrap();
```

# Errors

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

[`ParseError`]: enum.ParseError.html

<a id="method.set_ip_host"></a>

## set_ip_host

```rust
fn set_ip_host(self: &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

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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/");
# Ok(())
# }
# run().unwrap();
```

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

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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());
# Ok(())
# }
# run().unwrap();
```


<a id="method.set_password"></a>

## set_password

```rust
fn set_password(self: &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

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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"));
# Ok(())
# }
# run().unwrap();
```

<a id="method.set_username"></a>

## set_username

```rust
fn set_username(self: &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)

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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());
# Ok(())
# }
# run().unwrap();
```

Setup username to user1

```rust
use url::{Url, ParseError};

# fn run() -> Result<(), 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/");
# Ok(())
# }
# run().unwrap();
```

<a id="method.set_scheme"></a>

## set_scheme

```rust
fn set_scheme(self: &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](https://url.spec.whatwg.org/#scheme-state).

# Examples

Change the URL’s scheme from `https` to `http`:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```
Change the URL’s scheme from `foo` to `bar`:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

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

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

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

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```
Cannot change the URL’s scheme from `foo` to `https`:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```
Cannot change the URL’s scheme from `http` to `foo`:

```
use url::Url;
# use url::ParseError;

# fn run() -> Result<(), ParseError> {
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());
# Ok(())
# }
# run().unwrap();
```

<a id="method.from_file_path"></a>

## from_file_path

```rust
fn from_file_path(path: P) -> Result<Self, ()>
```

Convert a file name as `std::path::Path` into an URL in the `file` scheme.

This returns `Err` if the given path is not absolute or,
on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).

# Examples

On Unix-like platforms:

```
# if cfg!(unix) {
use url::Url;

# fn run() -> Result<(), ()> {
let url = Url::from_file_path("/tmp/foo.txt")?;
assert_eq!(url.as_str(), "file:///tmp/foo.txt");

let url = Url::from_file_path("../foo.txt");
assert!(url.is_err());

let url = Url::from_file_path("https://google.com/");
assert!(url.is_err());
# Ok(())
# }
# run().unwrap();
# }
```

This method is only available if the `std` Cargo feature is enabled.

<a id="method.from_directory_path"></a>

## from_directory_path

```rust
fn from_directory_path(path: P) -> Result<Self, ()>
```

Convert a directory name as `std::path::Path` into an URL in the `file` scheme.

This returns `Err` if the given path is not absolute or,
on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).

Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
so that the entire path is considered when using this URL as a base URL.

For example:

* `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  as the base URL is `file:///var/www/index.html`
* `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  as the base URL is `file:///var/index.html`, which might not be what was intended.

Note that `std::path` does not consider trailing slashes significant
and usually does not include them (e.g. in `Path::parent()`).

This method is only available if the `std` Cargo feature is enabled.

<a id="method.to_file_path"></a>

## to_file_path

```rust
fn to_file_path(self: &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.

```
# use url::Url;
# let url = Url::parse("file:///etc/passwd").unwrap();
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.)

This method is only available if the `std` Cargo feature is enabled.

<a id="impl-Send-for-Url"></a>

## impl Send for Url

<a id="impl-Sync-for-Url"></a>

## impl Sync for Url

<a id="impl-Freeze-for-Url"></a>

## impl Freeze for Url

<a id="impl-UnsafeUnpin-for-Url"></a>

## impl UnsafeUnpin for Url

<a id="impl-Unpin-for-Url"></a>

## impl Unpin for Url

<a id="impl-UnwindSafe-for-Url"></a>

## impl UnwindSafe for Url

<a id="impl-RefUnwindSafe-for-Url"></a>

## impl RefUnwindSafe for Url

<a id="impl-Borrow-for-Url"></a>

## impl Borrow for Url

<a id="method.borrow"></a>

## borrow

```rust
fn borrow(self: &Self) -> &T
```

<a id="impl-BorrowMut-for-Url"></a>

## impl BorrowMut for Url

<a id="method.borrow_mut"></a>

## borrow_mut

```rust
fn borrow_mut(self: &mut Self) -> &mut T
```

<a id="impl-CloneToUninit-for-Url"></a>

## impl CloneToUninit for Url

<a id="method.clone_to_uninit"></a>

## clone_to_uninit

```rust
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
```

<a id="impl-Into-for-Url"></a>

## impl Into for Url

<a id="method.into"></a>

## into

```rust
fn into(self: Self) -> U
```

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of
<code>[From]&lt;T&gt; for U</code> chooses to do.

[From]: https://doc.rust-lang.org/stable/core/convert/trait.From.html

<a id="impl-From-for-Url"></a>

## impl From for Url

<a id="method.from"></a>

## from

```rust
fn from(t: T) -> T
```

Returns the argument unchanged.

<a id="impl-TryInto-for-Url"></a>

## impl TryInto for Url

<a id="associatedtype.Error"></a>

## Error

<a id="method.try_into"></a>

## try_into

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

<a id="impl-TryFrom-for-Url"></a>

## impl TryFrom for Url

<a id="associatedtype.Error"></a>

## Error

<a id="method.try_from"></a>

## try_from

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

<a id="impl-Any-for-Url"></a>

## impl Any for Url

<a id="method.type_id"></a>

## type_id

```rust
fn type_id(self: &Self) -> TypeId
```

<a id="impl-ToOwned-for-Url"></a>

## impl ToOwned for Url

<a id="associatedtype.Owned"></a>

## Owned

<a id="method.to_owned"></a>

## to_owned

```rust
fn to_owned(self: &Self) -> T
```

<a id="method.clone_into"></a>

## clone_into

```rust
fn clone_into(self: &Self, target: &mut T)
```

<a id="impl-ToString-for-Url"></a>

## impl ToString for Url

<a id="method.to_string"></a>

## to_string

```rust
fn to_string(self: &Self) -> String
```

<a id="impl-Index-for-crate::Url"></a>

## impl Index for crate::Url

<a id="associatedtype.Output"></a>

## Output

<a id="method.index"></a>

## index

```rust
fn index(self: &Self, _: RangeFull) -> &str
```

<a id="impl-Index-for-crate::Url"></a>

## impl Index for crate::Url

<a id="associatedtype.Output"></a>

## Output

<a id="method.index"></a>

## index

```rust
fn index(self: &Self, range: RangeFrom<Position>) -> &str
```

<a id="impl-Index-for-crate::Url"></a>

## impl Index for crate::Url

<a id="associatedtype.Output"></a>

## Output

<a id="method.index"></a>

## index

```rust
fn index(self: &Self, range: RangeTo<Position>) -> &str
```

<a id="impl-Index-for-crate::Url"></a>

## impl Index for crate::Url

<a id="associatedtype.Output"></a>

## Output

<a id="method.index"></a>

## index

```rust
fn index(self: &Self, range: Range<Position>) -> &str
```

<a id="impl-Clone-for-Url"></a>

## impl Clone for Url

<a id="method.clone"></a>

## clone

```rust
fn clone(self: &Self) -> Url
```

<a id="impl-FromStr-for-Url"></a>

## impl FromStr for Url

Parse a string as an URL, without a base URL or encoding override.

<a id="associatedtype.Err"></a>

## Err

<a id="method.from_str"></a>

## from_str

```rust
fn from_str(input: &str) -> Result<Self, crate::ParseError>
```

<a id="impl-TryFrom-for-Url"></a>

## impl TryFrom for Url

<a id="associatedtype.Error"></a>

## Error

<a id="method.try_from"></a>

## try_from

```rust
fn try_from(s: &'a str) -> Result<Self, <Self as >::Error>
```

<a id="impl-Display-for-Url"></a>

## impl Display for Url

Display the serialization of this URL.

<a id="method.fmt"></a>

## fmt

```rust
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
```

<a id="impl-From-for-alloc::string::String"></a>

## impl From for alloc::string::String

String conversion.

<a id="method.from"></a>

## from

```rust
fn from(value: Url) -> Self
```

<a id="impl-Debug-for-Url"></a>

## impl Debug for Url

Debug the serialization of this URL.

<a id="method.fmt"></a>

## fmt

```rust
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
```

<a id="impl-Eq-for-Url"></a>

## impl Eq for Url

URLs compare like their serialization.

<a id="impl-PartialEq-for-Url"></a>

## impl PartialEq for Url

URLs compare like their serialization.

<a id="method.eq"></a>

## eq

```rust
fn eq(self: &Self, other: &Self) -> bool
```

<a id="impl-Ord-for-Url"></a>

## impl Ord for Url

URLs compare like their serialization.

<a id="method.cmp"></a>

## cmp

```rust
fn cmp(self: &Self, other: &Self) -> cmp::Ordering
```

<a id="impl-PartialOrd-for-Url"></a>

## impl PartialOrd for Url

URLs compare like their serialization.

<a id="method.partial_cmp"></a>

## partial_cmp

```rust
fn partial_cmp(self: &Self, other: &Self) -> Option<cmp::Ordering>
```

<a id="impl-Hash-for-Url"></a>

## impl Hash for Url

URLs hash like their serialization.

<a id="method.hash"></a>

## hash

```rust
fn hash(self: &Self, state: &mut H)
```

<a id="impl-AsRef-for-Url"></a>

## impl AsRef for Url

Return the serialization of this URL.

<a id="method.as_ref"></a>

## as_ref

```rust
fn as_ref(self: &Self) -> &str
```

<a id="struct.ParseOptions"></a>

## ParseOptions

```rust
pub struct url::ParseOptions { /* ... */ }
```

Full configuration for the URL parser.

<a id="impl-ParseOptions"></a>

## impl ParseOptions

<a id="method.base_url"></a>

## base_url

```rust
fn base_url(self: Self, new: Option<&'a Url>) -> Self
```

Change the base URL

See the notes of [`Url::join`] for more details about how this base is considered
when parsing.

[Url::join]: https://sourcey.com/examples/docs-showcase/reference/rust/pkg-url-url.md#method.join

<a id="method.encoding_override"></a>

## encoding_override

```rust
fn encoding_override(self: Self, new: EncodingOverride<'a>) -> Self
```

Override the character encoding of query strings.
This is a legacy concept only relevant for HTML.

<a id="method.syntax_violation_callback"></a>

## syntax_violation_callback

```rust
fn syntax_violation_callback(self: Self, new: Option<&'a dyn Fn(SyntaxViolation)>) -> Self
```

Call the provided function or closure for a non-fatal `SyntaxViolation`
when it occurs during parsing. Note that since the provided function is
`Fn`, the caller might need to utilize _interior mutability_, such as with
a `RefCell`, to collect the violations.

## Example
```
use std::cell::RefCell;
use url::{Url, SyntaxViolation};
# use url::ParseError;
# fn run() -> Result<(), url::ParseError> {
let violations = RefCell::new(Vec::new());
let url = Url::options()
    .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
    .parse("https:////example.com")?;
assert_eq!(url.as_str(), "https://example.com/");
assert_eq!(violations.into_inner(),
           vec!(SyntaxViolation::ExpectedDoubleSlash));
# Ok(())
# }
# run().unwrap();
```

<a id="method.parse"></a>

## parse

```rust
fn parse(self: Self, input: &str) -> Result<Url, crate::ParseError>
```

Parse an URL string with the configuration so far.

<a id="impl-Send-for-ParseOptions"></a>

## impl Send for ParseOptions

<a id="impl-Sync-for-ParseOptions"></a>

## impl Sync for ParseOptions

<a id="impl-Freeze-for-ParseOptions"></a>

## impl Freeze for ParseOptions

<a id="impl-UnsafeUnpin-for-ParseOptions"></a>

## impl UnsafeUnpin for ParseOptions

<a id="impl-Unpin-for-ParseOptions"></a>

## impl Unpin for ParseOptions

<a id="impl-UnwindSafe-for-ParseOptions"></a>

## impl UnwindSafe for ParseOptions

<a id="impl-RefUnwindSafe-for-ParseOptions"></a>

## impl RefUnwindSafe for ParseOptions

<a id="impl-Borrow-for-ParseOptions"></a>

## impl Borrow for ParseOptions

<a id="impl-BorrowMut-for-ParseOptions"></a>

## impl BorrowMut for ParseOptions

<a id="impl-CloneToUninit-for-ParseOptions"></a>

## impl CloneToUninit for ParseOptions

<a id="impl-Into-for-ParseOptions"></a>

## impl Into for ParseOptions

<a id="impl-From-for-ParseOptions"></a>

## impl From for ParseOptions

<a id="impl-TryInto-for-ParseOptions"></a>

## impl TryInto for ParseOptions

<a id="impl-TryFrom-for-ParseOptions"></a>

## impl TryFrom for ParseOptions

<a id="impl-Any-for-ParseOptions"></a>

## impl Any for ParseOptions

<a id="impl-ToOwned-for-ParseOptions"></a>

## impl ToOwned for ParseOptions

<a id="impl-Copy-for-ParseOptions"></a>

## impl Copy for ParseOptions

<a id="impl-Clone-for-ParseOptions"></a>

## impl Clone for ParseOptions

<a id="method.clone"></a>

## clone

```rust
fn clone(self: &Self) -> ParseOptions<'a>
```

<a id="struct.UrlQuery"></a>

## UrlQuery

```rust
pub struct url::UrlQuery { /* ... */ }
```

Implementation detail of `Url::query_pairs_mut`. Typically not used directly.

<a id="impl-Send-for-UrlQuery"></a>

## impl Send for UrlQuery

<a id="impl-Sync-for-UrlQuery"></a>

## impl Sync for UrlQuery

<a id="impl-Freeze-for-UrlQuery"></a>

## impl Freeze for UrlQuery

<a id="impl-UnsafeUnpin-for-UrlQuery"></a>

## impl UnsafeUnpin for UrlQuery

<a id="impl-Unpin-for-UrlQuery"></a>

## impl Unpin for UrlQuery

<a id="impl-UnwindSafe-for-UrlQuery"></a>

## impl UnwindSafe for UrlQuery

<a id="impl-RefUnwindSafe-for-UrlQuery"></a>

## impl RefUnwindSafe for UrlQuery

<a id="impl-Borrow-for-UrlQuery"></a>

## impl Borrow for UrlQuery

<a id="impl-BorrowMut-for-UrlQuery"></a>

## impl BorrowMut for UrlQuery

<a id="impl-Into-for-UrlQuery"></a>

## impl Into for UrlQuery

<a id="impl-From-for-UrlQuery"></a>

## impl From for UrlQuery

<a id="impl-TryInto-for-UrlQuery"></a>

## impl TryInto for UrlQuery

<a id="impl-TryFrom-for-UrlQuery"></a>

## impl TryFrom for UrlQuery

<a id="impl-Any-for-UrlQuery"></a>

## impl Any for UrlQuery

<a id="impl-Debug-for-UrlQuery"></a>

## impl Debug for UrlQuery

<a id="method.fmt"></a>

## fmt

```rust
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
```

<a id="impl-Target-for-UrlQuery"></a>

## impl Target for UrlQuery

<a id="method.as_mut_string"></a>

## as_mut_string

```rust
fn as_mut_string(self: &mut Self) -> &mut String
```

<a id="method.finish"></a>

## finish

```rust
fn finish(self: Self) -> &'a mut Url
```

<a id="associatedtype.Finished"></a>

## Finished

<a id="impl-Drop-for-UrlQuery"></a>

## impl Drop for UrlQuery

<a id="method.drop"></a>

## drop

```rust
fn drop(self: &mut Self)
```

<a id="reexport.form_urlencoded"></a>

## form_urlencoded

```rust
pub use form_urlencoded;
```

<a id="reexport.Host"></a>

## Host

```rust
pub use crate::host::Host;
```

<a id="reexport.OpaqueOrigin"></a>

## OpaqueOrigin

```rust
pub use crate::origin::OpaqueOrigin;
```

<a id="reexport.Origin"></a>

## Origin

```rust
pub use crate::origin::Origin;
```

<a id="reexport.ParseError"></a>

## ParseError

```rust
pub use crate::parser::ParseError;
```

<a id="reexport.SyntaxViolation"></a>

## SyntaxViolation

```rust
pub use crate::parser::SyntaxViolation;
```

<a id="reexport.PathSegmentsMut"></a>

## PathSegmentsMut

```rust
pub use crate::path_segments::PathSegmentsMut;
```

<a id="reexport.Position"></a>

## Position

```rust
pub use crate::slicing::Position;
```

<a id="reexport.EncodingOverride"></a>

## EncodingOverride

```rust
pub use form_urlencoded::EncodingOverride;
```
