1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
pub use super::super::validators::http_ftp_url::HttpFtpUrlLocalableWithProtocol as URL;
use super::*;

use std::fmt::Write;
use idna::domain_to_ascii;
use validators::host::Host;

impl Value for URL {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        f.write_str(self.get_protocol())?;

        if self.is_absolute() {
            f.write_str("://")?;
        } else {
            f.write_char(':')?;
        }

        let host = self.get_host();

        if let Host::Domain(domain) = host {
            match domain_to_ascii(domain.get_full_domain_without_port()) {
                Ok(domain_without_port) => {
                    f.write_str(&domain_without_port)?;
                }
                Err(_) => {
                    return Err(fmt::Error);
                }
            }

            if let Some(port) = domain.get_port() {
                f.write_char(':')?;
                f.write_fmt(format_args!("{}", port))?;
            }
        } else {
            f.write_str(host.get_full_host())?;
        }

        if let Some(path) = self.get_path() {
            f.write_str(&percent_encoding::utf8_percent_encode(path, percent_encoding::DEFAULT_ENCODE_SET).to_string())?;
        }

        if let Some(query) = self.get_query() {
            f.write_char('?')?;
            f.write_str(&percent_encoding::utf8_percent_encode(query, percent_encoding::QUERY_ENCODE_SET).to_string())?;
        }

        if let Some(fragment) = self.get_fragment() {
            f.write_char('#')?;
            f.write_str(&percent_encoding::utf8_percent_encode(fragment, percent_encoding::QUERY_ENCODE_SET).to_string())?;
        }

        Ok(())
    }
}