punycode.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. //! Punycode ([RFC 3492](http://tools.ietf.org/html/rfc3492)) implementation.
  9. //!
  10. //! Since Punycode fundamentally works on unicode code points,
  11. //! `encode` and `decode` take and return slices and vectors of `char`.
  12. //! `encode_str` and `decode_to_string` provide convenience wrappers
  13. //! that convert from and to Rust’s UTF-8 based `str` and `String` types.
  14. use std::u32;
  15. use std::char;
  16. // Bootstring parameters for Punycode
  17. static BASE: u32 = 36;
  18. static T_MIN: u32 = 1;
  19. static T_MAX: u32 = 26;
  20. static SKEW: u32 = 38;
  21. static DAMP: u32 = 700;
  22. static INITIAL_BIAS: u32 = 72;
  23. static INITIAL_N: u32 = 0x80;
  24. static DELIMITER: char = '-';
  25. #[inline]
  26. fn adapt(mut delta: u32, num_points: u32, first_time: bool) -> u32 {
  27. delta /= if first_time { DAMP } else { 2 };
  28. delta += delta / num_points;
  29. let mut k = 0;
  30. while delta > ((BASE - T_MIN) * T_MAX) / 2 {
  31. delta /= BASE - T_MIN;
  32. k += BASE;
  33. }
  34. k + (((BASE - T_MIN + 1) * delta) / (delta + SKEW))
  35. }
  36. /// Convert Punycode to an Unicode `String`.
  37. ///
  38. /// This is a convenience wrapper around `decode`.
  39. #[inline]
  40. pub fn decode_to_string(input: &str) -> Option<String> {
  41. decode(input).map(|chars| String::from_chars(chars.as_slice()))
  42. }
  43. /// Convert Punycode to Unicode.
  44. ///
  45. /// Return None on malformed input or overflow.
  46. /// Overflow can only happen on inputs that take more than
  47. /// 63 encoded bytes, the DNS limit on domain name labels.
  48. pub fn decode(input: &str) -> Option<Vec<char>> {
  49. // Handle "basic" (ASCII) code points.
  50. // They are encoded as-is befor the last delimiter, if any.
  51. let (mut output, input) = match input.rfind(DELIMITER) {
  52. None => (Vec::new(), input),
  53. Some(position) => (
  54. input.slice_to(position).chars().collect(),
  55. if position > 0 { input.slice_from(position + 1) } else { input }
  56. )
  57. };
  58. let mut code_point = INITIAL_N;
  59. let mut bias = INITIAL_BIAS;
  60. let mut i = 0;
  61. let mut iter = input.bytes();
  62. loop {
  63. let previous_i = i;
  64. let mut weight = 1;
  65. let mut k = BASE;
  66. let mut byte = match iter.next() {
  67. None => break,
  68. Some(byte) => byte,
  69. };
  70. // Decode a generalized variable-length integer into delta,
  71. // which gets added to i.
  72. loop {
  73. let digit = match byte {
  74. byte @ b'0' ... b'9' => byte - b'0' + 26,
  75. byte @ b'A' ... b'Z' => byte - b'A',
  76. byte @ b'a' ... b'z' => byte - b'a',
  77. _ => return None
  78. } as u32;
  79. if digit > (u32::MAX - i) / weight {
  80. return None // Overflow
  81. }
  82. i += digit * weight;
  83. let t = if k <= bias { T_MIN }
  84. else if k >= bias + T_MAX { T_MAX }
  85. else { k - bias };
  86. if digit < t {
  87. break
  88. }
  89. if weight > u32::MAX / (BASE - t) {
  90. return None // Overflow
  91. }
  92. weight *= BASE - t;
  93. k += BASE;
  94. byte = match iter.next() {
  95. None => return None, // End of input before the end of this delta
  96. Some(byte) => byte,
  97. };
  98. }
  99. let length = output.len() as u32;
  100. bias = adapt(i - previous_i, length + 1, previous_i == 0);
  101. if i / (length + 1) > u32::MAX - code_point {
  102. return None // Overflow
  103. }
  104. // i was supposed to wrap around from length+1 to 0,
  105. // incrementing code_point each time.
  106. code_point += i / (length + 1);
  107. i %= length + 1;
  108. let c = match char::from_u32(code_point) {
  109. Some(c) => c,
  110. None => return None
  111. };
  112. output.insert(i as uint, c);
  113. i += 1;
  114. }
  115. Some(output)
  116. }
  117. /// Convert an Unicode `str` to Punycode.
  118. ///
  119. /// This is a convenience wrapper around `encode`.
  120. #[inline]
  121. pub fn encode_str(input: &str) -> Option<String> {
  122. encode(input.chars().collect::<Vec<char>>().as_slice())
  123. }
  124. /// Convert Unicode to Punycode.
  125. ///
  126. /// Return None on overflow, which can only happen on inputs that would take more than
  127. /// 63 encoded bytes, the DNS limit on domain name labels.
  128. pub fn encode(input: &[char]) -> Option<String> {
  129. // Handle "basic" (ASCII) code points. They are encoded as-is.
  130. let output_bytes = input.iter().filter_map(|&c|
  131. if c.is_ascii() { Some(c as u8) } else { None }
  132. ).collect();
  133. let mut output = unsafe { String::from_utf8_unchecked(output_bytes) };
  134. let basic_length = output.len() as u32;
  135. if basic_length > 0 {
  136. output.push_str("-")
  137. }
  138. let mut code_point = INITIAL_N;
  139. let mut delta = 0;
  140. let mut bias = INITIAL_BIAS;
  141. let mut processed = basic_length;
  142. let input_length = input.len() as u32;
  143. while processed < input_length {
  144. // All code points < code_point have been handled already.
  145. // Find the next larger one.
  146. let min_code_point = input.iter().map(|&c| c as u32)
  147. .filter(|&c| c >= code_point).min().unwrap();
  148. if min_code_point - code_point > (u32::MAX - delta) / (processed + 1) {
  149. return None // Overflow
  150. }
  151. // Increase delta to advance the decoder’s <code_point,i> state to <min_code_point,0>
  152. delta += (min_code_point - code_point) * (processed + 1);
  153. code_point = min_code_point;
  154. for &c in input.iter() {
  155. let c = c as u32;
  156. if c < code_point {
  157. delta += 1;
  158. if delta == 0 {
  159. return None // Overflow
  160. }
  161. }
  162. if c == code_point {
  163. // Represent delta as a generalized variable-length integer:
  164. let mut q = delta;
  165. let mut k = BASE;
  166. loop {
  167. let t = if k <= bias { T_MIN }
  168. else if k >= bias + T_MAX { T_MAX }
  169. else { k - bias };
  170. if q < t {
  171. break
  172. }
  173. let value = t + ((q - t) % (BASE - t));
  174. value_to_digit(value, &mut output);
  175. q = (q - t) / (BASE - t);
  176. k += BASE;
  177. }
  178. value_to_digit(q, &mut output);
  179. bias = adapt(delta, processed + 1, processed == basic_length);
  180. delta = 0;
  181. processed += 1;
  182. }
  183. }
  184. delta += 1;
  185. code_point += 1;
  186. }
  187. Some(output)
  188. }
  189. #[inline]
  190. fn value_to_digit(value: u32, output: &mut String) {
  191. let code_point = match value {
  192. 0 ... 25 => value + 0x61, // a..z
  193. 26 ... 35 => value - 26 + 0x30, // 0..9
  194. _ => panic!()
  195. };
  196. unsafe { output.as_mut_vec().push(code_point as u8) }
  197. }
  198. #[cfg(test)]
  199. mod tests {
  200. use super::{decode, encode_str};
  201. use rustc_serialize::json::{from_str, Json, Object};
  202. fn one_test(description: &str, decoded: &str, encoded: &str) {
  203. match decode(encoded) {
  204. None => panic!("Decoding {} failed.", encoded),
  205. Some(result) => {
  206. let result = String::from_chars(result.as_slice());
  207. assert!(result.as_slice() == decoded,
  208. format!("Incorrect decoding of {}:\n {}\n!= {}\n{}",
  209. encoded, result.as_slice(), decoded, description))
  210. }
  211. }
  212. match encode_str(decoded) {
  213. None => panic!("Encoding {} failed.", decoded),
  214. Some(result) => {
  215. assert!(result.as_slice() == encoded,
  216. format!("Incorrect encoding of {}:\n {}\n!= {}\n{}",
  217. decoded, result.as_slice(), encoded, description))
  218. }
  219. }
  220. }
  221. fn get_string<'a>(map: &'a Object, key: &str) -> &'a str {
  222. match map.get(&key.to_string()) {
  223. Some(&Json::String(ref s)) => s.as_slice(),
  224. None => "",
  225. _ => panic!(),
  226. }
  227. }
  228. #[test]
  229. fn test_punycode() {
  230. match from_str(include_str!("punycode_tests.json")) {
  231. Ok(Json::Array(tests)) => for test in tests.iter() {
  232. match test {
  233. &Json::Object(ref o) => one_test(
  234. get_string(o, "description"),
  235. get_string(o, "decoded"),
  236. get_string(o, "encoded")
  237. ),
  238. _ => panic!(),
  239. }
  240. },
  241. other => panic!("{}", other)
  242. }
  243. }
  244. }