punycode.rs 8.1 KB

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