better_url/util/parts/host/domain/punycode/encode.rs
1//! Encoding.
2
3use crate::prelude::*;
4
5/// Punycode encode, in-place if possible.
6///
7/// Please note that, per [Appendix C of RFC 3492](https://datatracker.ietf.org/doc/html/rfc3492#appendix-C), this uses [`usize`]s instead of [`u32`]s.
8///
9/// In practice this means nothing but someone's going to complain so I figured I'd explain myself early.
10/// # Examples
11/// ```
12/// use better_url::util::*;
13///
14/// assert_eq!(encode_punycode("" ), "" );
15/// assert_eq!(encode_punycode("a" ), "a-" );
16/// assert_eq!(encode_punycode("a-"), "a--");
17///
18/// assert_eq!(encode_punycode("ليهمابتكلموشعربي؟" ), "egbpdaj6bu4bxfgehfvwxn" );
19/// assert_eq!(encode_punycode("他们为什么不说中文" ), "ihqwcrb4cv8a8dqg056pqjye" );
20/// assert_eq!(encode_punycode("他們爲什麽不說中文" ), "ihqwctvzc91f659drss3x8bo0yb" );
21/// assert_eq!(encode_punycode("Pročprostěnemluvíčesky" ), "Proprostnemluvesky-uyb24dma41a" );
22/// assert_eq!(encode_punycode("למההםפשוטלאמדבריםעברית" ), "4dbcagdahymbxekheh6e0a7fei0b" );
23/// assert_eq!(encode_punycode("यहलोगहिन\u{94d}दीक\u{94d}यो\u{902}नही\u{902}बोलसकत\u{947}ह\u{948}\u{902}"), "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd" );
24/// assert_eq!(encode_punycode("なぜみんな日本語を話してくれないのか" ), "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa" );
25/// assert_eq!(encode_punycode("세계의모든사람들이한국어를이해한다면얼마나좋을까" ), "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c");
26/// assert_eq!(encode_punycode("почемужеонинеговорятпорусски" ), "b1abfaaepdrnnbgefbadotcwatmq2g4l" );
27/// assert_eq!(encode_punycode("PorquénopuedensimplementehablarenEspañol" ), "PorqunopuedensimplementehablarenEspaol-fmd56a" );
28/// assert_eq!(encode_punycode("TạisaohọkhôngthểchỉnóitiếngViệt" ), "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g" );
29/// ```
30pub fn encode_punycode<'a, T: Into<Cow<'a, str>>>(value: T) -> Cow<'a, str> {
31 let mut value = value.into();
32
33 if value.is_ascii() {
34 if !value.is_empty() {
35 value.push_str("-");
36 }
37
38 value
39 } else {
40 let mut out = String::new();
41 encode_punycode_into(&value, &mut out);
42 out.into()
43 }
44}
45
46/// Punycode encode into a [`String`].
47///
48/// Please note that, per [Appendix C of RFC 3492](https://datatracker.ietf.org/doc/html/rfc3492#appendix-C), this uses [`usize`]s instead of [`u32`]s.
49///
50/// In practice this means nothing but someone's going to complain so I figured I'd explain myself early.
51pub fn encode_punycode_into<'a>(value: &str, out: &'a mut String) -> &'a str {
52 encode_punycode_into_bytes(value, unsafe {out.as_mut_vec()})
53}
54
55/// Punycode encode into a [`Vec`] of bytes.
56///
57/// Please note that, per [Appendix C of RFC 3492](https://datatracker.ietf.org/doc/html/rfc3492#appendix-C), this uses [`usize`]s instead of [`u32`]s.
58///
59/// In practice this means nothing but someone's going to complain so I figured I'd explain myself early.
60pub fn encode_punycode_into_bytes<'a>(value: &str, out: &'a mut Vec<u8>) -> &'a str {
61 let mut delta = 0usize;
62 let mut bias = 72usize;
63 let mut last_look = '\u{7F}';
64 let mut first = true;
65 let mut insert_points = 1usize;
66
67 let new_len = out.len();
68 out.reserve(value.len());
69
70 for b in value.bytes() {
71 if b.is_ascii() {
72 out.push(b);
73 insert_points += 1;
74 }
75 }
76
77 if insert_points != 1 {
78 out.push(b'-');
79 }
80
81 while let Some(look) = value.chars().filter(|&c| c > last_look).min() {
82 delta += (look as usize - last_look as usize - 1) * insert_points;
83 last_look = look;
84
85 for c in value.chars() {
86 if c < look {
87 delta += 1;
88 }
89
90 if c == look {
91 let mut q = delta;
92
93 for i in 1usize.. {
94 let threshold = (i * 36).saturating_sub(bias).clamp(1, 26);
95
96 if q < threshold {
97 out.push(q as u8 + b'a');
98 break;
99 }
100
101 let digit = threshold + (q - threshold) % (36 - threshold);
102 q = (q - threshold) / (36 - threshold);
103
104 out.push(match digit as u8 {
105 digit @ ..26 => digit + b'a',
106 digit @ 26.. => digit - 26 + b'0',
107 });
108 }
109
110
111
112 match first {
113 true => delta /= 700,
114 false => delta /= 2,
115 }
116
117 delta += delta / insert_points;
118
119 bias = 36;
120
121 while delta > 455 {
122 delta /= 35;
123 bias += 36;
124 }
125
126 bias -= (delta + 1405) / (delta + 38);
127
128
129
130 insert_points += 1;
131 delta = 0;
132 first = false;
133 }
134 }
135
136 delta += 1;
137 }
138
139 unsafe {
140 str::from_utf8_unchecked(out.get_unchecked(new_len..))
141 }
142}