ada_url/idna.rs
1#[cfg(feature = "std")]
2extern crate std;
3
4#[cfg_attr(not(feature = "std"), allow(unused_imports))]
5use crate::ffi;
6
7#[cfg(feature = "std")]
8use std::string::String;
9
10/// IDNA struct implements the `to_ascii` and `to_unicode` functions from the Unicode Technical
11/// Standard supporting a wide range of systems. It is suitable for URL parsing.
12/// For more information, [read the specification](https://www.unicode.org/reports/tr46/#ToUnicode)
13pub struct Idna {}
14
15impl Idna {
16 /// Process international domains according to the UTS #46 standard.
17 /// Returns empty string if the input is invalid.
18 ///
19 /// For more information, [read the specification](https://www.unicode.org/reports/tr46/#ToUnicode)
20 ///
21 /// ```
22 /// use ada_url::Idna;
23 /// assert_eq!(Idna::unicode("xn--meagefactory-m9a.ca"), "meßagefactory.ca");
24 /// ```
25 #[must_use]
26 #[cfg(feature = "std")]
27 pub fn unicode(input: &str) -> String {
28 unsafe { ffi::ada_idna_to_unicode(input.as_ptr().cast(), input.len()) }.to_string()
29 }
30
31 /// Process international domains according to the UTS #46 standard.
32 /// Returns empty string if the input is invalid.
33 ///
34 /// For more information, [read the specification](https://www.unicode.org/reports/tr46/#ToASCII)
35 ///
36 /// ```
37 /// use ada_url::Idna;
38 /// assert_eq!(Idna::ascii("meßagefactory.ca"), "xn--meagefactory-m9a.ca");
39 /// ```
40 #[must_use]
41 #[cfg(feature = "std")]
42 pub fn ascii(input: &str) -> String {
43 unsafe { ffi::ada_idna_to_ascii(input.as_ptr().cast(), input.len()) }.to_string()
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 #[cfg_attr(not(feature = "std"), allow(unused_imports))]
50 use crate::idna::*;
51
52 #[test]
53 fn unicode_should_work() {
54 #[cfg(feature = "std")]
55 assert_eq!(Idna::unicode("xn--meagefactory-m9a.ca"), "meßagefactory.ca");
56 }
57
58 #[test]
59 fn ascii_should_work() {
60 #[cfg(feature = "std")]
61 assert_eq!(Idna::ascii("meßagefactory.ca"), "xn--meagefactory-m9a.ca");
62 }
63}