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