idna.rs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 testType = pieces.remove(0);
  23. let original = pieces.remove(0);
  24. let source = unescape(original);
  25. let toUnicode = pieces.remove(0);
  26. let toAscii = 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: testType != "N"
  34. });
  35. let res = result.ok();
  36. if toAscii.starts_with("[") {
  37. //assert!(res == None, "Expected error. result: {} | original: {} | source: {}", res.unwrap(), original, source);
  38. continue;
  39. }
  40. let toAscii = if toAscii.len() > 0 {
  41. toAscii.to_string()
  42. } else {
  43. if toUnicode.len() > 0 {
  44. toUnicode.to_string()
  45. } else {
  46. source.clone()
  47. }
  48. };
  49. assert!(res != None, "Couldn't parse {} ", source);
  50. let output = res.unwrap();
  51. assert!(output == toAscii, "result: {} | expected: {} | original: {} | source: {}", output, toAscii, original, source);
  52. }
  53. }
  54. fn unescape(input: &str) -> String {
  55. let mut output = String::new();
  56. let mut chars = input.chars();
  57. loop {
  58. match chars.next() {
  59. None => return output,
  60. Some(c) =>
  61. if c == '\\' {
  62. match chars.next().unwrap() {
  63. '\\' => output.push('\\'),
  64. 'u' => {
  65. let c1 = chars.next().unwrap().to_digit(16).unwrap();
  66. let c2 = chars.next().unwrap().to_digit(16).unwrap();
  67. let c3 = chars.next().unwrap().to_digit(16).unwrap();
  68. let c4 = chars.next().unwrap().to_digit(16).unwrap();
  69. match char::from_u32((((c1 * 16 + c2) * 16 + c3) * 16 + c4))
  70. {
  71. Some(c) => output.push(c),
  72. None => { output.push_str(&format!("\\u{:X}{:X}{:X}{:X}",c1,c2,c3,c4)); }
  73. };
  74. }
  75. _ => panic!("Invalid test data input"),
  76. }
  77. } else {
  78. output.push(c);
  79. }
  80. }
  81. }
  82. }