url/lib.rs
1// Copyright 2013-2015 The rust-url developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9/*!
10
11rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
12for the [Rust](http://rust-lang.org/) programming language.
13
14
15# URL parsing and data structures
16
17First, URL parsing may fail for various reasons and therefore returns a `Result`.
18
19```
20use url::{Url, ParseError};
21
22assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
23```
24
25Let’s parse a valid URL and look at its components.
26
27```
28use url::{Url, Host, Position};
29# use url::ParseError;
30# fn run() -> Result<(), ParseError> {
31let issue_list_url = Url::parse(
32 "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
33)?;
34
35assert!(issue_list_url.scheme() == "https");
36assert!(issue_list_url.username() == "");
37assert!(issue_list_url.password() == None);
38assert!(issue_list_url.host_str() == Some("github.com"));
39assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
40assert!(issue_list_url.port() == None);
41assert!(issue_list_url.path() == "/rust-lang/rust/issues");
42assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
43 Some(vec!["rust-lang", "rust", "issues"]));
44assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
45assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
46assert!(issue_list_url.fragment() == None);
47assert!(!issue_list_url.cannot_be_a_base());
48# Ok(())
49# }
50# run().unwrap();
51```
52
53Some URLs are said to be *cannot-be-a-base*:
54they don’t have a username, password, host, or port,
55and their "path" is an arbitrary string rather than slash-separated segments:
56
57```
58use url::Url;
59# use url::ParseError;
60
61# fn run() -> Result<(), ParseError> {
62let data_url = Url::parse("data:text/plain,Hello?World#")?;
63
64assert!(data_url.cannot_be_a_base());
65assert!(data_url.scheme() == "data");
66assert!(data_url.path() == "text/plain,Hello");
67assert!(data_url.path_segments().is_none());
68assert!(data_url.query() == Some("World"));
69assert!(data_url.fragment() == Some(""));
70# Ok(())
71# }
72# run().unwrap();
73```
74
75## Default Features
76
77Versions `<= 2.5.2` of the crate have no default features. Versions `> 2.5.2` have the default feature 'std'.
78If you are upgrading across this boundary and you have specified `default-features = false`, then
79you will need to add the 'std' feature or the 'alloc' feature to your dependency.
80The 'std' feature has the same behavior as the previous versions. The 'alloc' feature
81provides no_std support.
82
83## Serde
84
85Enable the `serde` feature to include `Deserialize` and `Serialize` implementations for `url::Url`.
86
87# Base URL
88
89Many contexts allow URL *references* that can be relative to a *base URL*:
90
91```html
92<link rel="stylesheet" href="../main.css">
93```
94
95Since parsed URLs are absolute, giving a base is required for parsing relative URLs:
96
97```
98use url::{Url, ParseError};
99
100assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
101```
102
103Use the `join` method on an `Url` to use it as a base URL:
104
105```
106use url::Url;
107# use url::ParseError;
108
109# fn run() -> Result<(), ParseError> {
110let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
111let css_url = this_document.join("../main.css")?;
112assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
113# Ok(())
114# }
115# run().unwrap();
116```
117
118# Feature: `serde`
119
120If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
121[`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
122[`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
123See [serde documentation](https://serde.rs) for more information.
124
125```toml
126url = { version = "2", features = ["serde"] }
127```
128
129# Feature: `debugger_visualizer`
130
131If you enable the `debugger_visualizer` feature, the `url` crate will include
132a [natvis file](https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects)
133for [Visual Studio](https://www.visualstudio.com/) that allows you to view
134[`Url`](struct.Url.html) objects in the debugger.
135
136This feature requires Rust 1.71 or later.
137
138```toml
139url = { version = "2", features = ["debugger_visualizer"] }
140```
141
142*/
143
144#![no_std]
145#![doc(html_root_url = "https://docs.rs/url/2.5.9")]
146#![cfg_attr(
147 feature = "debugger_visualizer",
148 debugger_visualizer(natvis_file = "../../debug_metadata/url.natvis")
149)]
150
151pub use form_urlencoded;
152
153// For forwards compatibility
154#[cfg(feature = "std")]
155extern crate std;
156
157#[macro_use]
158extern crate alloc;
159
160#[cfg(feature = "serde")]
161extern crate serde;
162
163use crate::host::HostInternal;
164
165use crate::net::IpAddr;
166#[cfg(feature = "std")]
167#[cfg(any(
168 unix,
169 windows,
170 target_os = "redox",
171 target_os = "wasi",
172 target_os = "hermit"
173))]
174use crate::net::{SocketAddr, ToSocketAddrs};
175use crate::parser::{to_u32, Context, Parser, SchemeType, USERINFO};
176use alloc::borrow::Cow;
177use alloc::borrow::ToOwned;
178use alloc::str;
179use alloc::string::{String, ToString};
180use core::borrow::Borrow;
181use core::convert::TryFrom;
182use core::fmt::Write;
183use core::ops::{Range, RangeFrom, RangeTo};
184use core::{cmp, fmt, hash, mem};
185use percent_encoding::utf8_percent_encode;
186#[cfg(feature = "std")]
187#[cfg(any(
188 unix,
189 windows,
190 target_os = "redox",
191 target_os = "wasi",
192 target_os = "hermit"
193))]
194use std::io;
195#[cfg(feature = "std")]
196use std::path::{Path, PathBuf};
197
198/// `std` version of `net`
199#[cfg(feature = "std")]
200pub(crate) mod net {
201 pub use std::net::*;
202}
203/// `no_std` nightly version of `net`
204#[cfg(not(feature = "std"))]
205pub(crate) mod net {
206 pub use core::net::*;
207}
208
209pub use crate::host::Host;
210pub use crate::origin::{OpaqueOrigin, Origin};
211pub use crate::parser::{ParseError, SyntaxViolation};
212pub use crate::path_segments::PathSegmentsMut;
213pub use crate::slicing::Position;
214pub use form_urlencoded::EncodingOverride;
215
216mod host;
217mod origin;
218mod parser;
219mod path_segments;
220mod slicing;
221
222#[doc(hidden)]
223pub mod quirks;
224
225/// A parsed URL record.
226#[derive(Clone)]
227pub struct Url {
228 /// Syntax in pseudo-BNF:
229 ///
230 /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
231 /// non-hierarchical = non-hierarchical-path
232 /// non-hierarchical-path = /* Does not start with "/" */
233 /// hierarchical = authority? hierarchical-path
234 /// authority = "//" userinfo? host [ ":" port ]?
235 /// userinfo = username [ ":" password ]? "@"
236 /// hierarchical-path = [ "/" path-segment ]+
237 serialization: String,
238
239 // Components
240 scheme_end: u32, // Before ':'
241 username_end: u32, // Before ':' (if a password is given) or '@' (if not)
242 host_start: u32,
243 host_end: u32,
244 host: HostInternal,
245 port: Option<u16>,
246 path_start: u32, // Before initial '/', if any
247 query_start: Option<u32>, // Before '?', unlike Position::QueryStart
248 fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
249}
250
251/// Full configuration for the URL parser.
252#[derive(Copy, Clone)]
253#[must_use]
254pub struct ParseOptions<'a> {
255 base_url: Option<&'a Url>,
256 encoding_override: EncodingOverride<'a>,
257 violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
258}
259
260impl<'a> ParseOptions<'a> {
261 /// Change the base URL
262 ///
263 /// See the notes of [`Url::join`] for more details about how this base is considered
264 /// when parsing.
265 pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
266 self.base_url = new;
267 self
268 }
269
270 /// Override the character encoding of query strings.
271 /// This is a legacy concept only relevant for HTML.
272 pub fn encoding_override(mut self, new: EncodingOverride<'a>) -> Self {
273 self.encoding_override = new;
274 self
275 }
276
277 /// Call the provided function or closure for a non-fatal `SyntaxViolation`
278 /// when it occurs during parsing. Note that since the provided function is
279 /// `Fn`, the caller might need to utilize _interior mutability_, such as with
280 /// a `RefCell`, to collect the violations.
281 ///
282 /// ## Example
283 /// ```
284 /// use std::cell::RefCell;
285 /// use url::{Url, SyntaxViolation};
286 /// # use url::ParseError;
287 /// # fn run() -> Result<(), url::ParseError> {
288 /// let violations = RefCell::new(Vec::new());
289 /// let url = Url::options()
290 /// .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
291 /// .parse("https:////example.com")?;
292 /// assert_eq!(url.as_str(), "https://example.com/");
293 /// assert_eq!(violations.into_inner(),
294 /// vec!(SyntaxViolation::ExpectedDoubleSlash));
295 /// # Ok(())
296 /// # }
297 /// # run().unwrap();
298 /// ```
299 pub fn syntax_violation_callback(mut self, new: Option<&'a dyn Fn(SyntaxViolation)>) -> Self {
300 self.violation_fn = new;
301 self
302 }
303
304 /// Parse an URL string with the configuration so far.
305 pub fn parse(self, input: &str) -> Result<Url, crate::ParseError> {
306 Parser {
307 serialization: String::with_capacity(input.len()),
308 base_url: self.base_url,
309 query_encoding_override: self.encoding_override,
310 violation_fn: self.violation_fn,
311 context: Context::UrlParser,
312 }
313 .parse_url(input)
314 }
315}
316
317impl Url {
318 /// Parse an absolute URL from a string.
319 ///
320 /// # Examples
321 ///
322 /// ```rust
323 /// use url::Url;
324 /// # use url::ParseError;
325 ///
326 /// # fn run() -> Result<(), ParseError> {
327 /// let url = Url::parse("https://example.net")?;
328 /// # Ok(())
329 /// # }
330 /// # run().unwrap();
331 /// ```
332 ///
333 /// # Errors
334 ///
335 /// If the function can not parse an absolute URL from the given string,
336 /// a [`ParseError`] variant will be returned.
337 ///
338 /// [`ParseError`]: enum.ParseError.html
339 #[inline]
340 pub fn parse(input: &str) -> Result<Self, crate::ParseError> {
341 Self::options().parse(input)
342 }
343
344 /// Parse an absolute URL from a string and add params to its query string.
345 ///
346 /// Existing params are not removed.
347 ///
348 /// # Examples
349 ///
350 /// ```rust
351 /// use url::Url;
352 /// # use url::ParseError;
353 ///
354 /// # fn run() -> Result<(), ParseError> {
355 /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
356 /// &[("lang", "rust"), ("browser", "servo")])?;
357 /// assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str());
358 /// # Ok(())
359 /// # }
360 /// # run().unwrap();
361 /// ```
362 ///
363 /// # Errors
364 ///
365 /// If the function can not parse an absolute URL from the given string,
366 /// a [`ParseError`] variant will be returned.
367 ///
368 /// [`ParseError`]: enum.ParseError.html
369 #[inline]
370 pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Self, crate::ParseError>
371 where
372 I: IntoIterator,
373 I::Item: Borrow<(K, V)>,
374 K: AsRef<str>,
375 V: AsRef<str>,
376 {
377 let mut url = Self::options().parse(input);
378
379 if let Ok(ref mut url) = url {
380 url.query_pairs_mut().extend_pairs(iter);
381 }
382
383 url
384 }
385
386 /// https://url.spec.whatwg.org/#potentially-strip-trailing-spaces-from-an-opaque-path
387 fn strip_trailing_spaces_from_opaque_path(&mut self) {
388 if !self.cannot_be_a_base() {
389 return;
390 }
391
392 if self.fragment_start.is_some() {
393 return;
394 }
395
396 if self.query_start.is_some() {
397 return;
398 }
399
400 let trailing_space_count = self
401 .serialization
402 .chars()
403 .rev()
404 .take_while(|c| *c == ' ')
405 .count();
406
407 let start = self.serialization.len() - trailing_space_count;
408
409 self.serialization.truncate(start);
410 }
411
412 /// Parse a string as an URL, with this URL as the base URL.
413 ///
414 /// The inverse of this is [`make_relative`].
415 ///
416 /// # Notes
417 ///
418 /// - A trailing slash is significant.
419 /// Without it, the last path component is considered to be a “file” name
420 /// to be removed to get at the “directory” that is used as the base.
421 /// - A [scheme relative special URL](https://url.spec.whatwg.org/#scheme-relative-special-url-string)
422 /// as input replaces everything in the base URL after the scheme.
423 /// - An absolute URL (with a scheme) as input replaces the whole base URL (even the scheme).
424 ///
425 /// # Examples
426 ///
427 /// ```rust
428 /// use url::Url;
429 /// # use url::ParseError;
430 ///
431 /// // Base without a trailing slash
432 /// # fn run() -> Result<(), ParseError> {
433 /// let base = Url::parse("https://example.net/a/b.html")?;
434 /// let url = base.join("c.png")?;
435 /// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
436 ///
437 /// // Base with a trailing slash
438 /// let base = Url::parse("https://example.net/a/b/")?;
439 /// let url = base.join("c.png")?;
440 /// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
441 ///
442 /// // Input as scheme relative special URL
443 /// let base = Url::parse("https://alice.com/a")?;
444 /// let url = base.join("//eve.com/b")?;
445 /// assert_eq!(url.as_str(), "https://eve.com/b");
446 ///
447 /// // Input as base url relative special URL
448 /// let base = Url::parse("https://alice.com/a")?;
449 /// let url = base.join("/v1/meta")?;
450 /// assert_eq!(url.as_str(), "https://alice.com/v1/meta");
451 ///
452 /// // Input as absolute URL
453 /// let base = Url::parse("https://alice.com/a")?;
454 /// let url = base.join("http://eve.com/b")?;
455 /// assert_eq!(url.as_str(), "http://eve.com/b"); // http instead of https
456 ///
457 /// # Ok(())
458 /// # }
459 /// # run().unwrap();
460 /// ```
461 ///
462 /// # Errors
463 ///
464 /// If the function can not parse an URL from the given string
465 /// with this URL as the base URL, a [`ParseError`] variant will be returned.
466 ///
467 /// [`ParseError`]: enum.ParseError.html
468 /// [`make_relative`]: #method.make_relative
469 #[inline]
470 pub fn join(&self, input: &str) -> Result<Self, crate::ParseError> {
471 Self::options().base_url(Some(self)).parse(input)
472 }
473
474 /// Creates a relative URL if possible, with this URL as the base URL.
475 ///
476 /// This is the inverse of [`join`].
477 ///
478 /// # Examples
479 ///
480 /// ```rust
481 /// use url::Url;
482 /// # use url::ParseError;
483 ///
484 /// # fn run() -> Result<(), ParseError> {
485 /// let base = Url::parse("https://example.net/a/b.html")?;
486 /// let url = Url::parse("https://example.net/a/c.png")?;
487 /// let relative = base.make_relative(&url);
488 /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
489 ///
490 /// let base = Url::parse("https://example.net/a/b/")?;
491 /// let url = Url::parse("https://example.net/a/b/c.png")?;
492 /// let relative = base.make_relative(&url);
493 /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
494 ///
495 /// let base = Url::parse("https://example.net/a/b/")?;
496 /// let url = Url::parse("https://example.net/a/d/c.png")?;
497 /// let relative = base.make_relative(&url);
498 /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("../d/c.png"));
499 ///
500 /// let base = Url::parse("https://example.net/a/b.html?c=d")?;
501 /// let url = Url::parse("https://example.net/a/b.html?e=f")?;
502 /// let relative = base.make_relative(&url);
503 /// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("?e=f"));
504 /// # Ok(())
505 /// # }
506 /// # run().unwrap();
507 /// ```
508 ///
509 /// # Errors
510 ///
511 /// If this URL can't be a base for the given URL, `None` is returned.
512 /// This is for example the case if the scheme, host or port are not the same.
513 ///
514 /// [`join`]: #method.join
515 pub fn make_relative(&self, url: &Self) -> Option<String> {
516 if self.cannot_be_a_base() {
517 return None;
518 }
519
520 // Scheme, host and port need to be the same
521 if self.scheme() != url.scheme() || self.host() != url.host() || self.port() != url.port() {
522 return None;
523 }
524
525 // We ignore username/password at this point
526
527 // The path has to be transformed
528 let mut relative = String::new();
529
530 // Extract the filename of both URIs, these need to be handled separately
531 fn extract_path_filename(s: &str) -> (&str, &str) {
532 let last_slash_idx = s.rfind('/').unwrap_or(0);
533 let (path, filename) = s.split_at(last_slash_idx);
534 if filename.is_empty() {
535 (path, "")
536 } else {
537 (path, &filename[1..])
538 }
539 }
540
541 let (base_path, base_filename) = extract_path_filename(self.path());
542 let (url_path, url_filename) = extract_path_filename(url.path());
543
544 let mut base_path = base_path.split('/').peekable();
545 let mut url_path = url_path.split('/').peekable();
546
547 // Skip over the common prefix
548 while base_path.peek().is_some() && base_path.peek() == url_path.peek() {
549 base_path.next();
550 url_path.next();
551 }
552
553 // Add `..` segments for the remainder of the base path
554 for base_path_segment in base_path {
555 // Skip empty last segments
556 if base_path_segment.is_empty() {
557 break;
558 }
559
560 if !relative.is_empty() {
561 relative.push('/');
562 }
563
564 relative.push_str("..");
565 }
566
567 // Append the remainder of the other URI
568 for url_path_segment in url_path {
569 if !relative.is_empty() {
570 relative.push('/');
571 }
572
573 relative.push_str(url_path_segment);
574 }
575
576 // Add the filename if they are not the same
577 if !relative.is_empty() || base_filename != url_filename {
578 // If the URIs filename is empty this means that it was a directory
579 // so we'll have to append a '/'.
580 //
581 // Otherwise append it directly as the new filename.
582 if url_filename.is_empty() {
583 relative.push('/');
584 } else {
585 if !relative.is_empty() {
586 relative.push('/');
587 }
588 relative.push_str(url_filename);
589 }
590 }
591
592 // Query and fragment are only taken from the other URI
593 if let Some(query) = url.query() {
594 relative.push('?');
595 relative.push_str(query);
596 }
597
598 if let Some(fragment) = url.fragment() {
599 relative.push('#');
600 relative.push_str(fragment);
601 }
602
603 Some(relative)
604 }
605
606 /// Return a default `ParseOptions` that can fully configure the URL parser.
607 ///
608 /// # Examples
609 ///
610 /// Get default `ParseOptions`, then change base url
611 ///
612 /// ```rust
613 /// use url::Url;
614 /// # use url::ParseError;
615 /// # fn run() -> Result<(), ParseError> {
616 /// let options = Url::options();
617 /// let api = Url::parse("https://api.example.com")?;
618 /// let base_url = options.base_url(Some(&api));
619 /// let version_url = base_url.parse("version.json")?;
620 /// assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
621 /// # Ok(())
622 /// # }
623 /// # run().unwrap();
624 /// ```
625 pub fn options<'a>() -> ParseOptions<'a> {
626 ParseOptions {
627 base_url: None,
628 encoding_override: None,
629 violation_fn: None,
630 }
631 }
632
633 /// Return the serialization of this URL.
634 ///
635 /// This is fast since that serialization is already stored in the `Url` struct.
636 ///
637 /// # Examples
638 ///
639 /// ```rust
640 /// use url::Url;
641 /// # use url::ParseError;
642 ///
643 /// # fn run() -> Result<(), ParseError> {
644 /// let url_str = "https://example.net/";
645 /// let url = Url::parse(url_str)?;
646 /// assert_eq!(url.as_str(), url_str);
647 /// # Ok(())
648 /// # }
649 /// # run().unwrap();
650 /// ```
651 #[inline]
652 pub fn as_str(&self) -> &str {
653 &self.serialization
654 }
655
656 /// Return the serialization of this URL.
657 ///
658 /// This consumes the `Url` and takes ownership of the `String` stored in it.
659 ///
660 /// # Examples
661 ///
662 /// ```rust
663 /// use url::Url;
664 /// # use url::ParseError;
665 ///
666 /// # fn run() -> Result<(), ParseError> {
667 /// let url_str = "https://example.net/";
668 /// let url = Url::parse(url_str)?;
669 /// assert_eq!(String::from(url), url_str);
670 /// # Ok(())
671 /// # }
672 /// # run().unwrap();
673 /// ```
674 #[inline]
675 #[deprecated(since = "2.3.0", note = "use Into<String>")]
676 pub fn into_string(self) -> String {
677 self.into()
678 }
679
680 /// For internal testing, not part of the public API.
681 ///
682 /// Methods of the `Url` struct assume a number of invariants.
683 /// This checks each of these invariants and panic if one is not met.
684 /// This is for testing rust-url itself.
685 #[doc(hidden)]
686 pub fn check_invariants(&self) -> Result<(), String> {
687 macro_rules! assert {
688 ($x: expr) => {
689 if !$x {
690 return Err(format!(
691 "!( {} ) for URL {:?}",
692 stringify!($x),
693 self.serialization
694 ));
695 }
696 };
697 }
698
699 macro_rules! assert_eq {
700 ($a: expr, $b: expr) => {
701 {
702 let a = $a;
703 let b = $b;
704 if a != b {
705 return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
706 a, b, stringify!($a), stringify!($b),
707 self.serialization))
708 }
709 }
710 }
711 }
712
713 assert!(self.scheme_end >= 1);
714 assert!(self.byte_at(0).is_ascii_alphabetic());
715 assert!(self
716 .slice(1..self.scheme_end)
717 .chars()
718 .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.')));
719 assert_eq!(self.byte_at(self.scheme_end), b':');
720
721 if self.slice(self.scheme_end + 1..).starts_with("//") {
722 // URL with authority
723 if self.username_end != self.serialization.len() as u32 {
724 match self.byte_at(self.username_end) {
725 b':' => {
726 assert!(self.host_start >= self.username_end + 2);
727 assert_eq!(self.byte_at(self.host_start - 1), b'@');
728 }
729 b'@' => assert!(self.host_start == self.username_end + 1),
730 _ => assert_eq!(self.username_end, self.scheme_end + 3),
731 }
732 }
733 assert!(self.host_start >= self.username_end);
734 assert!(self.host_end >= self.host_start);
735 let host_str = self.slice(self.host_start..self.host_end);
736 match self.host {
737 HostInternal::None => assert_eq!(host_str, ""),
738 HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
739 HostInternal::Ipv6(address) => {
740 let h: Host<String> = Host::Ipv6(address);
741 assert_eq!(host_str, h.to_string())
742 }
743 HostInternal::Domain => {
744 if SchemeType::from(self.scheme()).is_special() {
745 assert!(!host_str.is_empty())
746 }
747 }
748 }
749 if self.path_start == self.host_end {
750 assert_eq!(self.port, None);
751 } else {
752 assert_eq!(self.byte_at(self.host_end), b':');
753 let port_str = self.slice(self.host_end + 1..self.path_start);
754 assert_eq!(
755 self.port,
756 Some(port_str.parse::<u16>().expect("Couldn't parse port?"))
757 );
758 }
759 assert!(
760 self.path_start as usize == self.serialization.len()
761 || matches!(self.byte_at(self.path_start), b'/' | b'#' | b'?')
762 );
763 } else {
764 // Anarchist URL (no authority)
765 assert_eq!(self.username_end, self.scheme_end + 1);
766 assert_eq!(self.host_start, self.scheme_end + 1);
767 assert_eq!(self.host_end, self.scheme_end + 1);
768 assert_eq!(self.host, HostInternal::None);
769 assert_eq!(self.port, None);
770 if self.path().starts_with("//") {
771 // special case when first path segment is empty
772 assert_eq!(self.byte_at(self.scheme_end + 1), b'/');
773 assert_eq!(self.byte_at(self.scheme_end + 2), b'.');
774 assert_eq!(self.path_start, self.scheme_end + 3);
775 } else {
776 assert_eq!(self.path_start, self.scheme_end + 1);
777 }
778 }
779 if let Some(start) = self.query_start {
780 assert!(start >= self.path_start);
781 assert_eq!(self.byte_at(start), b'?');
782 }
783 if let Some(start) = self.fragment_start {
784 assert!(start >= self.path_start);
785 assert_eq!(self.byte_at(start), b'#');
786 }
787 if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
788 assert!(fragment_start > query_start);
789 }
790
791 let other = Self::parse(self.as_str()).expect("Failed to parse myself?");
792 assert_eq!(&self.serialization, &other.serialization);
793 assert_eq!(self.scheme_end, other.scheme_end);
794 assert_eq!(self.username_end, other.username_end);
795 assert_eq!(self.host_start, other.host_start);
796 assert_eq!(self.host_end, other.host_end);
797 assert!(
798 self.host == other.host ||
799 // XXX No host round-trips to empty host.
800 // See https://github.com/whatwg/url/issues/79
801 (self.host_str(), other.host_str()) == (None, Some(""))
802 );
803 assert_eq!(self.port, other.port);
804 assert_eq!(self.path_start, other.path_start);
805 assert_eq!(self.query_start, other.query_start);
806 assert_eq!(self.fragment_start, other.fragment_start);
807 Ok(())
808 }
809
810 /// Return the origin of this URL (<https://url.spec.whatwg.org/#origin>)
811 ///
812 /// Note: this returns an opaque origin for `file:` URLs, which causes
813 /// `url.origin() != url.origin()`.
814 ///
815 /// # Examples
816 ///
817 /// URL with `ftp` scheme:
818 ///
819 /// ```rust
820 /// use url::{Host, Origin, Url};
821 /// # use url::ParseError;
822 ///
823 /// # fn run() -> Result<(), ParseError> {
824 /// let url = Url::parse("ftp://example.com/foo")?;
825 /// assert_eq!(url.origin(),
826 /// Origin::Tuple("ftp".into(),
827 /// Host::Domain("example.com".into()),
828 /// 21));
829 /// # Ok(())
830 /// # }
831 /// # run().unwrap();
832 /// ```
833 ///
834 /// URL with `blob` scheme:
835 ///
836 /// ```rust
837 /// use url::{Host, Origin, Url};
838 /// # use url::ParseError;
839 ///
840 /// # fn run() -> Result<(), ParseError> {
841 /// let url = Url::parse("blob:https://example.com/foo")?;
842 /// assert_eq!(url.origin(),
843 /// Origin::Tuple("https".into(),
844 /// Host::Domain("example.com".into()),
845 /// 443));
846 /// # Ok(())
847 /// # }
848 /// # run().unwrap();
849 /// ```
850 ///
851 /// URL with `file` scheme:
852 ///
853 /// ```rust
854 /// use url::{Host, Origin, Url};
855 /// # use url::ParseError;
856 ///
857 /// # fn run() -> Result<(), ParseError> {
858 /// let url = Url::parse("file:///tmp/foo")?;
859 /// assert!(!url.origin().is_tuple());
860 ///
861 /// let other_url = Url::parse("file:///tmp/foo")?;
862 /// assert!(url.origin() != other_url.origin());
863 /// # Ok(())
864 /// # }
865 /// # run().unwrap();
866 /// ```
867 ///
868 /// URL with other scheme:
869 ///
870 /// ```rust
871 /// use url::{Host, Origin, Url};
872 /// # use url::ParseError;
873 ///
874 /// # fn run() -> Result<(), ParseError> {
875 /// let url = Url::parse("foo:bar")?;
876 /// assert!(!url.origin().is_tuple());
877 /// # Ok(())
878 /// # }
879 /// # run().unwrap();
880 /// ```
881 #[inline]
882 pub fn origin(&self) -> Origin {
883 origin::url_origin(self)
884 }
885
886 /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
887 ///
888 /// # Examples
889 ///
890 /// ```
891 /// use url::Url;
892 /// # use url::ParseError;
893 ///
894 /// # fn run() -> Result<(), ParseError> {
895 /// let url = Url::parse("file:///tmp/foo")?;
896 /// assert_eq!(url.scheme(), "file");
897 /// # Ok(())
898 /// # }
899 /// # run().unwrap();
900 /// ```
901 #[inline]
902 pub fn scheme(&self) -> &str {
903 self.slice(..self.scheme_end)
904 }
905
906 /// Return whether the URL is special (has a special scheme)
907 ///
908 /// # Examples
909 ///
910 /// ```
911 /// use url::Url;
912 /// # use url::ParseError;
913 ///
914 /// # fn run() -> Result<(), ParseError> {
915 /// assert!(Url::parse("http:///tmp/foo")?.is_special());
916 /// assert!(Url::parse("file:///tmp/foo")?.is_special());
917 /// assert!(!Url::parse("moz:///tmp/foo")?.is_special());
918 /// # Ok(())
919 /// # }
920 /// # run().unwrap();
921 /// ```
922 pub fn is_special(&self) -> bool {
923 let scheme_type = SchemeType::from(self.scheme());
924 scheme_type.is_special()
925 }
926
927 /// Return whether the URL has an 'authority',
928 /// which can contain a username, password, host, and port number.
929 ///
930 /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
931 /// or cannot-be-a-base like `data:text/plain,Stuff`.
932 ///
933 /// See also the `authority` method.
934 ///
935 /// # Examples
936 ///
937 /// ```
938 /// use url::Url;
939 /// # use url::ParseError;
940 ///
941 /// # fn run() -> Result<(), ParseError> {
942 /// let url = Url::parse("ftp://rms@example.com")?;
943 /// assert!(url.has_authority());
944 ///
945 /// let url = Url::parse("unix:/run/foo.socket")?;
946 /// assert!(!url.has_authority());
947 ///
948 /// let url = Url::parse("data:text/plain,Stuff")?;
949 /// assert!(!url.has_authority());
950 /// # Ok(())
951 /// # }
952 /// # run().unwrap();
953 /// ```
954 #[inline]
955 pub fn has_authority(&self) -> bool {
956 debug_assert!(self.byte_at(self.scheme_end) == b':');
957 self.slice(self.scheme_end..).starts_with("://")
958 }
959
960 /// Return the authority of this URL as an ASCII string.
961 ///
962 /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
963 /// of a special URL, or percent encoded for non-special URLs.
964 /// IPv6 addresses are given between `[` and `]` brackets.
965 /// Ports are omitted if they match the well known port of a special URL.
966 ///
967 /// Username and password are percent-encoded.
968 ///
969 /// See also the `has_authority` method.
970 ///
971 /// # Examples
972 ///
973 /// ```
974 /// use url::Url;
975 /// # use url::ParseError;
976 ///
977 /// # fn run() -> Result<(), ParseError> {
978 /// let url = Url::parse("unix:/run/foo.socket")?;
979 /// assert_eq!(url.authority(), "");
980 /// let url = Url::parse("file:///tmp/foo")?;
981 /// assert_eq!(url.authority(), "");
982 /// let url = Url::parse("https://user:password@example.com/tmp/foo")?;
983 /// assert_eq!(url.authority(), "user:password@example.com");
984 /// let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?;
985 /// assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667");
986 /// let url = Url::parse("http://àlex.рф.example.com:80/foo")?;
987 /// assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com");
988 /// # Ok(())
989 /// # }
990 /// # run().unwrap();
991 /// ```
992 pub fn authority(&self) -> &str {
993 let scheme_separator_len = "://".len() as u32;
994 if self.has_authority() && self.path_start > self.scheme_end + scheme_separator_len {
995 self.slice(self.scheme_end + scheme_separator_len..self.path_start)
996 } else {
997 ""
998 }
999 }
1000
1001 /// Return whether this URL is a cannot-be-a-base URL,
1002 /// meaning that parsing a relative URL string with this URL as the base will return an error.
1003 ///
1004 /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
1005 /// as is typically the case of `data:` and `mailto:` URLs.
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// use url::Url;
1011 /// # use url::ParseError;
1012 ///
1013 /// # fn run() -> Result<(), ParseError> {
1014 /// let url = Url::parse("ftp://rms@example.com")?;
1015 /// assert!(!url.cannot_be_a_base());
1016 ///
1017 /// let url = Url::parse("unix:/run/foo.socket")?;
1018 /// assert!(!url.cannot_be_a_base());
1019 ///
1020 /// let url = Url::parse("data:text/plain,Stuff")?;
1021 /// assert!(url.cannot_be_a_base());
1022 /// # Ok(())
1023 /// # }
1024 /// # run().unwrap();
1025 /// ```
1026 #[inline]
1027 pub fn cannot_be_a_base(&self) -> bool {
1028 !self.slice(self.scheme_end + 1..).starts_with('/')
1029 }
1030
1031 /// Return the username for this URL (typically the empty string)
1032 /// as a percent-encoded ASCII string.
1033 ///
1034 /// # Examples
1035 ///
1036 /// ```
1037 /// use url::Url;
1038 /// # use url::ParseError;
1039 ///
1040 /// # fn run() -> Result<(), ParseError> {
1041 /// let url = Url::parse("ftp://rms@example.com")?;
1042 /// assert_eq!(url.username(), "rms");
1043 ///
1044 /// let url = Url::parse("ftp://:secret123@example.com")?;
1045 /// assert_eq!(url.username(), "");
1046 ///
1047 /// let url = Url::parse("https://example.com")?;
1048 /// assert_eq!(url.username(), "");
1049 /// # Ok(())
1050 /// # }
1051 /// # run().unwrap();
1052 /// ```
1053 pub fn username(&self) -> &str {
1054 let scheme_separator_len = "://".len() as u32;
1055 if self.has_authority() && self.username_end > self.scheme_end + scheme_separator_len {
1056 self.slice(self.scheme_end + scheme_separator_len..self.username_end)
1057 } else {
1058 ""
1059 }
1060 }
1061
1062 /// Return the password for this URL, if any, as a percent-encoded ASCII string.
1063 ///
1064 /// # Examples
1065 ///
1066 /// ```
1067 /// use url::Url;
1068 /// # use url::ParseError;
1069 ///
1070 /// # fn run() -> Result<(), ParseError> {
1071 /// let url = Url::parse("ftp://rms:secret123@example.com")?;
1072 /// assert_eq!(url.password(), Some("secret123"));
1073 ///
1074 /// let url = Url::parse("ftp://:secret123@example.com")?;
1075 /// assert_eq!(url.password(), Some("secret123"));
1076 ///
1077 /// let url = Url::parse("ftp://rms@example.com")?;
1078 /// assert_eq!(url.password(), None);
1079 ///
1080 /// let url = Url::parse("https://example.com")?;
1081 /// assert_eq!(url.password(), None);
1082 /// # Ok(())
1083 /// # }
1084 /// # run().unwrap();
1085 /// ```
1086 pub fn password(&self) -> Option<&str> {
1087 // This ':' is not the one marking a port number since a host can not be empty.
1088 // (Except for file: URLs, which do not have port numbers.)
1089 if self.has_authority()
1090 && self.username_end != self.serialization.len() as u32
1091 && self.byte_at(self.username_end) == b':'
1092 {
1093 debug_assert!(self.byte_at(self.host_start - 1) == b'@');
1094 Some(self.slice(self.username_end + 1..self.host_start - 1))
1095 } else {
1096 None
1097 }
1098 }
1099
1100 /// Equivalent to `url.host().is_some()`.
1101 ///
1102 /// # Examples
1103 ///
1104 /// ```
1105 /// use url::Url;
1106 /// # use url::ParseError;
1107 ///
1108 /// # fn run() -> Result<(), ParseError> {
1109 /// let url = Url::parse("ftp://rms@example.com")?;
1110 /// assert!(url.has_host());
1111 ///
1112 /// let url = Url::parse("unix:/run/foo.socket")?;
1113 /// assert!(!url.has_host());
1114 ///
1115 /// let url = Url::parse("data:text/plain,Stuff")?;
1116 /// assert!(!url.has_host());
1117 /// # Ok(())
1118 /// # }
1119 /// # run().unwrap();
1120 /// ```
1121 pub fn has_host(&self) -> bool {
1122 !matches!(self.host, HostInternal::None)
1123 }
1124
1125 /// Return the string representation of the host (domain or IP address) for this URL, if any.
1126 ///
1127 /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
1128 /// of a special URL, or percent encoded for non-special URLs.
1129 /// IPv6 addresses are given between `[` and `]` brackets.
1130 ///
1131 /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
1132 /// don’t have a host.
1133 ///
1134 /// See also the `host` method.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// use url::Url;
1140 /// # use url::ParseError;
1141 ///
1142 /// # fn run() -> Result<(), ParseError> {
1143 /// let url = Url::parse("https://127.0.0.1/index.html")?;
1144 /// assert_eq!(url.host_str(), Some("127.0.0.1"));
1145 ///
1146 /// let url = Url::parse("https://subdomain.example.com")?;
1147 /// assert_eq!(url.host_str(), Some("subdomain.example.com"));
1148 ///
1149 /// let url = Url::parse("ftp://rms@example.com")?;
1150 /// assert_eq!(url.host_str(), Some("example.com"));
1151 ///
1152 /// let url = Url::parse("unix:/run/foo.socket")?;
1153 /// assert_eq!(url.host_str(), None);
1154 ///
1155 /// let url = Url::parse("data:text/plain,Stuff")?;
1156 /// assert_eq!(url.host_str(), None);
1157 /// # Ok(())
1158 /// # }
1159 /// # run().unwrap();
1160 /// ```
1161 pub fn host_str(&self) -> Option<&str> {
1162 if self.has_host() {
1163 Some(self.slice(self.host_start..self.host_end))
1164 } else {
1165 None
1166 }
1167 }
1168
1169 /// Return the parsed representation of the host for this URL.
1170 /// Non-ASCII domain labels are punycode-encoded per IDNA if this is the host
1171 /// of a special URL, or percent encoded for non-special URLs.
1172 ///
1173 /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
1174 /// don’t have a host.
1175 ///
1176 /// See also the `host_str` method.
1177 ///
1178 /// # Examples
1179 ///
1180 /// ```
1181 /// use url::Url;
1182 /// # use url::ParseError;
1183 ///
1184 /// # fn run() -> Result<(), ParseError> {
1185 /// let url = Url::parse("https://127.0.0.1/index.html")?;
1186 /// assert!(url.host().is_some());
1187 ///
1188 /// let url = Url::parse("ftp://rms@example.com")?;
1189 /// assert!(url.host().is_some());
1190 ///
1191 /// let url = Url::parse("unix:/run/foo.socket")?;
1192 /// assert!(url.host().is_none());
1193 ///
1194 /// let url = Url::parse("data:text/plain,Stuff")?;
1195 /// assert!(url.host().is_none());
1196 /// # Ok(())
1197 /// # }
1198 /// # run().unwrap();
1199 /// ```
1200 pub fn host(&self) -> Option<Host<&str>> {
1201 match self.host {
1202 HostInternal::None => None,
1203 HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
1204 HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
1205 HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
1206 }
1207 }
1208
1209 /// If this URL has a host and it is a domain name (not an IP address), return it.
1210 /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
1211 /// of a special URL, or percent encoded for non-special URLs.
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```
1216 /// use url::Url;
1217 /// # use url::ParseError;
1218 ///
1219 /// # fn run() -> Result<(), ParseError> {
1220 /// let url = Url::parse("https://127.0.0.1/")?;
1221 /// assert_eq!(url.domain(), None);
1222 ///
1223 /// let url = Url::parse("mailto:rms@example.net")?;
1224 /// assert_eq!(url.domain(), None);
1225 ///
1226 /// let url = Url::parse("https://example.com/")?;
1227 /// assert_eq!(url.domain(), Some("example.com"));
1228 ///
1229 /// let url = Url::parse("https://subdomain.example.com/")?;
1230 /// assert_eq!(url.domain(), Some("subdomain.example.com"));
1231 ///
1232 /// # Ok(())
1233 /// # }
1234 /// # run().unwrap();
1235 /// ```
1236 pub fn domain(&self) -> Option<&str> {
1237 match self.host {
1238 HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
1239 _ => None,
1240 }
1241 }
1242
1243 /// Return the port number for this URL, if any.
1244 ///
1245 /// Note that default port numbers are never reflected by the serialization,
1246 /// use the `port_or_known_default()` method if you want a default port number returned.
1247 ///
1248 /// # Examples
1249 ///
1250 /// ```
1251 /// use url::Url;
1252 /// # use url::ParseError;
1253 ///
1254 /// # fn run() -> Result<(), ParseError> {
1255 /// let url = Url::parse("https://example.com")?;
1256 /// assert_eq!(url.port(), None);
1257 ///
1258 /// let url = Url::parse("https://example.com:443/")?;
1259 /// assert_eq!(url.port(), None);
1260 ///
1261 /// let url = Url::parse("ssh://example.com:22")?;
1262 /// assert_eq!(url.port(), Some(22));
1263 /// # Ok(())
1264 /// # }
1265 /// # run().unwrap();
1266 /// ```
1267 #[inline]
1268 pub fn port(&self) -> Option<u16> {
1269 self.port
1270 }
1271
1272 /// Return the port number for this URL, or the default port number if it is known.
1273 ///
1274 /// This method only knows the default port number
1275 /// of the `http`, `https`, `ws`, `wss` and `ftp` schemes.
1276 ///
1277 /// For URLs in these schemes, this method always returns `Some(_)`.
1278 /// For other schemes, it is the same as `Url::port()`.
1279 ///
1280 /// # Examples
1281 ///
1282 /// ```
1283 /// use url::Url;
1284 /// # use url::ParseError;
1285 ///
1286 /// # fn run() -> Result<(), ParseError> {
1287 /// let url = Url::parse("foo://example.com")?;
1288 /// assert_eq!(url.port_or_known_default(), None);
1289 ///
1290 /// let url = Url::parse("foo://example.com:1456")?;
1291 /// assert_eq!(url.port_or_known_default(), Some(1456));
1292 ///
1293 /// let url = Url::parse("https://example.com")?;
1294 /// assert_eq!(url.port_or_known_default(), Some(443));
1295 /// # Ok(())
1296 /// # }
1297 /// # run().unwrap();
1298 /// ```
1299 #[inline]
1300 pub fn port_or_known_default(&self) -> Option<u16> {
1301 self.port.or_else(|| parser::default_port(self.scheme()))
1302 }
1303
1304 /// Resolve a URL’s host and port number to `SocketAddr`.
1305 ///
1306 /// If the URL has the default port number of a scheme that is unknown to this library,
1307 /// `default_port_number` provides an opportunity to provide the actual port number.
1308 /// In non-example code this should be implemented either simply as `|| None`,
1309 /// or by matching on the URL’s `.scheme()`.
1310 ///
1311 /// If the host is a domain, it is resolved using the standard library’s DNS support.
1312 ///
1313 /// # Examples
1314 ///
1315 /// ```no_run
1316 /// let url = url::Url::parse("https://example.net/").unwrap();
1317 /// let addrs = url.socket_addrs(|| None).unwrap();
1318 /// std::net::TcpStream::connect(&*addrs)
1319 /// # ;
1320 /// ```
1321 ///
1322 /// ```
1323 /// /// With application-specific known default port numbers
1324 /// fn socket_addrs(url: url::Url) -> std::io::Result<Vec<std::net::SocketAddr>> {
1325 /// url.socket_addrs(|| match url.scheme() {
1326 /// "socks5" | "socks5h" => Some(1080),
1327 /// _ => None,
1328 /// })
1329 /// }
1330 /// ```
1331 #[cfg(feature = "std")]
1332 #[cfg(any(
1333 unix,
1334 windows,
1335 target_os = "redox",
1336 target_os = "wasi",
1337 target_os = "hermit"
1338 ))]
1339 pub fn socket_addrs(
1340 &self,
1341 default_port_number: impl Fn() -> Option<u16>,
1342 ) -> io::Result<alloc::vec::Vec<SocketAddr>> {
1343 // Note: trying to avoid the Vec allocation by returning `impl AsRef<[SocketAddr]>`
1344 // causes borrowck issues because the return value borrows `default_port_number`:
1345 //
1346 // https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md#scoping-for-type-and-lifetime-parameters
1347 //
1348 // > This RFC proposes that *all* type parameters are considered in scope
1349 // > for `impl Trait` in return position
1350
1351 fn io_result<T>(opt: Option<T>, message: &str) -> io::Result<T> {
1352 opt.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, message))
1353 }
1354
1355 let host = io_result(self.host(), "No host name in the URL")?;
1356 let port = io_result(
1357 self.port_or_known_default().or_else(default_port_number),
1358 "No port number in the URL",
1359 )?;
1360 Ok(match host {
1361 Host::Domain(domain) => (domain, port).to_socket_addrs()?.collect(),
1362 Host::Ipv4(ip) => vec![(ip, port).into()],
1363 Host::Ipv6(ip) => vec![(ip, port).into()],
1364 })
1365 }
1366
1367 /// Return the path for this URL, as a percent-encoded ASCII string.
1368 /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
1369 /// For other URLs, this starts with a '/' slash
1370 /// and continues with slash-separated path segments.
1371 ///
1372 /// # Examples
1373 ///
1374 /// ```rust
1375 /// use url::{Url, ParseError};
1376 ///
1377 /// # fn run() -> Result<(), ParseError> {
1378 /// let url = Url::parse("https://example.com/api/versions?page=2")?;
1379 /// assert_eq!(url.path(), "/api/versions");
1380 ///
1381 /// let url = Url::parse("https://example.com")?;
1382 /// assert_eq!(url.path(), "/");
1383 ///
1384 /// let url = Url::parse("https://example.com/countries/việt nam")?;
1385 /// assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
1386 /// # Ok(())
1387 /// # }
1388 /// # run().unwrap();
1389 /// ```
1390 pub fn path(&self) -> &str {
1391 match (self.query_start, self.fragment_start) {
1392 (None, None) => self.slice(self.path_start..),
1393 (Some(next_component_start), _) | (None, Some(next_component_start)) => {
1394 self.slice(self.path_start..next_component_start)
1395 }
1396 }
1397 }
1398
1399 /// Unless this URL is cannot-be-a-base,
1400 /// return an iterator of '/' slash-separated path segments,
1401 /// each as a percent-encoded ASCII string.
1402 ///
1403 /// Return `None` for cannot-be-a-base URLs.
1404 ///
1405 /// When `Some` is returned, the iterator always contains at least one string
1406 /// (which may be empty).
1407 ///
1408 /// # Examples
1409 ///
1410 /// ```
1411 /// use url::Url;
1412 ///
1413 /// # #[cfg(feature = "std")]
1414 /// # use std::error::Error;
1415 /// # #[cfg(not(feature = "std"))]
1416 /// # use core::error::Error;
1417 ///
1418 /// # fn run() -> Result<(), Box<dyn Error>> {
1419 /// let url = Url::parse("https://example.com/foo/bar")?;
1420 /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
1421 /// assert_eq!(path_segments.next(), Some("foo"));
1422 /// assert_eq!(path_segments.next(), Some("bar"));
1423 /// assert_eq!(path_segments.next(), None);
1424 ///
1425 /// let url = Url::parse("https://example.com")?;
1426 /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
1427 /// assert_eq!(path_segments.next(), Some(""));
1428 /// assert_eq!(path_segments.next(), None);
1429 ///
1430 /// let url = Url::parse("data:text/plain,HelloWorld")?;
1431 /// assert!(url.path_segments().is_none());
1432 ///
1433 /// let url = Url::parse("https://example.com/countries/việt nam")?;
1434 /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
1435 /// assert_eq!(path_segments.next(), Some("countries"));
1436 /// assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
1437 /// # Ok(())
1438 /// # }
1439 /// # run().unwrap();
1440 /// ```
1441 pub fn path_segments(&self) -> Option<str::Split<'_, char>> {
1442 let path = self.path();
1443 path.strip_prefix('/').map(|remainder| remainder.split('/'))
1444 }
1445
1446 /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
1447 ///
1448 /// # Examples
1449 ///
1450 /// ```rust
1451 /// use url::Url;
1452 /// # use url::ParseError;
1453 ///
1454 /// fn run() -> Result<(), ParseError> {
1455 /// let url = Url::parse("https://example.com/products?page=2")?;
1456 /// let query = url.query();
1457 /// assert_eq!(query, Some("page=2"));
1458 ///
1459 /// let url = Url::parse("https://example.com/products")?;
1460 /// let query = url.query();
1461 /// assert!(query.is_none());
1462 ///
1463 /// let url = Url::parse("https://example.com/?country=español")?;
1464 /// let query = url.query();
1465 /// assert_eq!(query, Some("country=espa%C3%B1ol"));
1466 /// # Ok(())
1467 /// # }
1468 /// # run().unwrap();
1469 /// ```
1470 pub fn query(&self) -> Option<&str> {
1471 match (self.query_start, self.fragment_start) {
1472 (None, _) => None,
1473 (Some(query_start), None) => {
1474 debug_assert!(self.byte_at(query_start) == b'?');
1475 Some(self.slice(query_start + 1..))
1476 }
1477 (Some(query_start), Some(fragment_start)) => {
1478 debug_assert!(self.byte_at(query_start) == b'?');
1479 Some(self.slice(query_start + 1..fragment_start))
1480 }
1481 }
1482 }
1483
1484 /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
1485 /// and return an iterator of (key, value) pairs.
1486 ///
1487 /// # Examples
1488 ///
1489 /// ```rust
1490 /// use std::borrow::Cow;
1491 ///
1492 /// use url::Url;
1493 /// # use url::ParseError;
1494 ///
1495 /// # fn run() -> Result<(), ParseError> {
1496 /// let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
1497 /// let mut pairs = url.query_pairs();
1498 ///
1499 /// assert_eq!(pairs.count(), 2);
1500 ///
1501 /// assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
1502 /// assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
1503 /// # Ok(())
1504 /// # }
1505 /// # run().unwrap();
1506 /// ```
1507 #[inline]
1508 pub fn query_pairs(&self) -> form_urlencoded::Parse<'_> {
1509 form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
1510 }
1511
1512 /// Return this URL’s fragment identifier, if any.
1513 ///
1514 /// A fragment is the part of the URL after the `#` symbol.
1515 /// The fragment is optional and, if present, contains a fragment identifier
1516 /// that identifies a secondary resource, such as a section heading
1517 /// of a document.
1518 ///
1519 /// In HTML, the fragment identifier is usually the id attribute of a an element
1520 /// that is scrolled to on load. Browsers typically will not send the fragment portion
1521 /// of a URL to the server.
1522 ///
1523 /// **Note:** the parser did *not* percent-encode this component,
1524 /// but the input may have been percent-encoded already.
1525 ///
1526 /// # Examples
1527 ///
1528 /// ```rust
1529 /// use url::Url;
1530 /// # use url::ParseError;
1531 ///
1532 /// # fn run() -> Result<(), ParseError> {
1533 /// let url = Url::parse("https://example.com/data.csv#row=4")?;
1534 ///
1535 /// assert_eq!(url.fragment(), Some("row=4"));
1536 ///
1537 /// let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;
1538 ///
1539 /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
1540 /// # Ok(())
1541 /// # }
1542 /// # run().unwrap();
1543 /// ```
1544 pub fn fragment(&self) -> Option<&str> {
1545 self.fragment_start.map(|start| {
1546 debug_assert!(self.byte_at(start) == b'#');
1547 self.slice(start + 1..)
1548 })
1549 }
1550
1551 fn mutate<F: FnOnce(&mut Parser<'_>) -> R, R>(&mut self, f: F) -> R {
1552 let mut parser = Parser::for_setter(mem::take(&mut self.serialization));
1553 let result = f(&mut parser);
1554 self.serialization = parser.serialization;
1555 result
1556 }
1557
1558 /// Change this URL’s fragment identifier.
1559 ///
1560 /// # Examples
1561 ///
1562 /// ```rust
1563 /// use url::Url;
1564 /// # use url::ParseError;
1565 ///
1566 /// # fn run() -> Result<(), ParseError> {
1567 /// let mut url = Url::parse("https://example.com/data.csv")?;
1568 /// assert_eq!(url.as_str(), "https://example.com/data.csv");
1569 ///
1570 /// url.set_fragment(Some("cell=4,1-6,2"));
1571 /// assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
1572 /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
1573 ///
1574 /// url.set_fragment(None);
1575 /// assert_eq!(url.as_str(), "https://example.com/data.csv");
1576 /// assert!(url.fragment().is_none());
1577 /// # Ok(())
1578 /// # }
1579 /// # run().unwrap();
1580 /// ```
1581 pub fn set_fragment(&mut self, fragment: Option<&str>) {
1582 // Remove any previous fragment
1583 if let Some(start) = self.fragment_start {
1584 debug_assert!(self.byte_at(start) == b'#');
1585 self.serialization.truncate(start as usize);
1586 }
1587 // Write the new one
1588 if let Some(input) = fragment {
1589 self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
1590 self.serialization.push('#');
1591 self.mutate(|parser| parser.parse_fragment(parser::Input::new_no_trim(input)))
1592 } else {
1593 self.fragment_start = None;
1594 self.strip_trailing_spaces_from_opaque_path();
1595 }
1596 }
1597
1598 fn take_fragment(&mut self) -> Option<String> {
1599 self.fragment_start.take().map(|start| {
1600 debug_assert!(self.byte_at(start) == b'#');
1601 let fragment = self.slice(start + 1..).to_owned();
1602 self.serialization.truncate(start as usize);
1603 fragment
1604 })
1605 }
1606
1607 fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
1608 if let Some(ref fragment) = fragment {
1609 assert!(self.fragment_start.is_none());
1610 self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
1611 self.serialization.push('#');
1612 self.serialization.push_str(fragment);
1613 }
1614 }
1615
1616 /// Change this URL’s query string. If `query` is `None`, this URL's
1617 /// query string will be cleared.
1618 ///
1619 /// # Examples
1620 ///
1621 /// ```rust
1622 /// use url::Url;
1623 /// # use url::ParseError;
1624 ///
1625 /// # fn run() -> Result<(), ParseError> {
1626 /// let mut url = Url::parse("https://example.com/products")?;
1627 /// assert_eq!(url.as_str(), "https://example.com/products");
1628 ///
1629 /// url.set_query(Some("page=2"));
1630 /// assert_eq!(url.as_str(), "https://example.com/products?page=2");
1631 /// assert_eq!(url.query(), Some("page=2"));
1632 /// # Ok(())
1633 /// # }
1634 /// # run().unwrap();
1635 /// ```
1636 pub fn set_query(&mut self, query: Option<&str>) {
1637 let fragment = self.take_fragment();
1638
1639 // Remove any previous query
1640 if let Some(start) = self.query_start.take() {
1641 debug_assert!(self.byte_at(start) == b'?');
1642 self.serialization.truncate(start as usize);
1643 }
1644 // Write the new query, if any
1645 if let Some(input) = query {
1646 self.query_start = Some(to_u32(self.serialization.len()).unwrap());
1647 self.serialization.push('?');
1648 let scheme_type = SchemeType::from(self.scheme());
1649 let scheme_end = self.scheme_end;
1650 self.mutate(|parser| {
1651 let vfn = parser.violation_fn;
1652 parser.parse_query(
1653 scheme_type,
1654 scheme_end,
1655 parser::Input::new_trim_tab_and_newlines(input, vfn),
1656 )
1657 });
1658 } else {
1659 self.query_start = None;
1660 if fragment.is_none() {
1661 self.strip_trailing_spaces_from_opaque_path();
1662 }
1663 }
1664
1665 self.restore_already_parsed_fragment(fragment);
1666 }
1667
1668 /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
1669 /// in `application/x-www-form-urlencoded` syntax.
1670 ///
1671 /// The return value has a method-chaining API:
1672 ///
1673 /// ```rust
1674 /// # use url::{Url, ParseError};
1675 ///
1676 /// # fn run() -> Result<(), ParseError> {
1677 /// let mut url = Url::parse("https://example.net?lang=fr#nav")?;
1678 /// assert_eq!(url.query(), Some("lang=fr"));
1679 ///
1680 /// url.query_pairs_mut().append_pair("foo", "bar");
1681 /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
1682 /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
1683 ///
1684 /// url.query_pairs_mut()
1685 /// .clear()
1686 /// .append_pair("foo", "bar & baz")
1687 /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
1688 /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
1689 /// assert_eq!(url.as_str(),
1690 /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
1691 /// # Ok(())
1692 /// # }
1693 /// # run().unwrap();
1694 /// ```
1695 ///
1696 /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
1697 /// not `url.set_query(None)`.
1698 ///
1699 /// The state of `Url` is unspecified if this return value is leaked without being dropped.
1700 pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<'_, UrlQuery<'_>> {
1701 let fragment = self.take_fragment();
1702
1703 let query_start;
1704 if let Some(start) = self.query_start {
1705 debug_assert!(self.byte_at(start) == b'?');
1706 query_start = start as usize;
1707 } else {
1708 query_start = self.serialization.len();
1709 self.query_start = Some(to_u32(query_start).unwrap());
1710 self.serialization.push('?');
1711 }
1712
1713 let query = UrlQuery {
1714 url: Some(self),
1715 fragment,
1716 };
1717 form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
1718 }
1719
1720 fn take_after_path(&mut self) -> String {
1721 match (self.query_start, self.fragment_start) {
1722 (Some(i), _) | (None, Some(i)) => {
1723 let after_path = self.slice(i..).to_owned();
1724 self.serialization.truncate(i as usize);
1725 after_path
1726 }
1727 (None, None) => String::new(),
1728 }
1729 }
1730
1731 /// Change this URL’s path.
1732 ///
1733 /// # Examples
1734 ///
1735 /// ```rust
1736 /// use url::Url;
1737 /// # use url::ParseError;
1738 ///
1739 /// # fn run() -> Result<(), ParseError> {
1740 /// let mut url = Url::parse("https://example.com")?;
1741 /// url.set_path("api/comments");
1742 /// assert_eq!(url.as_str(), "https://example.com/api/comments");
1743 /// assert_eq!(url.path(), "/api/comments");
1744 ///
1745 /// let mut url = Url::parse("https://example.com/api")?;
1746 /// url.set_path("data/report.csv");
1747 /// assert_eq!(url.as_str(), "https://example.com/data/report.csv");
1748 /// assert_eq!(url.path(), "/data/report.csv");
1749 ///
1750 /// // `set_path` percent-encodes the given string if it's not already percent-encoded.
1751 /// let mut url = Url::parse("https://example.com")?;
1752 /// url.set_path("api/some comments");
1753 /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
1754 /// assert_eq!(url.path(), "/api/some%20comments");
1755 ///
1756 /// // `set_path` will not double percent-encode the string if it's already percent-encoded.
1757 /// let mut url = Url::parse("https://example.com")?;
1758 /// url.set_path("api/some%20comments");
1759 /// assert_eq!(url.as_str(), "https://example.com/api/some%20comments");
1760 /// assert_eq!(url.path(), "/api/some%20comments");
1761 ///
1762 /// # Ok(())
1763 /// # }
1764 /// # run().unwrap();
1765 /// ```
1766 pub fn set_path(&mut self, mut path: &str) {
1767 let after_path = self.take_after_path();
1768 let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
1769 let cannot_be_a_base = self.cannot_be_a_base();
1770 let scheme_type = SchemeType::from(self.scheme());
1771 self.serialization.truncate(self.path_start as usize);
1772 self.mutate(|parser| {
1773 if cannot_be_a_base {
1774 if path.starts_with('/') {
1775 parser.serialization.push_str("%2F");
1776 path = &path[1..];
1777 }
1778 parser.parse_cannot_be_a_base_path(parser::Input::new_no_trim(path));
1779 } else {
1780 let mut has_host = true; // FIXME
1781 parser.parse_path_start(
1782 scheme_type,
1783 &mut has_host,
1784 parser::Input::new_no_trim(path),
1785 );
1786 }
1787 });
1788 self.restore_after_path(old_after_path_pos, &after_path);
1789 }
1790
1791 /// Return an object with methods to manipulate this URL’s path segments.
1792 ///
1793 /// Return `Err(())` if this URL is cannot-be-a-base.
1794 #[allow(clippy::result_unit_err)]
1795 pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut<'_>, ()> {
1796 if self.cannot_be_a_base() {
1797 Err(())
1798 } else {
1799 Ok(path_segments::new(self))
1800 }
1801 }
1802
1803 fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
1804 let new_after_path_position = to_u32(self.serialization.len()).unwrap();
1805 let adjust = |index: &mut u32| {
1806 *index -= old_after_path_position;
1807 *index += new_after_path_position;
1808 };
1809 if let Some(ref mut index) = self.query_start {
1810 adjust(index)
1811 }
1812 if let Some(ref mut index) = self.fragment_start {
1813 adjust(index)
1814 }
1815 self.serialization.push_str(after_path)
1816 }
1817
1818 /// Change this URL’s port number.
1819 ///
1820 /// Note that default port numbers are not reflected in the serialization.
1821 ///
1822 /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
1823 /// do nothing and return `Err`.
1824 ///
1825 /// # Examples
1826 ///
1827 /// ```
1828 /// use url::Url;
1829 ///
1830 /// # #[cfg(feature = "std")]
1831 /// # use std::error::Error;
1832 /// # #[cfg(not(feature = "std"))]
1833 /// # use core::error::Error;
1834 ///
1835 /// # fn run() -> Result<(), Box<dyn Error>> {
1836 /// let mut url = Url::parse("ssh://example.net:2048/")?;
1837 ///
1838 /// url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
1839 /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
1840 ///
1841 /// url.set_port(None).map_err(|_| "cannot be base")?;
1842 /// assert_eq!(url.as_str(), "ssh://example.net/");
1843 /// # Ok(())
1844 /// # }
1845 /// # run().unwrap();
1846 /// ```
1847 ///
1848 /// Known default port numbers are not reflected:
1849 ///
1850 /// ```rust
1851 /// use url::Url;
1852 ///
1853 /// # #[cfg(feature = "std")]
1854 /// # use std::error::Error;
1855 /// # #[cfg(not(feature = "std"))]
1856 /// # use core::error::Error;
1857 ///
1858 /// # fn run() -> Result<(), Box<dyn Error>> {
1859 /// let mut url = Url::parse("https://example.org/")?;
1860 ///
1861 /// url.set_port(Some(443)).map_err(|_| "cannot be base")?;
1862 /// assert!(url.port().is_none());
1863 /// # Ok(())
1864 /// # }
1865 /// # run().unwrap();
1866 /// ```
1867 ///
1868 /// Cannot set port for cannot-be-a-base URLs:
1869 ///
1870 /// ```
1871 /// use url::Url;
1872 /// # use url::ParseError;
1873 ///
1874 /// # fn run() -> Result<(), ParseError> {
1875 /// let mut url = Url::parse("mailto:rms@example.net")?;
1876 ///
1877 /// let result = url.set_port(Some(80));
1878 /// assert!(result.is_err());
1879 ///
1880 /// let result = url.set_port(None);
1881 /// assert!(result.is_err());
1882 /// # Ok(())
1883 /// # }
1884 /// # run().unwrap();
1885 /// ```
1886 #[allow(clippy::result_unit_err)]
1887 pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
1888 // has_host implies !cannot_be_a_base
1889 if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
1890 return Err(());
1891 }
1892 if port.is_some() && port == parser::default_port(self.scheme()) {
1893 port = None
1894 }
1895 self.set_port_internal(port);
1896 Ok(())
1897 }
1898
1899 fn set_port_internal(&mut self, port: Option<u16>) {
1900 match (self.port, port) {
1901 (None, None) => {}
1902 (Some(_), None) => {
1903 self.serialization
1904 .drain(self.host_end as usize..self.path_start as usize);
1905 let offset = self.path_start - self.host_end;
1906 self.path_start = self.host_end;
1907 if let Some(ref mut index) = self.query_start {
1908 *index -= offset
1909 }
1910 if let Some(ref mut index) = self.fragment_start {
1911 *index -= offset
1912 }
1913 }
1914 (Some(old), Some(new)) if old == new => {}
1915 (_, Some(new)) => {
1916 let path_and_after = self.slice(self.path_start..).to_owned();
1917 self.serialization.truncate(self.host_end as usize);
1918 write!(&mut self.serialization, ":{new}").unwrap();
1919 let old_path_start = self.path_start;
1920 let new_path_start = to_u32(self.serialization.len()).unwrap();
1921 self.path_start = new_path_start;
1922 let adjust = |index: &mut u32| {
1923 *index -= old_path_start;
1924 *index += new_path_start;
1925 };
1926 if let Some(ref mut index) = self.query_start {
1927 adjust(index)
1928 }
1929 if let Some(ref mut index) = self.fragment_start {
1930 adjust(index)
1931 }
1932 self.serialization.push_str(&path_and_after);
1933 }
1934 }
1935 self.port = port;
1936 }
1937
1938 /// Change this URL’s host.
1939 ///
1940 /// Removing the host (calling this with `None`)
1941 /// will also remove any username, password, and port number.
1942 ///
1943 /// # Examples
1944 ///
1945 /// Change host:
1946 ///
1947 /// ```
1948 /// use url::Url;
1949 /// # use url::ParseError;
1950 ///
1951 /// # fn run() -> Result<(), ParseError> {
1952 /// let mut url = Url::parse("https://example.net")?;
1953 /// let result = url.set_host(Some("rust-lang.org"));
1954 /// assert!(result.is_ok());
1955 /// assert_eq!(url.as_str(), "https://rust-lang.org/");
1956 /// # Ok(())
1957 /// # }
1958 /// # run().unwrap();
1959 /// ```
1960 ///
1961 /// Remove host:
1962 ///
1963 /// ```
1964 /// use url::Url;
1965 /// # use url::ParseError;
1966 ///
1967 /// # fn run() -> Result<(), ParseError> {
1968 /// let mut url = Url::parse("foo://example.net")?;
1969 /// let result = url.set_host(None);
1970 /// assert!(result.is_ok());
1971 /// assert_eq!(url.as_str(), "foo:/");
1972 /// # Ok(())
1973 /// # }
1974 /// # run().unwrap();
1975 /// ```
1976 ///
1977 /// Cannot remove host for 'special' schemes (e.g. `http`):
1978 ///
1979 /// ```
1980 /// use url::Url;
1981 /// # use url::ParseError;
1982 ///
1983 /// # fn run() -> Result<(), ParseError> {
1984 /// let mut url = Url::parse("https://example.net")?;
1985 /// let result = url.set_host(None);
1986 /// assert!(result.is_err());
1987 /// assert_eq!(url.as_str(), "https://example.net/");
1988 /// # Ok(())
1989 /// # }
1990 /// # run().unwrap();
1991 /// ```
1992 ///
1993 /// Cannot change or remove host for cannot-be-a-base URLs:
1994 ///
1995 /// ```
1996 /// use url::Url;
1997 /// # use url::ParseError;
1998 ///
1999 /// # fn run() -> Result<(), ParseError> {
2000 /// let mut url = Url::parse("mailto:rms@example.net")?;
2001 ///
2002 /// let result = url.set_host(Some("rust-lang.org"));
2003 /// assert!(result.is_err());
2004 /// assert_eq!(url.as_str(), "mailto:rms@example.net");
2005 ///
2006 /// let result = url.set_host(None);
2007 /// assert!(result.is_err());
2008 /// assert_eq!(url.as_str(), "mailto:rms@example.net");
2009 /// # Ok(())
2010 /// # }
2011 /// # run().unwrap();
2012 /// ```
2013 ///
2014 /// # Errors
2015 ///
2016 /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
2017 /// a [`ParseError`] variant will be returned.
2018 ///
2019 /// [`ParseError`]: enum.ParseError.html
2020 pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
2021 if self.cannot_be_a_base() {
2022 return Err(ParseError::SetHostOnCannotBeABaseUrl);
2023 }
2024
2025 let scheme_type = SchemeType::from(self.scheme());
2026
2027 if let Some(host) = host {
2028 if host.is_empty() && scheme_type.is_special() && !scheme_type.is_file() {
2029 return Err(ParseError::EmptyHost);
2030 }
2031 let mut host_substr = host;
2032 // Otherwise, if c is U+003A (:) and the [] flag is unset, then
2033 if !host.starts_with('[') || !host.ends_with(']') {
2034 match host.find(':') {
2035 Some(0) => {
2036 // If buffer is the empty string, validation error, return failure.
2037 return Err(ParseError::InvalidDomainCharacter);
2038 }
2039 // Let host be the result of host parsing buffer
2040 Some(colon_index) => {
2041 host_substr = &host[..colon_index];
2042 }
2043 None => {}
2044 }
2045 }
2046 if SchemeType::from(self.scheme()).is_special() {
2047 self.set_host_internal(Host::parse_cow(host_substr.into())?, None);
2048 } else {
2049 self.set_host_internal(Host::parse_opaque_cow(host_substr.into())?, None);
2050 }
2051 } else if self.has_host() {
2052 if scheme_type.is_special() && !scheme_type.is_file() {
2053 return Err(ParseError::EmptyHost);
2054 } else if self.serialization.len() == self.path_start as usize {
2055 self.serialization.push('/');
2056 }
2057 debug_assert!(self.byte_at(self.scheme_end) == b':');
2058 debug_assert!(self.byte_at(self.path_start) == b'/');
2059
2060 let new_path_start = if scheme_type.is_file() {
2061 self.scheme_end + 3
2062 } else {
2063 self.scheme_end + 1
2064 };
2065
2066 self.serialization
2067 .drain(new_path_start as usize..self.path_start as usize);
2068 let offset = self.path_start - new_path_start;
2069 self.path_start = new_path_start;
2070 self.username_end = new_path_start;
2071 self.host_start = new_path_start;
2072 self.host_end = new_path_start;
2073 self.port = None;
2074 if let Some(ref mut index) = self.query_start {
2075 *index -= offset
2076 }
2077 if let Some(ref mut index) = self.fragment_start {
2078 *index -= offset
2079 }
2080 }
2081 Ok(())
2082 }
2083
2084 /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
2085 fn set_host_internal(&mut self, host: Host<Cow<'_, str>>, opt_new_port: Option<Option<u16>>) {
2086 let old_suffix_pos = if opt_new_port.is_some() {
2087 self.path_start
2088 } else {
2089 self.host_end
2090 };
2091 let suffix = self.slice(old_suffix_pos..).to_owned();
2092 self.serialization.truncate(self.host_start as usize);
2093 if !self.has_authority() {
2094 debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
2095 debug_assert!(self.username_end == self.host_start);
2096 self.serialization.push('/');
2097 self.serialization.push('/');
2098 self.username_end += 2;
2099 self.host_start += 2;
2100 }
2101 write!(&mut self.serialization, "{host}").unwrap();
2102 self.host_end = to_u32(self.serialization.len()).unwrap();
2103 self.host = host.into();
2104
2105 if let Some(new_port) = opt_new_port {
2106 self.port = new_port;
2107 if let Some(port) = new_port {
2108 write!(&mut self.serialization, ":{port}").unwrap();
2109 }
2110 }
2111 let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
2112 self.serialization.push_str(&suffix);
2113
2114 let adjust = |index: &mut u32| {
2115 *index -= old_suffix_pos;
2116 *index += new_suffix_pos;
2117 };
2118 adjust(&mut self.path_start);
2119 if let Some(ref mut index) = self.query_start {
2120 adjust(index)
2121 }
2122 if let Some(ref mut index) = self.fragment_start {
2123 adjust(index)
2124 }
2125 }
2126
2127 /// Change this URL’s host to the given IP address.
2128 ///
2129 /// If this URL is cannot-be-a-base, do nothing and return `Err`.
2130 ///
2131 /// Compared to `Url::set_host`, this skips the host parser.
2132 ///
2133 /// # Examples
2134 ///
2135 /// ```rust
2136 /// use url::{Url, ParseError};
2137 ///
2138 /// # fn run() -> Result<(), ParseError> {
2139 /// let mut url = Url::parse("http://example.com")?;
2140 /// url.set_ip_host("127.0.0.1".parse().unwrap());
2141 /// assert_eq!(url.host_str(), Some("127.0.0.1"));
2142 /// assert_eq!(url.as_str(), "http://127.0.0.1/");
2143 /// # Ok(())
2144 /// # }
2145 /// # run().unwrap();
2146 /// ```
2147 ///
2148 /// Cannot change URL's from mailto(cannot-be-base) to ip:
2149 ///
2150 /// ```rust
2151 /// use url::{Url, ParseError};
2152 ///
2153 /// # fn run() -> Result<(), ParseError> {
2154 /// let mut url = Url::parse("mailto:rms@example.com")?;
2155 /// let result = url.set_ip_host("127.0.0.1".parse().unwrap());
2156 ///
2157 /// assert_eq!(url.as_str(), "mailto:rms@example.com");
2158 /// assert!(result.is_err());
2159 /// # Ok(())
2160 /// # }
2161 /// # run().unwrap();
2162 /// ```
2163 ///
2164 #[allow(clippy::result_unit_err)]
2165 pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
2166 if self.cannot_be_a_base() {
2167 return Err(());
2168 }
2169
2170 let address = match address {
2171 IpAddr::V4(address) => Host::Ipv4(address),
2172 IpAddr::V6(address) => Host::Ipv6(address),
2173 };
2174 self.set_host_internal(address, None);
2175 Ok(())
2176 }
2177
2178 /// Change this URL’s password.
2179 ///
2180 /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
2181 ///
2182 /// # Examples
2183 ///
2184 /// ```rust
2185 /// use url::{Url, ParseError};
2186 ///
2187 /// # fn run() -> Result<(), ParseError> {
2188 /// let mut url = Url::parse("mailto:rmz@example.com")?;
2189 /// let result = url.set_password(Some("secret_password"));
2190 /// assert!(result.is_err());
2191 ///
2192 /// let mut url = Url::parse("ftp://user1:secret1@example.com")?;
2193 /// let result = url.set_password(Some("secret_password"));
2194 /// assert_eq!(url.password(), Some("secret_password"));
2195 ///
2196 /// let mut url = Url::parse("ftp://user2:@example.com")?;
2197 /// let result = url.set_password(Some("secret2"));
2198 /// assert!(result.is_ok());
2199 /// assert_eq!(url.password(), Some("secret2"));
2200 /// # Ok(())
2201 /// # }
2202 /// # run().unwrap();
2203 /// ```
2204 #[allow(clippy::result_unit_err)]
2205 pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
2206 // has_host implies !cannot_be_a_base
2207 if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
2208 return Err(());
2209 }
2210 let password = password.unwrap_or_default();
2211 if !password.is_empty() {
2212 let host_and_after = self.slice(self.host_start..).to_owned();
2213 self.serialization.truncate(self.username_end as usize);
2214 self.serialization.push(':');
2215 self.serialization
2216 .extend(utf8_percent_encode(password, USERINFO));
2217 self.serialization.push('@');
2218
2219 let old_host_start = self.host_start;
2220 let new_host_start = to_u32(self.serialization.len()).unwrap();
2221 let adjust = |index: &mut u32| {
2222 *index -= old_host_start;
2223 *index += new_host_start;
2224 };
2225 self.host_start = new_host_start;
2226 adjust(&mut self.host_end);
2227 adjust(&mut self.path_start);
2228 if let Some(ref mut index) = self.query_start {
2229 adjust(index)
2230 }
2231 if let Some(ref mut index) = self.fragment_start {
2232 adjust(index)
2233 }
2234
2235 self.serialization.push_str(&host_and_after);
2236 } else if self.byte_at(self.username_end) == b':' {
2237 // If there is a password to remove
2238 let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
2239 debug_assert!(has_username_or_password);
2240 let username_start = self.scheme_end + 3;
2241 let empty_username = username_start == self.username_end;
2242 let start = self.username_end; // Remove the ':'
2243 let end = if empty_username {
2244 self.host_start // Remove the '@' as well
2245 } else {
2246 self.host_start - 1 // Keep the '@' to separate the username from the host
2247 };
2248 self.serialization.drain(start as usize..end as usize);
2249 let offset = end - start;
2250 self.host_start -= offset;
2251 self.host_end -= offset;
2252 self.path_start -= offset;
2253 if let Some(ref mut index) = self.query_start {
2254 *index -= offset
2255 }
2256 if let Some(ref mut index) = self.fragment_start {
2257 *index -= offset
2258 }
2259 }
2260 Ok(())
2261 }
2262
2263 /// Change this URL’s username.
2264 ///
2265 /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
2266 /// # Examples
2267 ///
2268 /// Cannot setup username from mailto(cannot-be-base)
2269 ///
2270 /// ```rust
2271 /// use url::{Url, ParseError};
2272 ///
2273 /// # fn run() -> Result<(), ParseError> {
2274 /// let mut url = Url::parse("mailto:rmz@example.com")?;
2275 /// let result = url.set_username("user1");
2276 /// assert_eq!(url.as_str(), "mailto:rmz@example.com");
2277 /// assert!(result.is_err());
2278 /// # Ok(())
2279 /// # }
2280 /// # run().unwrap();
2281 /// ```
2282 ///
2283 /// Setup username to user1
2284 ///
2285 /// ```rust
2286 /// use url::{Url, ParseError};
2287 ///
2288 /// # fn run() -> Result<(), ParseError> {
2289 /// let mut url = Url::parse("ftp://:secre1@example.com/")?;
2290 /// let result = url.set_username("user1");
2291 /// assert!(result.is_ok());
2292 /// assert_eq!(url.username(), "user1");
2293 /// assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
2294 /// # Ok(())
2295 /// # }
2296 /// # run().unwrap();
2297 /// ```
2298 #[allow(clippy::result_unit_err)]
2299 pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
2300 // has_host implies !cannot_be_a_base
2301 if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
2302 return Err(());
2303 }
2304 let username_start = self.scheme_end + 3;
2305 debug_assert!(self.slice(self.scheme_end..username_start) == "://");
2306 if self.slice(username_start..self.username_end) == username {
2307 return Ok(());
2308 }
2309 let after_username = self.slice(self.username_end..).to_owned();
2310 self.serialization.truncate(username_start as usize);
2311 self.serialization
2312 .extend(utf8_percent_encode(username, USERINFO));
2313
2314 let mut removed_bytes = self.username_end;
2315 self.username_end = to_u32(self.serialization.len()).unwrap();
2316 let mut added_bytes = self.username_end;
2317
2318 let new_username_is_empty = self.username_end == username_start;
2319 match (new_username_is_empty, after_username.chars().next()) {
2320 (true, Some('@')) => {
2321 removed_bytes += 1;
2322 self.serialization.push_str(&after_username[1..]);
2323 }
2324 (false, Some('@')) | (_, Some(':')) | (true, _) => {
2325 self.serialization.push_str(&after_username);
2326 }
2327 (false, _) => {
2328 added_bytes += 1;
2329 self.serialization.push('@');
2330 self.serialization.push_str(&after_username);
2331 }
2332 }
2333
2334 let adjust = |index: &mut u32| {
2335 *index -= removed_bytes;
2336 *index += added_bytes;
2337 };
2338 adjust(&mut self.host_start);
2339 adjust(&mut self.host_end);
2340 adjust(&mut self.path_start);
2341 if let Some(ref mut index) = self.query_start {
2342 adjust(index)
2343 }
2344 if let Some(ref mut index) = self.fragment_start {
2345 adjust(index)
2346 }
2347 Ok(())
2348 }
2349
2350 /// Change this URL’s scheme.
2351 ///
2352 /// Do nothing and return `Err` under the following circumstances:
2353 ///
2354 /// * If the new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
2355 /// * If this URL is cannot-be-a-base and the new scheme is one of
2356 /// `http`, `https`, `ws`, `wss`, `ftp` or `file`
2357 /// * If either the old or new scheme is a special scheme
2358 /// (`http`, `https`, `ws`, `wss`, `ftp` or `file`) and the other is not
2359 /// * If the new scheme is `file` and this URL includes credentials
2360 /// or has a non-null port
2361 /// * If this URL's scheme is `file` and its host is empty or null
2362 ///
2363 /// See also [the URL specification's section on legal scheme state
2364 /// overrides](https://url.spec.whatwg.org/#scheme-state).
2365 ///
2366 /// # Examples
2367 ///
2368 /// Change the URL’s scheme from `https` to `http`:
2369 ///
2370 /// ```
2371 /// use url::Url;
2372 /// # use url::ParseError;
2373 ///
2374 /// # fn run() -> Result<(), ParseError> {
2375 /// let mut url = Url::parse("https://example.net")?;
2376 /// let result = url.set_scheme("http");
2377 /// assert_eq!(url.as_str(), "http://example.net/");
2378 /// assert!(result.is_ok());
2379 /// # Ok(())
2380 /// # }
2381 /// # run().unwrap();
2382 /// ```
2383 /// Change the URL’s scheme from `foo` to `bar`:
2384 ///
2385 /// ```
2386 /// use url::Url;
2387 /// # use url::ParseError;
2388 ///
2389 /// # fn run() -> Result<(), ParseError> {
2390 /// let mut url = Url::parse("foo://example.net")?;
2391 /// let result = url.set_scheme("bar");
2392 /// assert_eq!(url.as_str(), "bar://example.net");
2393 /// assert!(result.is_ok());
2394 /// # Ok(())
2395 /// # }
2396 /// # run().unwrap();
2397 /// ```
2398 ///
2399 /// Cannot change URL’s scheme from `https` to `foõ`:
2400 ///
2401 /// ```
2402 /// use url::Url;
2403 /// # use url::ParseError;
2404 ///
2405 /// # fn run() -> Result<(), ParseError> {
2406 /// let mut url = Url::parse("https://example.net")?;
2407 /// let result = url.set_scheme("foõ");
2408 /// assert_eq!(url.as_str(), "https://example.net/");
2409 /// assert!(result.is_err());
2410 /// # Ok(())
2411 /// # }
2412 /// # run().unwrap();
2413 /// ```
2414 ///
2415 /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
2416 ///
2417 /// ```
2418 /// use url::Url;
2419 /// # use url::ParseError;
2420 ///
2421 /// # fn run() -> Result<(), ParseError> {
2422 /// let mut url = Url::parse("mailto:rms@example.net")?;
2423 /// let result = url.set_scheme("https");
2424 /// assert_eq!(url.as_str(), "mailto:rms@example.net");
2425 /// assert!(result.is_err());
2426 /// # Ok(())
2427 /// # }
2428 /// # run().unwrap();
2429 /// ```
2430 /// Cannot change the URL’s scheme from `foo` to `https`:
2431 ///
2432 /// ```
2433 /// use url::Url;
2434 /// # use url::ParseError;
2435 ///
2436 /// # fn run() -> Result<(), ParseError> {
2437 /// let mut url = Url::parse("foo://example.net")?;
2438 /// let result = url.set_scheme("https");
2439 /// assert_eq!(url.as_str(), "foo://example.net");
2440 /// assert!(result.is_err());
2441 /// # Ok(())
2442 /// # }
2443 /// # run().unwrap();
2444 /// ```
2445 /// Cannot change the URL’s scheme from `http` to `foo`:
2446 ///
2447 /// ```
2448 /// use url::Url;
2449 /// # use url::ParseError;
2450 ///
2451 /// # fn run() -> Result<(), ParseError> {
2452 /// let mut url = Url::parse("http://example.net")?;
2453 /// let result = url.set_scheme("foo");
2454 /// assert_eq!(url.as_str(), "http://example.net/");
2455 /// assert!(result.is_err());
2456 /// # Ok(())
2457 /// # }
2458 /// # run().unwrap();
2459 /// ```
2460 #[allow(clippy::result_unit_err, clippy::suspicious_operation_groupings)]
2461 pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
2462 let mut parser = Parser::for_setter(String::new());
2463 let remaining = parser.parse_scheme(parser::Input::new_no_trim(scheme))?;
2464 let new_scheme_type = SchemeType::from(&parser.serialization);
2465 let old_scheme_type = SchemeType::from(self.scheme());
2466 // If url’s scheme is a special scheme and buffer is not a special scheme, then return.
2467 if (new_scheme_type.is_special() && !old_scheme_type.is_special()) ||
2468 // If url’s scheme is not a special scheme and buffer is a special scheme, then return.
2469 (!new_scheme_type.is_special() && old_scheme_type.is_special()) ||
2470 // If url includes credentials or has a non-null port, and buffer is "file", then return.
2471 // If url’s scheme is "file" and its host is an empty host or null, then return.
2472 (new_scheme_type.is_file() && self.has_authority())
2473 {
2474 return Err(());
2475 }
2476
2477 if !remaining.is_empty() || (!self.has_host() && new_scheme_type.is_special()) {
2478 return Err(());
2479 }
2480 let old_scheme_end = self.scheme_end;
2481 let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
2482 let adjust = |index: &mut u32| {
2483 *index -= old_scheme_end;
2484 *index += new_scheme_end;
2485 };
2486
2487 self.scheme_end = new_scheme_end;
2488 adjust(&mut self.username_end);
2489 adjust(&mut self.host_start);
2490 adjust(&mut self.host_end);
2491 adjust(&mut self.path_start);
2492 if let Some(ref mut index) = self.query_start {
2493 adjust(index)
2494 }
2495 if let Some(ref mut index) = self.fragment_start {
2496 adjust(index)
2497 }
2498
2499 parser.serialization.push_str(self.slice(old_scheme_end..));
2500 self.serialization = parser.serialization;
2501
2502 // Update the port so it can be removed
2503 // If it is the scheme's default
2504 // we don't mind it silently failing
2505 // if there was no port in the first place
2506 let previous_port = self.port();
2507 let _ = self.set_port(previous_port);
2508
2509 Ok(())
2510 }
2511
2512 /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
2513 ///
2514 /// This returns `Err` if the given path is not absolute or,
2515 /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
2516 ///
2517 /// # Examples
2518 ///
2519 /// On Unix-like platforms:
2520 ///
2521 /// ```
2522 /// # if cfg!(unix) {
2523 /// use url::Url;
2524 ///
2525 /// # fn run() -> Result<(), ()> {
2526 /// let url = Url::from_file_path("/tmp/foo.txt")?;
2527 /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
2528 ///
2529 /// let url = Url::from_file_path("../foo.txt");
2530 /// assert!(url.is_err());
2531 ///
2532 /// let url = Url::from_file_path("https://google.com/");
2533 /// assert!(url.is_err());
2534 /// # Ok(())
2535 /// # }
2536 /// # run().unwrap();
2537 /// # }
2538 /// ```
2539 ///
2540 /// This method is only available if the `std` Cargo feature is enabled.
2541 #[cfg(all(
2542 feature = "std",
2543 any(
2544 unix,
2545 windows,
2546 target_os = "redox",
2547 target_os = "wasi",
2548 target_os = "hermit"
2549 )
2550 ))]
2551 #[allow(clippy::result_unit_err)]
2552 pub fn from_file_path<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ()> {
2553 let mut serialization = "file://".to_owned();
2554 let host_start = serialization.len() as u32;
2555 let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
2556 Ok(Self {
2557 serialization,
2558 scheme_end: "file".len() as u32,
2559 username_end: host_start,
2560 host_start,
2561 host_end,
2562 host,
2563 port: None,
2564 path_start: host_end,
2565 query_start: None,
2566 fragment_start: None,
2567 })
2568 }
2569
2570 /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
2571 ///
2572 /// This returns `Err` if the given path is not absolute or,
2573 /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
2574 ///
2575 /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
2576 /// so that the entire path is considered when using this URL as a base URL.
2577 ///
2578 /// For example:
2579 ///
2580 /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
2581 /// as the base URL is `file:///var/www/index.html`
2582 /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
2583 /// as the base URL is `file:///var/index.html`, which might not be what was intended.
2584 ///
2585 /// Note that `std::path` does not consider trailing slashes significant
2586 /// and usually does not include them (e.g. in `Path::parent()`).
2587 ///
2588 /// This method is only available if the `std` Cargo feature is enabled.
2589 #[cfg(all(
2590 feature = "std",
2591 any(
2592 unix,
2593 windows,
2594 target_os = "redox",
2595 target_os = "wasi",
2596 target_os = "hermit"
2597 )
2598 ))]
2599 #[allow(clippy::result_unit_err)]
2600 pub fn from_directory_path<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ()> {
2601 let mut url = Self::from_file_path(path)?;
2602 if !url.serialization.ends_with('/') {
2603 url.serialization.push('/')
2604 }
2605 Ok(url)
2606 }
2607
2608 /// Serialize with Serde using the internal representation of the `Url` struct.
2609 ///
2610 /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
2611 /// for speed, compared to the `Deserialize` trait impl.
2612 ///
2613 /// This method is only available if the `serde` Cargo feature is enabled.
2614 #[cfg(feature = "serde")]
2615 #[deny(unused)]
2616 pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2617 where
2618 S: serde::Serializer,
2619 {
2620 use serde::Serialize;
2621 // Destructuring first lets us ensure that adding or removing fields forces this method
2622 // to be updated
2623 let Url {
2624 ref serialization,
2625 ref scheme_end,
2626 ref username_end,
2627 ref host_start,
2628 ref host_end,
2629 ref host,
2630 ref port,
2631 ref path_start,
2632 ref query_start,
2633 ref fragment_start,
2634 } = *self;
2635 (
2636 serialization,
2637 scheme_end,
2638 username_end,
2639 host_start,
2640 host_end,
2641 host,
2642 port,
2643 path_start,
2644 query_start,
2645 fragment_start,
2646 )
2647 .serialize(serializer)
2648 }
2649
2650 /// Serialize with Serde using the internal representation of the `Url` struct.
2651 ///
2652 /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
2653 /// for speed, compared to the `Deserialize` trait impl.
2654 ///
2655 /// This method is only available if the `serde` Cargo feature is enabled.
2656 #[cfg(feature = "serde")]
2657 #[deny(unused)]
2658 pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error>
2659 where
2660 D: serde::Deserializer<'de>,
2661 {
2662 use serde::de::{Deserialize, Error};
2663 let (
2664 serialization,
2665 scheme_end,
2666 username_end,
2667 host_start,
2668 host_end,
2669 host,
2670 port,
2671 path_start,
2672 query_start,
2673 fragment_start,
2674 ) = Deserialize::deserialize(deserializer)?;
2675 let url = Url {
2676 serialization,
2677 scheme_end,
2678 username_end,
2679 host_start,
2680 host_end,
2681 host,
2682 port,
2683 path_start,
2684 query_start,
2685 fragment_start,
2686 };
2687 if cfg!(debug_assertions) {
2688 url.check_invariants().map_err(Error::custom)?
2689 }
2690 Ok(url)
2691 }
2692
2693 /// Assuming the URL is in the `file` scheme or similar,
2694 /// convert its path to an absolute `std::path::Path`.
2695 ///
2696 /// **Note:** This does not actually check the URL’s `scheme`,
2697 /// and may give nonsensical results for other schemes.
2698 /// It is the user’s responsibility to check the URL’s scheme before calling this.
2699 ///
2700 /// ```
2701 /// # use url::Url;
2702 /// # let url = Url::parse("file:///etc/passwd").unwrap();
2703 /// let path = url.to_file_path();
2704 /// ```
2705 ///
2706 /// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
2707 /// `file:` URLs may have a non-local host),
2708 /// or if `Path::new_opt()` returns `None`.
2709 /// (That is, if the percent-decoded path contains a NUL byte or,
2710 /// for a Windows path, is not UTF-8.)
2711 ///
2712 /// This method is only available if the `std` Cargo feature is enabled.
2713 #[inline]
2714 #[cfg(all(
2715 feature = "std",
2716 any(
2717 unix,
2718 windows,
2719 target_os = "redox",
2720 target_os = "wasi",
2721 target_os = "hermit"
2722 )
2723 ))]
2724 #[allow(clippy::result_unit_err)]
2725 pub fn to_file_path(&self) -> Result<PathBuf, ()> {
2726 if let Some(segments) = self.path_segments() {
2727 let host = match self.host() {
2728 None | Some(Host::Domain("localhost")) => None,
2729 Some(_) if cfg!(windows) && self.scheme() == "file" => {
2730 Some(&self.serialization[self.host_start as usize..self.host_end as usize])
2731 }
2732 _ => return Err(()),
2733 };
2734
2735 let str_len = self.as_str().len();
2736 let estimated_capacity = if cfg!(target_os = "redox") {
2737 let scheme_len = self.scheme().len();
2738 let file_scheme_len = "file".len();
2739 // remove only // because it still has file:
2740 if scheme_len < file_scheme_len {
2741 let scheme_diff = file_scheme_len - scheme_len;
2742 (str_len + scheme_diff).saturating_sub(2)
2743 } else {
2744 let scheme_diff = scheme_len - file_scheme_len;
2745 str_len.saturating_sub(scheme_diff + 2)
2746 }
2747 } else if cfg!(windows) {
2748 // remove scheme: - has possible \\ for hostname
2749 str_len.saturating_sub(self.scheme().len() + 1)
2750 } else {
2751 // remove scheme://
2752 str_len.saturating_sub(self.scheme().len() + 3)
2753 };
2754 return file_url_segments_to_pathbuf(estimated_capacity, host, segments);
2755 }
2756 Err(())
2757 }
2758
2759 // Private helper methods:
2760
2761 #[inline]
2762 fn slice<R>(&self, range: R) -> &str
2763 where
2764 R: RangeArg,
2765 {
2766 range.slice_of(&self.serialization)
2767 }
2768
2769 #[inline]
2770 fn byte_at(&self, i: u32) -> u8 {
2771 self.serialization.as_bytes()[i as usize]
2772 }
2773}
2774
2775/// Parse a string as an URL, without a base URL or encoding override.
2776impl str::FromStr for Url {
2777 type Err = ParseError;
2778
2779 #[inline]
2780 fn from_str(input: &str) -> Result<Self, crate::ParseError> {
2781 Self::parse(input)
2782 }
2783}
2784
2785impl<'a> TryFrom<&'a str> for Url {
2786 type Error = ParseError;
2787
2788 fn try_from(s: &'a str) -> Result<Self, Self::Error> {
2789 Self::parse(s)
2790 }
2791}
2792
2793/// Display the serialization of this URL.
2794impl fmt::Display for Url {
2795 #[inline]
2796 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2797 fmt::Display::fmt(&self.serialization, formatter)
2798 }
2799}
2800
2801/// String conversion.
2802impl From<Url> for String {
2803 fn from(value: Url) -> Self {
2804 value.serialization
2805 }
2806}
2807
2808/// Debug the serialization of this URL.
2809impl fmt::Debug for Url {
2810 #[inline]
2811 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2812 formatter
2813 .debug_struct("Url")
2814 .field("scheme", &self.scheme())
2815 .field("cannot_be_a_base", &self.cannot_be_a_base())
2816 .field("username", &self.username())
2817 .field("password", &self.password())
2818 .field("host", &self.host())
2819 .field("port", &self.port())
2820 .field("path", &self.path())
2821 .field("query", &self.query())
2822 .field("fragment", &self.fragment())
2823 .finish()
2824 }
2825}
2826
2827/// URLs compare like their serialization.
2828impl Eq for Url {}
2829
2830/// URLs compare like their serialization.
2831impl PartialEq for Url {
2832 #[inline]
2833 fn eq(&self, other: &Self) -> bool {
2834 self.serialization == other.serialization
2835 }
2836}
2837
2838/// URLs compare like their serialization.
2839impl Ord for Url {
2840 #[inline]
2841 fn cmp(&self, other: &Self) -> cmp::Ordering {
2842 self.serialization.cmp(&other.serialization)
2843 }
2844}
2845
2846/// URLs compare like their serialization.
2847impl PartialOrd for Url {
2848 #[inline]
2849 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2850 Some(self.cmp(other))
2851 }
2852}
2853
2854/// URLs hash like their serialization.
2855impl hash::Hash for Url {
2856 #[inline]
2857 fn hash<H>(&self, state: &mut H)
2858 where
2859 H: hash::Hasher,
2860 {
2861 hash::Hash::hash(&self.serialization, state)
2862 }
2863}
2864
2865/// Return the serialization of this URL.
2866impl AsRef<str> for Url {
2867 #[inline]
2868 fn as_ref(&self) -> &str {
2869 &self.serialization
2870 }
2871}
2872
2873trait RangeArg {
2874 fn slice_of<'a>(&self, s: &'a str) -> &'a str;
2875}
2876
2877impl RangeArg for Range<u32> {
2878 #[inline]
2879 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
2880 &s[self.start as usize..self.end as usize]
2881 }
2882}
2883
2884impl RangeArg for RangeFrom<u32> {
2885 #[inline]
2886 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
2887 &s[self.start as usize..]
2888 }
2889}
2890
2891impl RangeArg for RangeTo<u32> {
2892 #[inline]
2893 fn slice_of<'a>(&self, s: &'a str) -> &'a str {
2894 &s[..self.end as usize]
2895 }
2896}
2897
2898/// Serializes this URL into a `serde` stream.
2899///
2900/// This implementation is only available if the `serde` Cargo feature is enabled.
2901#[cfg(feature = "serde")]
2902impl serde::Serialize for Url {
2903 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2904 where
2905 S: serde::Serializer,
2906 {
2907 serializer.serialize_str(self.as_str())
2908 }
2909}
2910
2911/// Deserializes this URL from a `serde` stream.
2912///
2913/// This implementation is only available if the `serde` Cargo feature is enabled.
2914#[cfg(feature = "serde")]
2915impl<'de> serde::Deserialize<'de> for Url {
2916 fn deserialize<D>(deserializer: D) -> Result<Url, D::Error>
2917 where
2918 D: serde::Deserializer<'de>,
2919 {
2920 use serde::de::{Error, Visitor};
2921
2922 struct UrlVisitor;
2923
2924 impl Visitor<'_> for UrlVisitor {
2925 type Value = Url;
2926
2927 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2928 formatter.write_str("a string representing an URL")
2929 }
2930
2931 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
2932 where
2933 E: Error,
2934 {
2935 Url::parse(s).map_err(|err| Error::custom(format!("{err}: {s:?}")))
2936 }
2937 }
2938
2939 deserializer.deserialize_str(UrlVisitor)
2940 }
2941}
2942
2943#[cfg(all(
2944 feature = "std",
2945 any(unix, target_os = "redox", target_os = "wasi", target_os = "hermit")
2946))]
2947fn path_to_file_url_segments(
2948 path: &Path,
2949 serialization: &mut String,
2950) -> Result<(u32, HostInternal), ()> {
2951 use parser::SPECIAL_PATH_SEGMENT;
2952 use percent_encoding::percent_encode;
2953 #[cfg(target_os = "hermit")]
2954 use std::os::hermit::ffi::OsStrExt;
2955 #[cfg(any(unix, target_os = "redox"))]
2956 use std::os::unix::prelude::OsStrExt;
2957 if !path.is_absolute() {
2958 return Err(());
2959 }
2960 let host_end = to_u32(serialization.len()).unwrap();
2961 let mut empty = true;
2962 // skip the root component
2963 for component in path.components().skip(1) {
2964 empty = false;
2965 serialization.push('/');
2966 #[cfg(not(target_os = "wasi"))]
2967 serialization.extend(percent_encode(
2968 component.as_os_str().as_bytes(),
2969 SPECIAL_PATH_SEGMENT,
2970 ));
2971 #[cfg(target_os = "wasi")]
2972 serialization.extend(percent_encode(
2973 component.as_os_str().to_string_lossy().as_bytes(),
2974 SPECIAL_PATH_SEGMENT,
2975 ));
2976 }
2977 if empty {
2978 // An URL’s path must not be empty.
2979 serialization.push('/');
2980 }
2981 Ok((host_end, HostInternal::None))
2982}
2983
2984#[cfg(all(feature = "std", windows))]
2985fn path_to_file_url_segments(
2986 path: &Path,
2987 serialization: &mut String,
2988) -> Result<(u32, HostInternal), ()> {
2989 path_to_file_url_segments_windows(path, serialization)
2990}
2991
2992// Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
2993#[cfg(feature = "std")]
2994#[cfg_attr(not(windows), allow(dead_code))]
2995fn path_to_file_url_segments_windows(
2996 path: &Path,
2997 serialization: &mut String,
2998) -> Result<(u32, HostInternal), ()> {
2999 use crate::parser::PATH_SEGMENT;
3000 use percent_encoding::percent_encode;
3001 use std::path::{Component, Prefix};
3002 if !path.is_absolute() {
3003 return Err(());
3004 }
3005 let mut components = path.components();
3006
3007 let host_start = serialization.len() + 1;
3008 let host_end;
3009 let host_internal;
3010
3011 match components.next() {
3012 Some(Component::Prefix(ref p)) => match p.kind() {
3013 Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
3014 host_end = to_u32(serialization.len()).unwrap();
3015 host_internal = HostInternal::None;
3016 serialization.push('/');
3017 serialization.push(letter as char);
3018 serialization.push(':');
3019 }
3020 Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
3021 let host = Host::parse_cow(server.to_str().ok_or(())?.into()).map_err(|_| ())?;
3022 write!(serialization, "{host}").unwrap();
3023 host_end = to_u32(serialization.len()).unwrap();
3024 host_internal = host.into();
3025 serialization.push('/');
3026 let share = share.to_str().ok_or(())?;
3027 serialization.extend(percent_encode(share.as_bytes(), PATH_SEGMENT));
3028 }
3029 _ => return Err(()),
3030 },
3031 _ => return Err(()),
3032 }
3033
3034 let mut path_only_has_prefix = true;
3035 for component in components {
3036 if component == Component::RootDir {
3037 continue;
3038 }
3039
3040 path_only_has_prefix = false;
3041 // FIXME: somehow work with non-unicode?
3042 let component = component.as_os_str().to_str().ok_or(())?;
3043
3044 serialization.push('/');
3045 serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT));
3046 }
3047
3048 // A windows drive letter must end with a slash.
3049 if serialization.len() > host_start
3050 && parser::is_windows_drive_letter(&serialization[host_start..])
3051 && path_only_has_prefix
3052 {
3053 serialization.push('/');
3054 }
3055
3056 Ok((host_end, host_internal))
3057}
3058
3059#[cfg(all(
3060 feature = "std",
3061 any(unix, target_os = "redox", target_os = "wasi", target_os = "hermit")
3062))]
3063fn file_url_segments_to_pathbuf(
3064 estimated_capacity: usize,
3065 host: Option<&str>,
3066 segments: str::Split<'_, char>,
3067) -> Result<PathBuf, ()> {
3068 use alloc::vec::Vec;
3069 use percent_encoding::percent_decode;
3070 #[cfg(not(target_os = "wasi"))]
3071 use std::ffi::OsStr;
3072 #[cfg(target_os = "hermit")]
3073 use std::os::hermit::ffi::OsStrExt;
3074 #[cfg(any(unix, target_os = "redox"))]
3075 use std::os::unix::prelude::OsStrExt;
3076
3077 if host.is_some() {
3078 return Err(());
3079 }
3080
3081 let mut bytes = Vec::new();
3082 bytes.try_reserve(estimated_capacity).map_err(|_| ())?;
3083 if cfg!(target_os = "redox") {
3084 bytes.extend(b"file:");
3085 }
3086
3087 for segment in segments {
3088 bytes.push(b'/');
3089 bytes.extend(percent_decode(segment.as_bytes()));
3090 }
3091
3092 // A windows drive letter must end with a slash.
3093 if bytes.len() > 2
3094 && bytes[bytes.len() - 2].is_ascii_alphabetic()
3095 && matches!(bytes[bytes.len() - 1], b':' | b'|')
3096 {
3097 bytes.push(b'/');
3098 }
3099
3100 #[cfg(not(target_os = "wasi"))]
3101 let path = PathBuf::from(OsStr::from_bytes(&bytes));
3102 #[cfg(target_os = "wasi")]
3103 let path = String::from_utf8(bytes)
3104 .map(|path| PathBuf::from(path))
3105 .map_err(|_| ())?;
3106
3107 debug_assert!(
3108 path.is_absolute(),
3109 "to_file_path() failed to produce an absolute Path"
3110 );
3111
3112 Ok(path)
3113}
3114
3115#[cfg(all(feature = "std", windows))]
3116fn file_url_segments_to_pathbuf(
3117 estimated_capacity: usize,
3118 host: Option<&str>,
3119 segments: str::Split<char>,
3120) -> Result<PathBuf, ()> {
3121 file_url_segments_to_pathbuf_windows(estimated_capacity, host, segments)
3122}
3123
3124// Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
3125#[cfg(feature = "std")]
3126#[cfg_attr(not(windows), allow(dead_code))]
3127fn file_url_segments_to_pathbuf_windows(
3128 estimated_capacity: usize,
3129 host: Option<&str>,
3130 mut segments: str::Split<'_, char>,
3131) -> Result<PathBuf, ()> {
3132 use percent_encoding::percent_decode_str;
3133 let mut string = String::new();
3134 string.try_reserve(estimated_capacity).map_err(|_| ())?;
3135 if let Some(host) = host {
3136 string.push_str(r"\\");
3137 string.push_str(host);
3138 } else {
3139 let first = segments.next().ok_or(())?;
3140
3141 match first.len() {
3142 2 => {
3143 if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
3144 return Err(());
3145 }
3146
3147 string.push_str(first);
3148 }
3149
3150 4 => {
3151 if !first.starts_with(parser::ascii_alpha) {
3152 return Err(());
3153 }
3154 let bytes = first.as_bytes();
3155 if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
3156 return Err(());
3157 }
3158
3159 string.push_str(&first[0..1]);
3160 string.push(':');
3161 }
3162
3163 _ => return Err(()),
3164 }
3165 };
3166
3167 for segment in segments {
3168 string.push('\\');
3169
3170 // Currently non-unicode windows paths cannot be represented
3171 match percent_decode_str(segment).decode_utf8() {
3172 Ok(s) => string.push_str(&s),
3173 Err(..) => return Err(()),
3174 }
3175 }
3176 // ensure our estimated capacity was good
3177 if cfg!(test) {
3178 debug_assert!(
3179 string.len() <= estimated_capacity,
3180 "len: {}, capacity: {}",
3181 string.len(),
3182 estimated_capacity
3183 );
3184 }
3185 let path = PathBuf::from(string);
3186 debug_assert!(
3187 path.is_absolute(),
3188 "to_file_path() failed to produce an absolute Path"
3189 );
3190 Ok(path)
3191}
3192
3193/// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
3194#[derive(Debug)]
3195pub struct UrlQuery<'a> {
3196 url: Option<&'a mut Url>,
3197 fragment: Option<String>,
3198}
3199
3200// `as_mut_string` string here exposes the internal serialization of an `Url`,
3201// which should not be exposed to users.
3202// We achieve that by not giving users direct access to `UrlQuery`:
3203// * Its fields are private
3204// (and so can not be constructed with struct literal syntax outside of this crate),
3205// * It has no constructor
3206// * It is only visible (on the type level) to users in the return type of
3207// `Url::query_pairs_mut` which is `Serializer<UrlQuery>`
3208// * `Serializer` keeps its target in a private field
3209// * Unlike in other `Target` impls, `UrlQuery::finished` does not return `Self`.
3210impl<'a> form_urlencoded::Target for UrlQuery<'a> {
3211 fn as_mut_string(&mut self) -> &mut String {
3212 &mut self.url.as_mut().unwrap().serialization
3213 }
3214
3215 fn finish(mut self) -> &'a mut Url {
3216 let url = self.url.take().unwrap();
3217 url.restore_already_parsed_fragment(self.fragment.take());
3218 url
3219 }
3220
3221 type Finished = &'a mut Url;
3222}
3223
3224impl Drop for UrlQuery<'_> {
3225 fn drop(&mut self) {
3226 if let Some(url) = self.url.take() {
3227 url.restore_already_parsed_fragment(self.fragment.take())
3228 }
3229 }
3230}