idna.rs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. extern crate url;
  2. use std::char;
  3. use url::idna;
  4. #[test]
  5. fn test_uts46() {
  6. // http://www.unicode.org/Public/idna/latest/IdnaTest.txt
  7. for line in include_str!("IdnaTest.txt").lines() {
  8. if line == "" || line.starts_with("#") {
  9. continue
  10. }
  11. // Remove comments
  12. let mut line = match line.find("#") {
  13. Some(index) => &line[0..index],
  14. None => line
  15. };
  16. let mut expected_failure = false;
  17. if line.starts_with("XFAIL") {
  18. expected_failure = true;
  19. line = &line[5..line.len()];
  20. };
  21. let mut pieces = line.split(';').map(|x| x.trim()).collect::<Vec<&str>>();
  22. let test_type = pieces.remove(0);
  23. let original = pieces.remove(0);
  24. let source = unescape(original);
  25. let to_unicode = pieces.remove(0);
  26. let to_ascii = pieces.remove(0);
  27. let _nv8 = pieces.len() > 0;
  28. if expected_failure {
  29. continue;
  30. }
  31. let result = idna::uts46_to_ascii(&source, idna::Uts46Flags {
  32. use_std3_ascii_rules: true,
  33. transitional_processing: test_type != "N",
  34. verify_dns_length: true,
  35. });
  36. let res = result.ok();
  37. if to_ascii.starts_with("[") {
  38. //assert!(res == None, "Expected error. result: {} | original: {} | source: {}", res.unwrap(), original, source);
  39. continue;
  40. }
  41. let to_ascii = if to_ascii.len() > 0 {
  42. to_ascii.to_string()
  43. } else {
  44. if to_unicode.len() > 0 {
  45. to_unicode.to_string()
  46. } else {
  47. source.clone()
  48. }
  49. };
  50. assert!(res != None, "Couldn't parse {} ", source);
  51. let output = res.unwrap();
  52. assert!(output == to_ascii, "result: {} | expected: {} | original: {} | source: {}", output, to_ascii, original, source);
  53. }
  54. }
  55. fn unescape(input: &str) -> String {
  56. let mut output = String::new();
  57. let mut chars = input.chars();
  58. loop {
  59. match chars.next() {
  60. None => return output,
  61. Some(c) =>
  62. if c == '\\' {
  63. match chars.next().unwrap() {
  64. '\\' => output.push('\\'),
  65. 'u' => {
  66. let c1 = chars.next().unwrap().to_digit(16).unwrap();
  67. let c2 = chars.next().unwrap().to_digit(16).unwrap();
  68. let c3 = chars.next().unwrap().to_digit(16).unwrap();
  69. let c4 = chars.next().unwrap().to_digit(16).unwrap();
  70. match char::from_u32((((c1 * 16 + c2) * 16 + c3) * 16 + c4))
  71. {
  72. Some(c) => output.push(c),
  73. None => { output.push_str(&format!("\\u{:X}{:X}{:X}{:X}",c1,c2,c3,c4)); }
  74. };
  75. }
  76. _ => panic!("Invalid test data input"),
  77. }
  78. } else {
  79. output.push(c);
  80. }
  81. }
  82. }
  83. }