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
55
56
57
58
59
60
61
62
63
64
65
use std::ascii::AsciiExt;
use std::borrow::Cow::{self, Borrowed, Owned};
use external_idna;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Error;
pub fn to_ascii(s: &str) -> Result<Cow<str>, Error> {
if s.is_ascii() {
Ok(Borrowed(s))
} else {
external_idna::domain_to_ascii(s)
.map(Owned)
.map_err(|_| Error)
}
}
pub fn to_unicode(s: &str) -> Result<Cow<str>, Error> {
let is_unicode = s.split('.').any(|s| s.starts_with("xn--"));
if is_unicode {
match external_idna::domain_to_unicode(s) {
(s, Ok(_)) => Ok(Owned(s)),
(_, Err(_)) => Err(Error)
}
} else {
Ok(Borrowed(s))
}
}
#[cfg(test)]
mod test {
use super::{to_ascii, to_unicode};
static SAMPLE_HOSTS: &'static [(&'static str, &'static str)] = &[
("bücher.de.", "xn--bcher-kva.de."),
("ουτοπία.δπθ.gr.", "xn--kxae4bafwg.xn--pxaix.gr."),
("bücher.de", "xn--bcher-kva.de"),
("ουτοπία.δπθ.gr", "xn--kxae4bafwg.xn--pxaix.gr"),
];
#[test]
fn test_hosts() {
for &(uni, ascii) in SAMPLE_HOSTS {
assert_eq!(to_ascii(uni).unwrap(), ascii);
assert_eq!(to_unicode(ascii).unwrap(), uni);
assert_eq!(to_ascii(ascii).unwrap(), ascii);
assert_eq!(to_unicode(uni).unwrap(), uni);
}
}
}