Skip to content

Commit 8b3ee5a

Browse files
committed
url: add the authority method
Signed-off-by: Alejandro Martinez Ruiz <alex@flawedcode.org>
1 parent 359bc90 commit 8b3ee5a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

url/src/lib.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,8 @@ impl Url {
792792
/// URLs that do *not* are either path-only like `unix:/run/foo.socket`
793793
/// or cannot-be-a-base like `data:text/plain,Stuff`.
794794
///
795+
/// See also the `authority` method.
796+
///
795797
/// # Examples
796798
///
797799
/// ```
@@ -817,6 +819,47 @@ impl Url {
817819
self.slice(self.scheme_end..).starts_with("://")
818820
}
819821

822+
/// Return the authority of this URL as an ASCII string.
823+
///
824+
/// Non-ASCII domains are punycode-encoded per IDNA if this is the host
825+
/// of a special URL, or percent encoded for non-special URLs.
826+
/// IPv6 addresses are given between `[` and `]` brackets.
827+
/// Ports are omitted if they match the well known port of a special URL.
828+
///
829+
/// Username and password are percent-encoded.
830+
///
831+
/// See also the `has_authority` method.
832+
///
833+
/// # Examples
834+
///
835+
/// ```
836+
/// use url::Url;
837+
/// # use url::ParseError;
838+
///
839+
/// # fn run() -> Result<(), ParseError> {
840+
/// let url = Url::parse("unix:/run/foo.socket")?;
841+
/// assert_eq!(url.authority(), "");
842+
/// let url = Url::parse("file:///tmp/foo")?;
843+
/// assert_eq!(url.authority(), "");
844+
/// let url = Url::parse("https://user:password@example.com/tmp/foo")?;
845+
/// assert_eq!(url.authority(), "user:password@example.com");
846+
/// let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?;
847+
/// assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667");
848+
/// let url = Url::parse("http://àlex.рф.example.com:80/foo")?;
849+
/// assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com");
850+
/// # Ok(())
851+
/// # }
852+
/// # run().unwrap();
853+
/// ```
854+
pub fn authority(&self) -> &str {
855+
let scheme_separator_len = "://".len() as u32;
856+
if self.has_authority() && self.path_start > self.scheme_end + scheme_separator_len {
857+
self.slice(self.scheme_end + scheme_separator_len..self.path_start)
858+
} else {
859+
""
860+
}
861+
}
862+
820863
/// Return whether this URL is a cannot-be-a-base URL,
821864
/// meaning that parsing a relative URL string with this URL as the base will return an error.
822865
///

0 commit comments

Comments
 (0)