punycode.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. //! 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 alloc::{string::String, vec::Vec};
  15. use core::char;
  16. use core::fmt::Write;
  17. use core::marker::PhantomData;
  18. // Bootstring parameters for Punycode
  19. const BASE: u32 = 36;
  20. const T_MIN: u32 = 1;
  21. const T_MAX: u32 = 26;
  22. const SKEW: u32 = 38;
  23. const DAMP: u32 = 700;
  24. const INITIAL_BIAS: u32 = 72;
  25. const INITIAL_N: u32 = 0x80;
  26. #[inline]
  27. fn adapt(mut delta: u32, num_points: u32, first_time: bool) -> u32 {
  28. delta /= if first_time { DAMP } else { 2 };
  29. delta += delta / num_points;
  30. let mut k = 0;
  31. while delta > ((BASE - T_MIN) * T_MAX) / 2 {
  32. delta /= BASE - T_MIN;
  33. k += BASE;
  34. }
  35. k + (((BASE - T_MIN + 1) * delta) / (delta + SKEW))
  36. }
  37. /// Convert Punycode to an Unicode `String`.
  38. ///
  39. /// Return None on malformed input or overflow.
  40. /// Overflow can only happen on inputs that take more than
  41. /// 63 encoded bytes, the DNS limit on domain name labels.
  42. #[inline]
  43. pub fn decode_to_string(input: &str) -> Option<String> {
  44. Some(
  45. Decoder::default()
  46. .decode::<u8, ExternalCaller>(input.as_bytes())
  47. .ok()?
  48. .collect(),
  49. )
  50. }
  51. /// Convert Punycode to Unicode.
  52. ///
  53. /// Return None on malformed input or overflow.
  54. /// Overflow can only happen on inputs that take more than
  55. /// 63 encoded bytes, the DNS limit on domain name labels.
  56. pub fn decode(input: &str) -> Option<Vec<char>> {
  57. Some(
  58. Decoder::default()
  59. .decode::<u8, ExternalCaller>(input.as_bytes())
  60. .ok()?
  61. .collect(),
  62. )
  63. }
  64. /// Marker for internal vs. external caller to retain old API behavior
  65. /// while tweaking behavior for internal callers.
  66. ///
  67. /// External callers need overflow checks when encoding, but internal
  68. /// callers don't, because `PUNYCODE_ENCODE_MAX_INPUT_LENGTH` is set
  69. /// to 1000, and per RFC 3492 section 6.4, the integer variable does
  70. /// not need to be able to represent values larger than
  71. /// (char::MAX - INITIAL_N) * (PUNYCODE_ENCODE_MAX_INPUT_LENGTH + 1),
  72. /// which is less than u32::MAX.
  73. ///
  74. /// External callers need to handle upper-case ASCII when decoding,
  75. /// but internal callers don't, because the internal code calls the
  76. /// decoder only with lower-case inputs.
  77. pub(crate) trait PunycodeCaller {
  78. const EXTERNAL_CALLER: bool;
  79. }
  80. pub(crate) struct InternalCaller;
  81. impl PunycodeCaller for InternalCaller {
  82. const EXTERNAL_CALLER: bool = false;
  83. }
  84. struct ExternalCaller;
  85. impl PunycodeCaller for ExternalCaller {
  86. const EXTERNAL_CALLER: bool = true;
  87. }
  88. pub(crate) trait PunycodeCodeUnit {
  89. fn is_delimiter(&self) -> bool;
  90. fn is_ascii(&self) -> bool;
  91. fn digit(&self) -> Option<u32>;
  92. fn char(&self) -> char;
  93. fn char_ascii_lower_case(&self) -> char;
  94. }
  95. impl PunycodeCodeUnit for u8 {
  96. fn is_delimiter(&self) -> bool {
  97. *self == b'-'
  98. }
  99. fn is_ascii(&self) -> bool {
  100. *self < 0x80
  101. }
  102. fn digit(&self) -> Option<u32> {
  103. let byte = *self;
  104. Some(match byte {
  105. byte @ b'0'..=b'9' => byte - b'0' + 26,
  106. byte @ b'A'..=b'Z' => byte - b'A',
  107. byte @ b'a'..=b'z' => byte - b'a',
  108. _ => return None,
  109. } as u32)
  110. }
  111. fn char(&self) -> char {
  112. char::from(*self)
  113. }
  114. fn char_ascii_lower_case(&self) -> char {
  115. char::from(self.to_ascii_lowercase())
  116. }
  117. }
  118. impl PunycodeCodeUnit for char {
  119. fn is_delimiter(&self) -> bool {
  120. *self == '-'
  121. }
  122. fn is_ascii(&self) -> bool {
  123. debug_assert!(false); // Unused
  124. true
  125. }
  126. fn digit(&self) -> Option<u32> {
  127. let byte = *self;
  128. Some(match byte {
  129. byte @ '0'..='9' => u32::from(byte) - u32::from('0') + 26,
  130. // byte @ 'A'..='Z' => u32::from(byte) - u32::from('A'), // XXX not needed if no public input
  131. byte @ 'a'..='z' => u32::from(byte) - u32::from('a'),
  132. _ => return None,
  133. })
  134. }
  135. fn char(&self) -> char {
  136. debug_assert!(false); // Unused
  137. *self
  138. }
  139. fn char_ascii_lower_case(&self) -> char {
  140. // No need to actually lower-case!
  141. *self
  142. }
  143. }
  144. #[derive(Default)]
  145. pub(crate) struct Decoder {
  146. insertions: smallvec::SmallVec<[(usize, char); 59]>,
  147. }
  148. impl Decoder {
  149. /// Split the input iterator and return a Vec with insertions of encoded characters
  150. pub(crate) fn decode<'a, T: PunycodeCodeUnit + Copy, C: PunycodeCaller>(
  151. &'a mut self,
  152. input: &'a [T],
  153. ) -> Result<Decode<'a, T, C>, ()> {
  154. self.insertions.clear();
  155. // Handle "basic" (ASCII) code points.
  156. // They are encoded as-is before the last delimiter, if any.
  157. let (base, input) = if let Some(position) = input.iter().rposition(|c| c.is_delimiter()) {
  158. (
  159. &input[..position],
  160. if position > 0 {
  161. &input[position + 1..]
  162. } else {
  163. input
  164. },
  165. )
  166. } else {
  167. (&input[..0], input)
  168. };
  169. if C::EXTERNAL_CALLER && !base.iter().all(|c| c.is_ascii()) {
  170. return Err(());
  171. }
  172. let base_len = base.len();
  173. let mut length = base_len as u32;
  174. let mut code_point = INITIAL_N;
  175. let mut bias = INITIAL_BIAS;
  176. let mut i = 0u32;
  177. let mut iter = input.iter();
  178. loop {
  179. let previous_i = i;
  180. let mut weight = 1;
  181. let mut k = BASE;
  182. let mut byte = match iter.next() {
  183. None => break,
  184. Some(byte) => byte,
  185. };
  186. // Decode a generalized variable-length integer into delta,
  187. // which gets added to i.
  188. loop {
  189. let digit = if let Some(digit) = byte.digit() {
  190. digit
  191. } else {
  192. return Err(());
  193. };
  194. let product = digit.checked_mul(weight).ok_or(())?;
  195. i = i.checked_add(product).ok_or(())?;
  196. let t = if k <= bias {
  197. T_MIN
  198. } else if k >= bias + T_MAX {
  199. T_MAX
  200. } else {
  201. k - bias
  202. };
  203. if digit < t {
  204. break;
  205. }
  206. weight = weight.checked_mul(BASE - t).ok_or(())?;
  207. k += BASE;
  208. byte = match iter.next() {
  209. None => return Err(()), // End of input before the end of this delta
  210. Some(byte) => byte,
  211. };
  212. }
  213. bias = adapt(i - previous_i, length + 1, previous_i == 0);
  214. // i was supposed to wrap around from length+1 to 0,
  215. // incrementing code_point each time.
  216. code_point = code_point.checked_add(i / (length + 1)).ok_or(())?;
  217. i %= length + 1;
  218. let c = match char::from_u32(code_point) {
  219. Some(c) => c,
  220. None => return Err(()),
  221. };
  222. // Move earlier insertions farther out in the string
  223. for (idx, _) in &mut self.insertions {
  224. if *idx >= i as usize {
  225. *idx += 1;
  226. }
  227. }
  228. self.insertions.push((i as usize, c));
  229. length += 1;
  230. i += 1;
  231. }
  232. self.insertions.sort_by_key(|(i, _)| *i);
  233. Ok(Decode {
  234. base: base.iter(),
  235. insertions: &self.insertions,
  236. inserted: 0,
  237. position: 0,
  238. len: base_len + self.insertions.len(),
  239. phantom: PhantomData::<C>,
  240. })
  241. }
  242. }
  243. pub(crate) struct Decode<'a, T, C>
  244. where
  245. T: PunycodeCodeUnit + Copy,
  246. C: PunycodeCaller,
  247. {
  248. base: core::slice::Iter<'a, T>,
  249. pub(crate) insertions: &'a [(usize, char)],
  250. inserted: usize,
  251. position: usize,
  252. len: usize,
  253. phantom: PhantomData<C>,
  254. }
  255. impl<T: PunycodeCodeUnit + Copy, C: PunycodeCaller> Iterator for Decode<'_, T, C> {
  256. type Item = char;
  257. fn next(&mut self) -> Option<Self::Item> {
  258. loop {
  259. match self.insertions.get(self.inserted) {
  260. Some((pos, c)) if *pos == self.position => {
  261. self.inserted += 1;
  262. self.position += 1;
  263. return Some(*c);
  264. }
  265. _ => {}
  266. }
  267. if let Some(c) = self.base.next() {
  268. self.position += 1;
  269. return Some(if C::EXTERNAL_CALLER {
  270. c.char()
  271. } else {
  272. c.char_ascii_lower_case()
  273. });
  274. } else if self.inserted >= self.insertions.len() {
  275. return None;
  276. }
  277. }
  278. }
  279. fn size_hint(&self) -> (usize, Option<usize>) {
  280. let len = self.len - self.position;
  281. (len, Some(len))
  282. }
  283. }
  284. impl<T: PunycodeCodeUnit + Copy, C: PunycodeCaller> ExactSizeIterator for Decode<'_, T, C> {
  285. fn len(&self) -> usize {
  286. self.len - self.position
  287. }
  288. }
  289. /// Convert an Unicode `str` to Punycode.
  290. ///
  291. /// This is a convenience wrapper around `encode`.
  292. #[inline]
  293. pub fn encode_str(input: &str) -> Option<String> {
  294. if input.len() > u32::MAX as usize {
  295. return None;
  296. }
  297. let mut buf = String::with_capacity(input.len());
  298. encode_into::<_, _, ExternalCaller>(input.chars(), &mut buf)
  299. .ok()
  300. .map(|()| buf)
  301. }
  302. /// Convert Unicode to Punycode.
  303. ///
  304. /// Return None on overflow, which can only happen on inputs that would take more than
  305. /// 63 encoded bytes, the DNS limit on domain name labels.
  306. pub fn encode(input: &[char]) -> Option<String> {
  307. if input.len() > u32::MAX as usize {
  308. return None;
  309. }
  310. let mut buf = String::with_capacity(input.len());
  311. encode_into::<_, _, ExternalCaller>(input.iter().copied(), &mut buf)
  312. .ok()
  313. .map(|()| buf)
  314. }
  315. pub(crate) enum PunycodeEncodeError {
  316. Overflow,
  317. Sink,
  318. }
  319. impl From<core::fmt::Error> for PunycodeEncodeError {
  320. fn from(_: core::fmt::Error) -> Self {
  321. Self::Sink
  322. }
  323. }
  324. pub(crate) fn encode_into<I, W, C>(input: I, output: &mut W) -> Result<(), PunycodeEncodeError>
  325. where
  326. I: Iterator<Item = char> + Clone,
  327. W: Write + ?Sized,
  328. C: PunycodeCaller,
  329. {
  330. // Handle "basic" (ASCII) code points. They are encoded as-is.
  331. let (mut input_length, mut basic_length) = (0u32, 0);
  332. for c in input.clone() {
  333. input_length = input_length
  334. .checked_add(1)
  335. .ok_or(PunycodeEncodeError::Overflow)?;
  336. if c.is_ascii() {
  337. output.write_char(c)?;
  338. basic_length += 1;
  339. }
  340. }
  341. if !C::EXTERNAL_CALLER {
  342. // We should never get an overflow here with the internal caller being
  343. // length-limited, but let's check anyway once here trusting the math
  344. // from RFC 3492 section 6.4 and then omit the overflow checks in the
  345. // loop below.
  346. let len_plus_one = input_length
  347. .checked_add(1)
  348. .ok_or(PunycodeEncodeError::Overflow)?;
  349. len_plus_one
  350. .checked_mul(u32::from(char::MAX) - INITIAL_N)
  351. .ok_or(PunycodeEncodeError::Overflow)?;
  352. }
  353. if basic_length > 0 {
  354. output.write_char('-')?;
  355. }
  356. let mut code_point = INITIAL_N;
  357. let mut delta = 0u32;
  358. let mut bias = INITIAL_BIAS;
  359. let mut processed = basic_length;
  360. while processed < input_length {
  361. // All code points < code_point have been handled already.
  362. // Find the next larger one.
  363. let min_code_point = input
  364. .clone()
  365. .map(|c| c as u32)
  366. .filter(|&c| c >= code_point)
  367. .min()
  368. .unwrap();
  369. // Increase delta to advance the decoder’s <code_point,i> state to <min_code_point,0>
  370. if C::EXTERNAL_CALLER {
  371. let product = (min_code_point - code_point)
  372. .checked_mul(processed + 1)
  373. .ok_or(PunycodeEncodeError::Overflow)?;
  374. delta = delta
  375. .checked_add(product)
  376. .ok_or(PunycodeEncodeError::Overflow)?;
  377. } else {
  378. delta += (min_code_point - code_point) * (processed + 1);
  379. }
  380. code_point = min_code_point;
  381. for c in input.clone() {
  382. let c = c as u32;
  383. if c < code_point {
  384. if C::EXTERNAL_CALLER {
  385. delta = delta.checked_add(1).ok_or(PunycodeEncodeError::Overflow)?;
  386. } else {
  387. delta += 1;
  388. }
  389. }
  390. if c == code_point {
  391. // Represent delta as a generalized variable-length integer:
  392. let mut q = delta;
  393. let mut k = BASE;
  394. loop {
  395. let t = if k <= bias {
  396. T_MIN
  397. } else if k >= bias + T_MAX {
  398. T_MAX
  399. } else {
  400. k - bias
  401. };
  402. if q < t {
  403. break;
  404. }
  405. let value = t + ((q - t) % (BASE - t));
  406. output.write_char(value_to_digit(value))?;
  407. q = (q - t) / (BASE - t);
  408. k += BASE;
  409. }
  410. output.write_char(value_to_digit(q))?;
  411. bias = adapt(delta, processed + 1, processed == basic_length);
  412. delta = 0;
  413. processed += 1;
  414. }
  415. }
  416. delta += 1;
  417. code_point += 1;
  418. }
  419. Ok(())
  420. }
  421. #[inline]
  422. fn value_to_digit(value: u32) -> char {
  423. match value {
  424. 0..=25 => (value as u8 + b'a') as char, // a..z
  425. 26..=35 => (value as u8 - 26 + b'0') as char, // 0..9
  426. _ => panic!(),
  427. }
  428. }
  429. #[test]
  430. #[ignore = "slow"]
  431. #[cfg(target_pointer_width = "64")]
  432. fn huge_encode() {
  433. let mut buf = String::new();
  434. assert!(encode_into::<_, _, ExternalCaller>(
  435. core::iter::repeat('ß').take(u32::MAX as usize + 1),
  436. &mut buf
  437. )
  438. .is_err());
  439. assert_eq!(buf.len(), 0);
  440. }