display_as/
url.rs

1//! [Format] as URL, with escaping using percent encoding.
2
3use super::*;
4use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
5
6/// [Format] as URL.
7#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
8pub struct URL;
9impl Format for URL {
10    fn escape(f: &mut Formatter, s: &str) -> Result<(), Error> {
11        f.write_str(&utf8_percent_encode(s, DEFAULT_ENCODE_SET).to_string())
12    }
13    /// The MIME type for URL is [mime::TEXT_URL_UTF_8].
14    fn mime() -> mime::Mime {
15        return "text/x-url".parse().unwrap();
16    }
17    fn this_format() -> Self {
18        URL
19    }
20}
21
22display_integers_as!(URL);
23display_floats_as!(URL, "e", "", 1, None);
24
25#[test]
26fn escaping() {
27    assert_eq!(&format_as!(URL, ("&")).into_string(), "&");
28    assert_eq!(
29        &format_as!(URL, ("hello &>this is cool")).into_string(),
30        "hello%20&%3Ethis%20is%20cool"
31    );
32    assert_eq!(
33        &format_as!(URL, ("hello &>this is 'cool")).into_string(),
34        "hello%20&%3Ethis%20is%20\'cool"
35    );
36}