1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#[path = "encode_sets.rs"]
mod encode_sets;
#[derive(Copy)]
pub struct EncodeSet {
map: &'static [&'static str; 256],
}
pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE };
pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY };
pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT };
pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO };
pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD };
pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME };
pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet {
map: &encode_sets::FORM_URLENCODED,
};
#[inline]
pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) {
for &byte in input.iter() {
output.push_str(encode_set.map[byte as usize])
}
}
#[inline]
pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String {
let mut output = String::new();
percent_encode_to(input, encode_set, &mut output);
output
}
#[inline]
pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) {
percent_encode_to(input.as_bytes(), encode_set, output)
}
#[inline]
pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String {
let mut output = String::new();
utf8_percent_encode_to(input, encode_set, &mut output);
output
}
pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) {
let mut i = 0;
while i < input.len() {
let c = input[i];
if c == b'%' && i + 2 < input.len() {
match (from_hex(input[i + 1]), from_hex(input[i + 2])) {
(Some(h), Some(l)) => {
output.push(h * 0x10 + l);
i += 3;
continue
},
_ => (),
}
}
output.push(c);
i += 1;
}
}
#[inline]
pub fn percent_decode(input: &[u8]) -> Vec<u8> {
let mut output = Vec::new();
percent_decode_to(input, &mut output);
output
}
#[inline]
pub fn lossy_utf8_percent_decode(input: &[u8]) -> String {
String::from_utf8_lossy(percent_decode(input).as_slice()).to_string()
}
#[inline]
pub fn from_hex(byte: u8) -> Option<u8> {
match byte {
b'0' ... b'9' => Some(byte - b'0'),
b'A' ... b'F' => Some(byte + 10 - b'A'),
b'a' ... b'f' => Some(byte + 10 - b'a'),
_ => None
}
}