punycode.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2013 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. use idna::punycode::{decode, encode_str};
  9. use rustc_serialize::json::{Json, Object};
  10. use test::TestFn;
  11. fn one_test(decoded: &str, encoded: &str) {
  12. match decode(encoded) {
  13. None => panic!("Decoding {} failed.", encoded),
  14. Some(result) => {
  15. let result = result.into_iter().collect::<String>();
  16. assert!(
  17. result == decoded,
  18. format!(
  19. "Incorrect decoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  20. encoded, result, decoded
  21. )
  22. )
  23. }
  24. }
  25. match encode_str(decoded) {
  26. None => panic!("Encoding {} failed.", decoded),
  27. Some(result) => assert!(
  28. result == encoded,
  29. format!(
  30. "Incorrect encoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  31. decoded, result, encoded
  32. )
  33. ),
  34. }
  35. }
  36. fn get_string<'a>(map: &'a Object, key: &str) -> &'a str {
  37. match map.get(&key.to_string()) {
  38. Some(&Json::String(ref s)) => s,
  39. None => "",
  40. _ => panic!(),
  41. }
  42. }
  43. pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
  44. match Json::from_str(include_str!("punycode_tests.json")) {
  45. Ok(Json::Array(tests)) => {
  46. for (i, test) in tests.into_iter().enumerate() {
  47. match test {
  48. Json::Object(o) => {
  49. let test_name = {
  50. let desc = get_string(&o, "description");
  51. if desc.is_empty() {
  52. format!("Punycode {}", i + 1)
  53. } else {
  54. format!("Punycode {}: {}", i + 1, desc)
  55. }
  56. };
  57. add_test(
  58. test_name,
  59. TestFn::dyn_test_fn(move || {
  60. one_test(get_string(&o, "decoded"), get_string(&o, "encoded"))
  61. }),
  62. )
  63. }
  64. _ => panic!(),
  65. }
  66. }
  67. }
  68. other => panic!("{:?}", other),
  69. }
  70. }