1#![forbid(unsafe_code)]
2
3pub fn encode_uri(s: impl AsRef<str>) -> String {
5 let mut encoded = String::with_capacity(s.as_ref().len());
6 for c in s.as_ref().as_bytes() {
7 match c {
8 b'A'..=b'Z'
9 | b'a'..=b'z'
10 | b'0'..=b'9'
11 | b'-'
12 | b'_'
13 | b'.'
14 | b'!'
15 | b'~'
16 | b'*'
17 | b'\''
18 | b'('
19 | b')'
20 | b';'
21 | b','
22 | b'/'
23 | b'?'
24 | b':'
25 | b'@'
26 | b'&'
27 | b'='
28 | b'+'
29 | b'$'
30 | b'#' => encoded.push(char::from_u32(*c as _).unwrap()),
31 c => {
32 encoded.push('%');
33 encoded.push_str(&format!("{:02x}", c));
34 }
35 }
36 }
37 encoded
38}
39
40pub fn encode_uri_component(s: impl AsRef<str>) -> String {
42 let mut encoded = String::with_capacity(s.as_ref().len());
43 for c in s.as_ref().as_bytes() {
44 match c {
45 b'A'..=b'Z'
46 | b'a'..=b'z'
47 | b'0'..=b'9'
48 | b'-'
49 | b'_'
50 | b'.'
51 | b'!'
52 | b'~'
53 | b'*'
54 | b'\''
55 | b'('
56 | b')' => encoded.push(char::from_u32(*c as _).unwrap()),
57 c => {
58 encoded.push('%');
59 encoded.push_str(&format!("{:02x}", c));
60 }
61 }
62 }
63 encoded
64}
65
66pub fn encode_query_param(s: impl AsRef<str>) -> String {
68 let mut encoded = String::with_capacity(s.as_ref().len());
69 for c in s.as_ref().as_bytes() {
70 match c {
71 b' ' => encoded.push('+'),
72 b'A'..=b'Z'
73 | b'a'..=b'z'
74 | b'0'..=b'9'
75 | b'-'
76 | b'_'
77 | b'.'
78 | b'!'
79 | b'~'
80 | b'*'
81 | b'\''
82 | b'('
83 | b')'
84 | b';'
85 | b','
86 | b'/'
87 | b'?'
88 | b':'
89 | b'@'
90 | b'&'
91 | b'='
92 | b'+'
93 | b'$'
94 | b'#' => encoded.push(char::from_u32(*c as _).unwrap()),
95 c => {
96 encoded.push('%');
97 encoded.push_str(&format!("{:02x}", c));
98 }
99 }
100 }
101 encoded
102}