punycode.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 crate::test::TestFn;
  9. use idna::punycode::{decode, encode_str};
  10. use serde_json::map::Map;
  11. use serde_json::Value;
  12. use std::str::FromStr;
  13. fn one_test(decoded: &str, encoded: &str) {
  14. match decode(encoded) {
  15. None => panic!("Decoding {} failed.", encoded),
  16. Some(result) => {
  17. let result = result.into_iter().collect::<String>();
  18. assert!(
  19. result == decoded,
  20. "Incorrect decoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  21. encoded,
  22. result,
  23. decoded
  24. )
  25. }
  26. }
  27. match encode_str(decoded) {
  28. None => panic!("Encoding {} failed.", decoded),
  29. Some(result) => assert!(
  30. result == encoded,
  31. "Incorrect encoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
  32. decoded,
  33. result,
  34. encoded
  35. ),
  36. }
  37. }
  38. fn get_string<'a>(map: &'a Map<String, Value>, key: &str) -> &'a str {
  39. match map.get(&key.to_string()) {
  40. Some(Value::String(s)) => s,
  41. None => "",
  42. _ => panic!(),
  43. }
  44. }
  45. pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
  46. match Value::from_str(include_str!("punycode_tests.json")) {
  47. Ok(Value::Array(tests)) => {
  48. for (i, test) in tests.into_iter().enumerate() {
  49. match test {
  50. Value::Object(o) => {
  51. let test_name = {
  52. let desc = get_string(&o, "description");
  53. if desc.is_empty() {
  54. format!("Punycode {}", i + 1)
  55. } else {
  56. format!("Punycode {}: {}", i + 1, desc)
  57. }
  58. };
  59. add_test(
  60. test_name,
  61. TestFn::DynTestFn(Box::new(move || {
  62. one_test(get_string(&o, "decoded"), get_string(&o, "encoded"))
  63. })),
  64. )
  65. }
  66. _ => panic!(),
  67. }
  68. }
  69. }
  70. other => panic!("{:?}", other),
  71. }
  72. }