Struct Uri
pub struct Uri { /* private fields */ }http only.Expand description
First-class URI value.
Represents any RFC 3986 URI-reference — an absolute URI
(http://example.com/path), a network-path (//host/path), an
origin-form path (/path?query), a relative reference (../foo,
?y, #frag), or the HTTP asterisk-form (*). Use
is_absolute to check for the scheme-bearing case.
Opaque — fields are private. Construct via Uri::parse (strict
shapes only) or Uri::parse_reference (all URI-references including
relatives); inspect via typed accessors (scheme,
path, query, fragment,
host, port, userinfo,
authority); mutate via the set_* / clear_*
methods.
Clone is cheap: Asterisk is zero-cost, Lazy / Owned clone is one
atomic refcount bump on the inner Arc.
§Logging safety
The Debug impl redacts the userinfo password
portion (anything after the first : inside user:pass@host),
rendering it as "***". This is the safe default for tracing spans
and log lines — a raw Debug-print would otherwise leak credentials
into observability sinks. The username portion is rendered as-is.
Display deliberately does not redact (it
is the wire-faithful form); use a dedicated wire writer such as
write_http_origin_form when
serializing for HTTP — those drop the userinfo entirely per RFC 9110
§4.2.4.
Implementations§
§impl Uri
impl Uri
pub fn write_http_origin_form(
&self,
buf: &mut BytesMut,
) -> Result<(), WireError>
Available on crate feature net only.
pub fn write_http_origin_form( &self, buf: &mut BytesMut, ) -> Result<(), WireError>
net only.HTTP/1.1 origin-form request-target: /path[?query].
Used for normal requests to an origin server (the common case).
Empty path is normalised to /. Scheme, authority, and fragment
are stripped — origin-form carries only the path-and-query.
Errors with WireError::AsteriskMismatch if the URI is * —
asterisk-form is its own request-target form (write * directly,
it’s a one-byte literal).
pub fn write_http_absolute_form(
&self,
buf: &mut BytesMut,
) -> Result<(), WireError>
Available on crate feature net only.
pub fn write_http_absolute_form( &self, buf: &mut BytesMut, ) -> Result<(), WireError>
net only.HTTP/1.1 absolute-form request-target:
scheme:[//authority]path[?query].
Used by clients sending through a forward proxy. Userinfo and fragment are stripped (RFC 9110 §§4.2.4, 7.1).
Available on crate feature net only.
net only.HTTP/1.1 authority-form request-target: host[:port].
Only used for CONNECT. Userinfo, scheme, path, query, and
fragment are all stripped.
Wire fidelity: an OptPort::Empty
port emits a bare trailing : (e.g. example.com:), mirroring
the parser. RFC 3986 §3.2.3 grammar permits this; some peers
may reject. Call Uri::canonicalize
first if you want the empty marker normalized away.
pub fn write_h2_path(&self, buf: &mut BytesMut)
Available on crate feature net only.
pub fn write_h2_path(&self, buf: &mut BytesMut)
net only.HTTP/2 / HTTP/3 :path pseudo-header content.
Same shape as origin-form (empty path → /), with one exception:
asterisk-form requests carry * in :path per RFC 9113 §8.3.1,
so this method writes * for an asterisk URI rather than
erroring.
Available on crate feature net only.
net only.HTTP/2 / HTTP/3 :authority pseudo-header content: host[:port].
Userinfo is omitted per RFC 9113 §8.3.1.
Wire fidelity: see write_http_authority_form
for the OptPort::Empty round-trip behavior.
pub fn write_h2_scheme(&self, buf: &mut BytesMut) -> Result<(), WireError>
Available on crate feature net only.
pub fn write_h2_scheme(&self, buf: &mut BytesMut) -> Result<(), WireError>
net only.HTTP/2 / HTTP/3 :scheme pseudo-header content (e.g. https).
§impl Uri
impl Uri
pub const MAX_LEN: usize = parser::MAX_URI_LEN
Available on crate feature net only.
pub const MAX_LEN: usize = parser::MAX_URI_LEN
net only.Maximum input length accepted by any of the Uri::parse* entry
points. Inputs longer than this fail with ParseError::TooLong.
Capped at u16::MAX - 1 (component offsets are u16).
pub fn parse<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Parse a URI. Graceful: accepts what browsers and curl accept
(e.g. unreserved chars outside RFC 3986’s pchar, raw UTF-8 in
path/query/fragment). Rejects: ASCII control bytes anywhere,
empty input, and inputs longer than the internal cap.
pub fn parse_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Parse a URI in RFC 3986 strict mode. Inputs that would parse
under Uri::parse but violate the strict grammar return
ParseError::StrictViolation.
pub fn parse_reference<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse_reference<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Parse any RFC 3986 URI-reference — absolute URI or relative-ref.
Accepts everything parse accepts, plus the
relative-ref grammar from §4.2:
- empty input (same-document reference)
//host/path(network-path reference)g,g/h,../g(path-noscheme)?y(query-only)#s(fragment-only)
Use this when parsing a reference to feed into
resolve.
pub fn parse_reference_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse_reference_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Strict variant of parse_reference.
pub fn from_static(s: &'static str) -> Uri
Available on crate feature net only.
pub fn from_static(s: &'static str) -> Uri
net only.Parse a &'static str URI, panicking on invalid input. Convenient
for compile-time-known URIs (constants, defaults, tests, examples)
where the failure mode is “this binary contains a typo” rather
than runtime input handling.
Uses the graceful parser — same shape as parse,
just without the Result. Use parse for any
runtime / user-supplied input.
§Panics
Panics with the underlying ParseError if s is not a valid
URI.
Available on crate feature net only.
net only.Parse the HTTP authority-form request-target used by CONNECT
(RFC 9112 §3.2.3).
Dedicated entry point because parse cannot
disambiguate authority-form from scheme:opaque-path —
example.com:443 is grammatically both
authority(example.com:443) and scheme(example.com) + opaque-path(443), and RFC 3986 prefers the scheme reading. HTTP
proxies and clients handling CONNECT must route those
targets through this function instead.
§Graceful grammar (this method): [userinfo@]host[:port]
Userinfo and a missing port are accepted as graceful conveniences
for HTTP tooling — userinfo is preserved on the value but
stripped by write_http_authority_form
before serialization, and the missing port is treated as “fill
in from the scheme” by the HTTP layer. Wire output remains RFC
9112-compliant.
For a parser that rejects everything outside host:port, use
parse_authority_form_strict.
The returned Uri has no scheme, no path, no query, and no
fragment — only the authority components (host,
port, userinfo).
Returns ParseError::InvalidComponent for inputs that contain
any of /, ?, or # — those bytes indicate a non-authority
shape and the caller should use parse instead.
Available on crate feature net only.
net only.Strict-mode variant of parse_authority_form:
enforces RFC 9112 §3.2.3 exactly.
Grammar: host ":" port. Userinfo and a missing port both
return ParseError::StrictViolation; everything else matches
parse_authority_form.
Available on crate feature net only.
net only.Build an HTTP authority-form URI ([userinfo@]host[:port], the
CONNECT request-target shape) directly from an already-parsed
Authority.
Unlike parse_authority_form this skips
re-parsing and re-validating a host:port string: the host/port are
moved in as values and only the canonical bytes are rendered (needed for
the lazy representation). Use it whenever you already hold an
Authority instead of round-tripping
through Authority::to_string() + parse_authority_form.
Available on crate feature net only.
net only.Project this URI to HTTP authority-form ([userinfo@]host[:port]),
the CONNECT request-target shape — keeping only the authority and
dropping the scheme, path, query and fragment.
Returns None when there is no authority component (e.g. an
origin-form /path or the asterisk-form *). This is the companion
to parse_authority_form for an
already-parsed URI, so callers need not round-trip through a manual
host:port string.
pub fn as_str(&self) -> Cow<'_, str>
Available on crate feature net only.
pub fn as_str(&self) -> Cow<'_, str>
net only.View this Uri as a str.
This method may allocate, and can also contain sensitive credentials. Do not use it for hot paths or logging purposes. Nor is it intended for encoding purposes.
It is mostly used for where you need a string representation,
but wish to borrow if possible and only allocate to a string if
you must, as a possibly cheaper alternative compared to to_string.
pub fn encode_to(&self, buf: &mut Vec<u8>)
Available on crate feature net only.
pub fn encode_to(&self, buf: &mut Vec<u8>)
net only.Append this URI’s canonical wire bytes to buf, without going
through std::fmt.
Parsed (lazy) and asterisk URIs copy their stored bytes in directly
(no re-render); the mutated (owned) form — rare on an encode path,
which normally carries a parsed request-target — falls back to
Display.
This writes the wire-faithful full form (matching Display),
so it does not strip userinfo/fragment. To project a richer URI to
a specific HTTP request-target form, use the dedicated
write_http_origin_form family.
pub fn is_asterisk(&self) -> bool
Available on crate feature net only.
pub fn is_asterisk(&self) -> bool
net only.Returns true if this is the OPTIONS-* request-target.
pub fn is_absolute(&self) -> bool
Available on crate feature net only.
pub fn is_absolute(&self) -> bool
net only.Returns true if this is an absolute URI — has a scheme. Inverse
case is a URI-reference without a scheme (relative reference,
origin-form path, or the asterisk).
pub fn scheme(&self) -> Option<&Protocol>
Available on crate feature net only.
pub fn scheme(&self) -> Option<&Protocol>
net only.Returns the scheme component, or None if the URI has none
(origin-form URIs and the asterisk-form).
pub fn path(&self) -> Option<PathRef<'_>>
Available on crate feature net only.
pub fn path(&self) -> Option<PathRef<'_>>
net only.Returns the path component, or None for the asterisk-form
(which has no path — the request-target is *).
For every other form (origin, absolute with or without authority)
a path is always present per RFC 3986 §3.3 — possibly empty
(e.g. http://example.com has an empty path-abempty).
pub fn query(&self) -> Option<QueryRef<'_>>
Available on crate feature net only.
pub fn query(&self) -> Option<QueryRef<'_>>
net only.Returns the query component, or None if the URI has no ?
delimiter on the wire.
Some(empty) vs None matters — ? followed by nothing is
distinct from no ? at all (load-bearing for SigV4 / cache
keys / proxy fidelity).
pub fn fragment(&self) -> Option<FragmentRef<'_>>
Available on crate feature net only.
pub fn fragment(&self) -> Option<FragmentRef<'_>>
net only.Returns the fragment component, or None if the URI has no #
delimiter on the wire. Same Some(empty) vs None distinction
as query.
Note: the wire writer for HTTP request-targets strips the fragment per RFC 9110 §7.1. This accessor returns it for inspection / logging / preservation purposes.
pub fn host(&self) -> Option<HostRef<'_>>
Available on crate feature net only.
pub fn host(&self) -> Option<HostRef<'_>>
net only.Returns the authority’s host, or None if the URI has no
authority (origin-form /foo, asterisk-form *, opaque-path
urn:isbn:0, etc.).
This is a shortcut for accessing just the host component;
Uri::authority gives the full bundle
(host + port + userinfo).
pub fn port(&self) -> OptPort
Available on crate feature net only.
pub fn port(&self) -> OptPort
net only.Returns the port as an OptPort —
Unset / Empty / Set(u16).
Most callers want port_u16 instead — it
returns Option<u16> and collapses the wire-only Empty
distinction. Use port() only when you need to preserve the
difference between host (no colon) and host: (colon with
no digits) on the wire.
Scheme default ports are NOT substituted — that’s a
canonicalization policy decision the caller makes (e.g.
Protocol::default_port() if the URI’s scheme is known).
pub fn port_u16(&self) -> Option<u16>
Available on crate feature net only.
pub fn port_u16(&self) -> Option<u16>
net only.Relaxed view of the port — Set(n) → Some(n), Unset /
Empty both → None. Use when the wire distinction between
“no colon” and “empty colon” doesn’t matter (e.g. dialing).
pub fn userinfo(&self) -> Option<UserInfoRef<'_>>
Available on crate feature net only.
pub fn userinfo(&self) -> Option<UserInfoRef<'_>>
net only.Returns the userinfo component, or None if the URI has no
authority OR the authority has no @.
Some("") (the @host form — empty userinfo before @) is
distinct from None (no @ at all). Wire fidelity preserved.
Available on crate feature net only.
net only.pub fn path_or_root(&self) -> &str
Available on crate feature net only.
pub fn path_or_root(&self) -> &str
net only.The raw path as a &str, defaulting to "/" when the path is
absent or empty (the effective origin-form path). Shortcut for
uri.path().map(|p| p.as_raw_str()).filter(|p| !p.is_empty()).unwrap_or("/").
pub fn query_or_empty(&self) -> &str
Available on crate feature net only.
pub fn query_or_empty(&self) -> &str
net only.The raw query as a &str, defaulting to "" when absent. Shortcut
for uri.query().map(|q| q.as_raw_str()).unwrap_or_default().
pub fn scheme_str(&self) -> Option<&str>
Available on crate feature net only.
pub fn scheme_str(&self) -> Option<&str>
net only.The scheme as a &str, or None. Shortcut for
uri.scheme().map(|p| p.as_str()).
pub fn host_str(&self) -> Option<Cow<'_, str>>
Available on crate feature net only.
pub fn host_str(&self) -> Option<Cow<'_, str>>
net only.The host rendered as a string, or None. Shortcut for
uri.host().map(|h| h.to_str()).
pub fn request_target(&self) -> Cow<'_, str>
Available on crate feature net only.
pub fn request_target(&self) -> Cow<'_, str>
net only.The HTTP origin-form request-target: path_or_root
followed by ? + query when a query is present. Borrows when there
is no query (zero-alloc), otherwise allocates the joined string.
pub fn has_path_prefix(&self, prefix: impl IntoUriComponent) -> bool
Available on crate feature net only.
pub fn has_path_prefix(&self, prefix: impl IntoUriComponent) -> bool
net only.true when the path begins with prefix — matched at / segment
boundaries with percent-decoded comparison (default PathMatchOptions).
See has_path_prefix_with_opts for
partial / raw / case-insensitive matching, and PathMut::strip_prefix
to remove it.
pub fn has_path_prefix_with_opts(
&self,
prefix: impl IntoUriComponent,
opts: PathMatchOptions,
) -> bool
Available on crate feature net only.
pub fn has_path_prefix_with_opts( &self, prefix: impl IntoUriComponent, opts: PathMatchOptions, ) -> bool
net only.has_path_prefix with explicit PathMatchOptions.
pub fn has_path_suffix(&self, suffix: impl IntoUriComponent) -> bool
Available on crate feature net only.
pub fn has_path_suffix(&self, suffix: impl IntoUriComponent) -> bool
net only.true when the path ends with suffix — matched at / segment
boundaries with percent-decoded comparison (default PathMatchOptions).
pub fn has_path_suffix_with_opts(
&self,
suffix: impl IntoUriComponent,
opts: PathMatchOptions,
) -> bool
Available on crate feature net only.
pub fn has_path_suffix_with_opts( &self, suffix: impl IntoUriComponent, opts: PathMatchOptions, ) -> bool
net only.has_path_suffix with explicit PathMatchOptions.
pub fn path_segment(&self, n: usize) -> Option<PathSegment<'_>>
Available on crate feature net only.
pub fn path_segment(&self, n: usize) -> Option<PathSegment<'_>>
net only.The n-th path segment (0-indexed, /-delimited, leading /
ignored), or None. Shortcut for uri.path()?.segments().nth(n).
pub fn first_path_segment(&self) -> Option<PathSegment<'_>>
Available on crate feature net only.
pub fn first_path_segment(&self) -> Option<PathSegment<'_>>
net only.The first segment Shortcut for uri.path_segment(0).
pub fn query_params<'de, T>(&'de self) -> Result<T, QueryDeserializeError>where
T: Deserialize<'de>,
Available on crate feature net only.
pub fn query_params<'de, T>(&'de self) -> Result<T, QueryDeserializeError>where
T: Deserialize<'de>,
net only.Deserialize the query string into T via serde (an absent query
deserializes as empty). Shortcut over Uri::query +
QueryRef::deserialize.
pub fn ensure_path_trailing_slash(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn ensure_path_trailing_slash(&mut self) -> &mut Uri
net only.Ensure the path ends with exactly one trailing / (appended when
missing; an empty path becomes /). Scheme, authority and query
are preserved.
pub fn with_path(self, path: impl IntoUriComponent) -> Uri
Available on crate feature net only.
pub fn with_path(self, path: impl IntoUriComponent) -> Uri
net only.Replace the path. Bytes outside RFC 3986 pchar ∪ {'/'} are
percent-encoded — pass raw (decoded) values, the library
serializes them correctly. Already-legal owned inputs move
without allocating.
pub fn set_path(&mut self, path: impl IntoUriComponent) -> &mut Uri
Available on crate feature net only.
pub fn set_path(&mut self, path: impl IntoUriComponent) -> &mut Uri
net only.Replace the path. Bytes outside RFC 3986 pchar ∪ {'/'} are
percent-encoded — pass raw (decoded) values, the library
serializes them correctly. Already-legal owned inputs move
without allocating.
pub fn unset_path(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn unset_path(&mut self) -> &mut Uri
net only.Clear the path (empty bytes — no leading /). Path is never
absent in the URI grammar, so this is the canonical “no path”
state, not a removal.
pub fn without_path(self) -> Uri
Available on crate feature net only.
pub fn without_path(self) -> Uri
net only.Consuming form of unset_path.
pub fn path_mut(&mut self) -> PathMut<'_>
Available on crate feature net only.
pub fn path_mut(&mut self) -> PathMut<'_>
net only.Returns a PathMut guard for incremental path mutation —
push_segment, pop_segment, clear.
pub fn with_additional_path_segment(self, segment: impl IntoUriComponent) -> Uri
Available on crate feature net only.
pub fn with_additional_path_segment(self, segment: impl IntoUriComponent) -> Uri
net only.Append an additional /-delimited path segment, inserting a
/ separator first if the current path doesn’t already end
with one. Shortcut for path_mut().push_segment(..) —
see that method for the full encoding policy (bytes outside
the RFC 3986 path-segment set are percent-encoded; pass
decoded values, not pre-encoded ones).
Empty path + "x" → /x; /foo + "bar" → /foo/bar;
/foo/ + "bar" → /foo/bar (no double slash).
pub fn set_additional_path_segment(
&mut self,
segment: impl IntoUriComponent,
) -> &mut Uri
Available on crate feature net only.
pub fn set_additional_path_segment( &mut self, segment: impl IntoUriComponent, ) -> &mut Uri
net only.Append an additional /-delimited path segment, inserting a
/ separator first if the current path doesn’t already end
with one. Shortcut for path_mut().push_segment(..) —
see that method for the full encoding policy (bytes outside
the RFC 3986 path-segment set are percent-encoded; pass
decoded values, not pre-encoded ones).
Empty path + "x" → /x; /foo + "bar" → /foo/bar;
/foo/ + "bar" → /foo/bar (no double slash).
pub fn with_path_without_last_segment(self) -> Uri
Available on crate feature net only.
pub fn with_path_without_last_segment(self) -> Uri
net only.Remove the final /-delimited path segment. Shortcut for
path_mut().pop_segment() when you
want the shortened Uri back and don’t need the removed
bytes (use the guard directly if you do).
This pops one wire segment — not a Path::parent-style
“go up a directory”. A trailing / is its own empty segment,
so /foo/bar/ → /foo/bar (the trailing slash is dropped),
/foo/bar → /foo, and /foo → empty. An empty or opaque
(no /) path collapses to empty.
pub fn set_path_without_last_segment(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn set_path_without_last_segment(&mut self) -> &mut Uri
net only.Remove the final /-delimited path segment. Shortcut for
path_mut().pop_segment() when you
want the shortened Uri back and don’t need the removed
bytes (use the guard directly if you do).
This pops one wire segment — not a Path::parent-style
“go up a directory”. A trailing / is its own empty segment,
so /foo/bar/ → /foo/bar (the trailing slash is dropped),
/foo/bar → /foo, and /foo → empty. An empty or opaque
(no /) path collapses to empty.
pub fn maybe_with_query(self, query: Option<Query>) -> Uri
Available on crate feature net only.
pub fn maybe_with_query(self, query: Option<Query>) -> Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn maybe_set_query(&mut self, query: Option<Query>) -> &mut Uri
Available on crate feature net only.
pub fn maybe_set_query(&mut self, query: Option<Query>) -> &mut Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn with_query(self, query: Query) -> Uri
Available on crate feature net only.
pub fn with_query(self, query: Query) -> Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn set_query(&mut self, query: Query) -> &mut Uri
Available on crate feature net only.
pub fn set_query(&mut self, query: Query) -> &mut Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn without_query(self) -> Uri
Available on crate feature net only.
pub fn without_query(self) -> Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn unset_query(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn unset_query(&mut self) -> &mut Uri
net only.Set, clear, or assign the query. Bytes taken as-is — no
re-encoding. Pair with set_query_from_bytes
when you have raw bytes that need pct-encoding.
pub fn set_query_from_bytes(&mut self, query: impl IntoUriComponent) -> &mut Uri
Available on crate feature net only.
pub fn set_query_from_bytes(&mut self, query: impl IntoUriComponent) -> &mut Uri
net only.Encode raw bytes into a Query and assign. Bytes outside
pchar ∪ {'/', '?'} are percent-encoded (including #).
pub fn with_query_from_bytes(self, query: impl IntoUriComponent) -> Uri
Available on crate feature net only.
pub fn with_query_from_bytes(self, query: impl IntoUriComponent) -> Uri
net only.Consuming form of set_query_from_bytes.
pub fn query_mut(&mut self) -> QueryMut<'_>
Available on crate feature net only.
pub fn query_mut(&mut self) -> QueryMut<'_>
net only.Returns a QueryMut guard for incremental query mutation —
push_pair, push_key, pop, drain.
pub fn set_scheme(&mut self, scheme: impl Into<Protocol>) -> &mut Uri
Available on crate feature net only.
pub fn set_scheme(&mut self, scheme: impl Into<Protocol>) -> &mut Uri
net only.Set the scheme. Accepts any Into<Protocol> — most usefully
Protocol itself, but also &str / String
(via the existing Protocol::From<&str> chain that’s used
throughout rama’s HTTP / SOCKS5 / TLS plumbing).
The scheme is a presentation-only component for the parsed URI
— canonicalize lowercases custom schemes per RFC 3986
§6.2.2.1, known schemes (http, https, ws, wss,
socks5, socks5h) are already case-normalised at construction.
pub fn with_scheme(self, scheme: impl Into<Protocol>) -> Uri
Available on crate feature net only.
pub fn with_scheme(self, scheme: impl Into<Protocol>) -> Uri
net only.Consuming form of set_scheme.
pub fn unset_scheme(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn unset_scheme(&mut self) -> &mut Uri
net only.Clear the scheme — turns an absolute-form URI into a
relative-reference. Shortcut for the None arm of
maybe_set_scheme.
pub fn without_scheme(self) -> Uri
Available on crate feature net only.
pub fn without_scheme(self) -> Uri
net only.Consuming form of unset_scheme.
pub fn maybe_set_scheme(
&mut self,
scheme: impl Into<Option<Protocol>>,
) -> &mut Uri
Available on crate feature net only.
pub fn maybe_set_scheme( &mut self, scheme: impl Into<Option<Protocol>>, ) -> &mut Uri
net only.Set or clear the scheme in one call. Some(scheme) is equivalent
to set_scheme; None is equivalent to
unset_scheme.
pub fn maybe_with_scheme(self, scheme: impl Into<Option<Protocol>>) -> Uri
Available on crate feature net only.
pub fn maybe_with_scheme(self, scheme: impl Into<Option<Protocol>>) -> Uri
net only.Consuming form of maybe_set_scheme.
pub fn canonicalize(self) -> Uri
Available on crate feature net only.
pub fn canonicalize(self) -> Uri
net only.Apply RFC 3986 §6.2.2 syntax-based normalization. Returns a new
Uri with:
- Host promoted from
Host::Uninterpretedto typedDomain/IpAddrwhen the bytes decode to one (%6D→m; pct-encoded UTF-8 → IDN→ACE under theidnafeature). Sub-delim reg-name and IPvFuture stayUninterpreted— no canonical typed form exists. - Pct-encoded octets that map to unreserved characters
(
%41→A,%7E→~) decoded in path / query / fragment. Reserved / sub-delim octets stay encoded; their hex digits are uppercased per §6.2.2.1. - Default port dropped (
http://example.com:80/→http://example.com/). - Empty path replaced with
/when an authority is present. - Dot-segments (
.,..) removed from the path per §6.2.2.3.
Wire-fidelity is lost. Use this when you specifically want a canonical form — typically client-side, building HTTP requests from user input. Server / proxy / forwarding code that needs to preserve received bytes should leave the URI unmodified.
pub fn parse_canonical<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse_canonical<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Parse input and immediately apply canonicalize.
One-shot convenience for client-side URI construction from user
input.
pub fn parse_canonical_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
Available on crate feature net only.
pub fn parse_canonical_strict<T>(input: T) -> Result<Uri, ParseError>where
T: IntoUriInput,
net only.Strict variant of parse_canonical —
rejects RFC 3986 grammar violations before canonicalizing.
pub fn resolve(&self, reference: &Uri) -> Result<Uri, ResolveError>
Available on crate feature net only.
pub fn resolve(&self, reference: &Uri) -> Result<Uri, ResolveError>
net only.Resolve reference against self (the base URI).
Graceful — matches browser / curl behaviour:
- If the reference shares the base’s scheme, the scheme is treated as inherited (RFC 3986 §5.2.2 non-strict loophole).
- Excess
..segments past the path root are silently clamped.
Use resolve_strict to reject both.
Errors when the base has no scheme, the base or reference is the asterisk-form, or the resolved URI exceeds the internal cap.
pub fn resolve_strict(&self, reference: &Uri) -> Result<Uri, ResolveError>
Available on crate feature net only.
pub fn resolve_strict(&self, reference: &Uri) -> Result<Uri, ResolveError>
net only.Resolve reference against self in strict mode (RFC 3986 §5.2.2):
- No scheme-matching loophole — a reference with a scheme stays absolute even if its scheme matches the base’s.
- A
..segment that would traverse past the path root is an error (ResolveError::DotSegmentTraversalPastRoot).
pub fn with_fragment(self, fragment: impl IntoUriComponent) -> Uri
Available on crate feature net only.
pub fn with_fragment(self, fragment: impl IntoUriComponent) -> Uri
net only.Set the fragment. Leading # is implicit. Bytes outside
pchar ∪ {'/', '?'} are percent-encoded.
pub fn set_fragment(&mut self, fragment: impl IntoUriComponent) -> &mut Uri
Available on crate feature net only.
pub fn set_fragment(&mut self, fragment: impl IntoUriComponent) -> &mut Uri
net only.Set the fragment. Leading # is implicit. Bytes outside
pchar ∪ {'/', '?'} are percent-encoded.
pub fn unset_fragment(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn unset_fragment(&mut self) -> &mut Uri
net only.Remove the fragment entirely (no # on the wire — distinct from
an empty-fragment # per §3.5).
pub fn without_fragment(self) -> Uri
Available on crate feature net only.
pub fn without_fragment(self) -> Uri
net only.Consuming form of unset_fragment.
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
Available on crate feature net only.
net only.Set or remove the authority (userinfo + host + port).
pub fn set_host(&mut self, host: impl Into<Host>) -> &mut Uri
Available on crate feature net only.
pub fn set_host(&mut self, host: impl Into<Host>) -> &mut Uri
net only.Set just the host, preserving any existing userinfo and port.
Accepts any Into<Host> — Host,
Domain, IpAddr,
Ipv4Addr, or
Ipv6Addr. For inputs that need
parsing (&str / String), use
try_set_host instead.
If the URI has no authority yet, one is created with the given host and no userinfo / port. Existing authority parts are preserved otherwise.
pub fn with_host(self, host: impl Into<Host>) -> Uri
Available on crate feature net only.
pub fn with_host(self, host: impl Into<Host>) -> Uri
net only.Consuming form of set_host.
pub fn try_set_host<H>(&mut self, host: H) -> Result<&mut Uri, UriError>
Available on crate feature net only.
pub fn try_set_host<H>(&mut self, host: H) -> Result<&mut Uri, UriError>
net only.Fallible host setter. Accepts any TryInto<Host> — typically
&str / String / &[u8] / Vec<u8>.
Routes through Host::try_from which
does IP-first, then Domain::try_from
(IDN-normalising non-ASCII to ACE under the idna feature). So
try_set_host("münchen.de") ends up with a canonical
Host::Name(Domain("xn--mnchen-3ya.de")) — exactly what
client-side code building URIs from user input expects.
Returns UriError::ComponentConversion tagged with
Component::Host when the upstream conversion fails — the
inner boxed cause carries the original error.
pub fn try_with_host<H>(self, host: H) -> Result<Uri, UriError>
Available on crate feature net only.
pub fn try_with_host<H>(self, host: H) -> Result<Uri, UriError>
net only.Consuming form of try_set_host.
pub fn set_port(&mut self, port: impl Into<OptPort>) -> &mut Uri
Available on crate feature net only.
pub fn set_port(&mut self, port: impl Into<OptPort>) -> &mut Uri
net only.Set just the port, preserving the rest of the authority.
Some(port) sets the explicit port; None clears any
existing :port suffix (scheme default ports are not
substituted — they remain implicit). If the URI has no
authority yet, one is created with the loopback IPv4 host
as a placeholder — callers building a URI from scratch should
set the host before the port for clarity.
pub fn with_port(self, port: impl Into<OptPort>) -> Uri
Available on crate feature net only.
pub fn with_port(self, port: impl Into<OptPort>) -> Uri
net only.Consuming form of set_port.
pub fn set_user_info(
&mut self,
user_info: impl Into<Option<UserInfo>>,
) -> &mut Uri
Available on crate feature net only.
pub fn set_user_info( &mut self, user_info: impl Into<Option<UserInfo>>, ) -> &mut Uri
net only.Set just the user-info, preserving the rest of the authority.
Some(user_info) sets the user[:pass]@ prefix; None clears
any existing user-info. If the URI has no authority yet, one is
created with the loopback IPv4 host as a placeholder — see
set_port for the same caveat.
pub fn with_user_info(self, user_info: impl Into<Option<UserInfo>>) -> Uri
Available on crate feature net only.
pub fn with_user_info(self, user_info: impl Into<Option<UserInfo>>) -> Uri
net only.Consuming form of set_user_info.
pub fn unset_user_info(&mut self) -> &mut Uri
Available on crate feature net only.
pub fn unset_user_info(&mut self) -> &mut Uri
net only.Clear the user-info. Shortcut for set_user_info(None).
pub fn without_user_info(self) -> Uri
Available on crate feature net only.
pub fn without_user_info(self) -> Uri
net only.Consuming form of unset_user_info.
pub fn try_set_user_info<U>(
&mut self,
user_info: U,
) -> Result<&mut Uri, UriError>
Available on crate feature net only.
pub fn try_set_user_info<U>( &mut self, user_info: U, ) -> Result<&mut Uri, UriError>
net only.Fallible user-info setter. Accepts any TryInto<UserInfo> —
typically &str / String. Routes through
UserInfo::try_from which enforces
the RFC 3986 §3.2.1 userinfo grammar.
§impl Uri
impl Uri
pub fn view(&self) -> UriRef<'_>
Available on crate feature net only.
pub fn view(&self) -> UriRef<'_>
net only.Borrow this URI as a UriRef — a single match-once snapshot
of every component accessor.
Most useful for code that inspects three-or-more components in
a row: each Uri::scheme() / host() / path() etc. re-walks
the internal match &self.inner { … } per call; view() does
the walk once and exposes the results as struct fields.
Trait Implementations§
§impl<'de> Deserialize<'de> for Uri
impl<'de> Deserialize<'de> for Uri
§fn deserialize<D>(
deserializer: D,
) -> Result<Uri, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Uri, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
§impl Display for Uri
impl Display for Uri
§fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Writes the canonical URI string: [scheme:][//authority][path][?query][#fragment].
Lazy URIs round-trip byte-for-byte through their source buffer; Owned
URIs reassemble from components.
Not the HTTP wire form. This includes userinfo and fragment and
preserves the original port — none of which belong on an HTTP request
line or in HTTP/2 pseudo-headers. Use the dedicated write_*_form
helpers (landing with the relative-resolution work) when serializing
for HTTP. Logging a Uri via Display may leak
userinfo — use Debug (password-redacted) if the
destination is a tracing sink, or strip the userinfo explicitly.
impl Eq for Uri
§impl FromRequest for Uri
impl FromRequest for Uri
§type Rejection = Infallible
type Rejection = Infallible
§async fn from_request(
req: Request,
) -> Result<Uri, <Uri as FromRequest>::Rejection>
async fn from_request( req: Request, ) -> Result<Uri, <Uri as FromRequest>::Rejection>
impl IntoUrl for Uri
§impl Ord for Uri
impl Ord for Uri
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
§impl PartialOrd for Uri
impl PartialOrd for Uri
§impl Serialize for Uri
impl Serialize for Uri
§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
Auto Trait Implementations§
impl Freeze for Uri
impl RefUnwindSafe for Uri
impl Send for Uri
impl Sync for Uri
impl Unpin for Uri
impl UnsafeUnpin for Uri
impl UnwindSafe for Uri
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a rama_grpc::Request§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§fn and<P, B, E>(self, other: P) -> And<T, P>
fn and<P, B, E>(self, other: P) -> And<T, P>
Policy that returns Action::Follow only if self and other return
Action::Follow. Read more§impl<T, U> RamaTryFrom<T> for Uwhere
U: TryFrom<T>,
impl<T, U> RamaTryFrom<T> for Uwhere
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
fn rama_try_from(value: T) -> Result<U, <U as RamaTryFrom<T>>::Error>
§impl<T, U, CrateMarker> RamaTryInto<U, CrateMarker> for Twhere
U: RamaTryFrom<T, CrateMarker>,
impl<T, U, CrateMarker> RamaTryInto<U, CrateMarker> for Twhere
U: RamaTryFrom<T, CrateMarker>,
type Error = <U as RamaTryFrom<T, CrateMarker>>::Error
fn rama_try_into(self) -> Result<U, <U as RamaTryFrom<T, CrateMarker>>::Error>
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<T> ToStringFallible for Twhere
T: Display,
impl<T> ToStringFallible for Twhere
T: Display,
§fn try_to_string(&self) -> Result<String, TryReserveError>
fn try_to_string(&self) -> Result<String, TryReserveError>
ToString::to_string, but without panic on OOM.
§impl<V, F> ValueFormatter<&V> for F
impl<V, F> ValueFormatter<&V> for F
§fn format_value(writer: impl ValueWriter, value: &&V)
fn format_value(writer: impl ValueWriter, value: &&V)
value to writer§impl<V, F> ValueFormatter<Arc<V>> for F
impl<V, F> ValueFormatter<Arc<V>> for F
§fn format_value(writer: impl ValueWriter, value: &Arc<V>)
fn format_value(writer: impl ValueWriter, value: &Arc<V>)
value to writer§impl<V, F> ValueFormatter<Box<V>> for F
impl<V, F> ValueFormatter<Box<V>> for F
§fn format_value(writer: impl ValueWriter, value: &Box<V>)
fn format_value(writer: impl ValueWriter, value: &Box<V>)
value to writer§impl<V, F> ValueFormatter<Cow<'_, V>> for F
impl<V, F> ValueFormatter<Cow<'_, V>> for F
§fn format_value(writer: impl ValueWriter, value: &Cow<'_, V>)
fn format_value(writer: impl ValueWriter, value: &Cow<'_, V>)
value to writer§impl<V, F> ValueFormatter<Option<V>> for Fwhere
F: ValueFormatter<V> + ?Sized,
impl<V, F> ValueFormatter<Option<V>> for Fwhere
F: ValueFormatter<V> + ?Sized,
§fn format_value(writer: impl ValueWriter, value: &Option<V>)
fn format_value(writer: impl ValueWriter, value: &Option<V>)
value to writer