1use address::{DomainRef, HostRef};
2
3use crate::WebUrl;
4
5impl WebUrl {
6 pub fn host(&self) -> HostRef<'_> {
10 if let Some(ip) = self.ip {
11 HostRef::Address(ip)
12 } else {
13 HostRef::Name(unsafe { DomainRef::new(self.host_str()) })
14 }
15 }
16
17 fn host_str(&self) -> &str {
23 let start: usize = (self.scheme_len + 3) as usize;
24 let end: usize = self.host_end as usize;
25 &self.url[start..end]
26 }
27}
28
29#[cfg(test)]
30mod tests {
31 use address::{HostRef, IPv4Address, IPv6Address};
32
33 use crate::WebUrl;
34 use std::error::Error;
35 use std::str::FromStr;
36
37 #[test]
38 fn host_domain() -> Result<(), Box<dyn Error>> {
39 let url = WebUrl::from_str("https://example.com")?;
40 match url.host() {
41 HostRef::Name(domain) => assert_eq!(domain.name(), "example.com"),
42 _ => panic!("expected domain"),
43 }
44 Ok(())
45 }
46
47 #[test]
48 fn host_domain_uppercase() -> Result<(), Box<dyn Error>> {
49 let url = WebUrl::from_str("https://EXAMPLE.COM")?;
50 match url.host() {
51 HostRef::Name(domain) => assert_eq!(domain.name(), "example.com"),
52 _ => panic!("expected domain"),
53 }
54 Ok(())
55 }
56
57 #[test]
58 fn host_ipv4() -> Result<(), Box<dyn Error>> {
59 let url = WebUrl::from_str("https://127.0.0.1")?;
60 match url.host() {
61 HostRef::Address(ip) => assert_eq!(ip, IPv4Address::LOCALHOST.to_ip()),
62 _ => panic!("expected ip address"),
63 }
64 Ok(())
65 }
66
67 #[test]
68 fn host_ipv6() -> Result<(), Box<dyn Error>> {
69 let url = WebUrl::from_str("https://[::1]")?;
70 match url.host() {
71 HostRef::Address(ip) => assert_eq!(ip, IPv6Address::LOCALHOST.to_ip()),
72 _ => panic!("expected ip address"),
73 }
74 Ok(())
75 }
76}