punycode.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2013 Simon Sapin.
  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!(result == decoded,
  17. format!("Incorrect decoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  18. encoded, result, decoded))
  19. }
  20. }
  21. match encode_str(decoded) {
  22. None => panic!("Encoding {} failed.", decoded),
  23. Some(result) => {
  24. assert!(result == encoded,
  25. format!("Incorrect encoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  26. decoded, result, encoded))
  27. }
  28. }
  29. }
  30. fn get_string<'a>(map: &'a Object, key: &str) -> &'a str {
  31. match map.get(&key.to_string()) {
  32. Some(&Json::String(ref s)) => s,
  33. None => "",
  34. _ => panic!(),
  35. }
  36. }
  37. pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
  38. match Json::from_str(include_str!("punycode_tests.json")) {
  39. Ok(Json::Array(tests)) => for (i, test) in tests.into_iter().enumerate() {
  40. match test {
  41. Json::Object(o) => {
  42. let test_name = {
  43. let desc = get_string(&o, "description");
  44. if desc.is_empty() {
  45. format!("Punycode {}", i + 1)
  46. } else {
  47. format!("Punycode {}: {}", i + 1, desc)
  48. }
  49. };
  50. add_test(test_name, TestFn::dyn_test_fn(move || one_test(
  51. get_string(&o, "decoded"),
  52. get_string(&o, "encoded"),
  53. )))
  54. }
  55. _ => panic!(),
  56. }
  57. },
  58. other => panic!("{:?}", other)
  59. }
  60. }