percent_encoding/
percent_encoding.rs1#![no_std]
40
41#[cfg(feature = "std")]
43extern crate std as _;
44
45#[cfg(feature = "alloc")]
46extern crate alloc;
47
48#[cfg(feature = "alloc")]
49use alloc::{
50 borrow::{Cow, ToOwned},
51 string::String,
52 vec::Vec,
53};
54use core::{fmt, slice, str};
55
56pub use self::ascii_set::{AsciiSet, CONTROLS, NON_ALPHANUMERIC};
57
58mod ascii_set;
59
60#[inline]
73pub fn percent_encode_byte(byte: u8) -> &'static str {
74 static ENC_TABLE: &[u8; 768] = b"\
75 %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
76 %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
77 %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
78 %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
79 %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
80 %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
81 %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
82 %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
83 %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
84 %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
85 %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
86 %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
87 %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
88 %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
89 %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
90 %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
91 ";
92
93 let index = usize::from(byte) * 3;
94 unsafe { str::from_utf8_unchecked(&ENC_TABLE[index..index + 3]) }
97}
98
99#[inline]
117pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
118 PercentEncode {
119 bytes: input,
120 ascii_set,
121 }
122}
123
124#[inline]
136pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
137 percent_encode(input.as_bytes(), ascii_set)
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct PercentEncode<'a> {
143 bytes: &'a [u8],
144 ascii_set: &'static AsciiSet,
145}
146
147impl<'a> Iterator for PercentEncode<'a> {
148 type Item = &'a str;
149
150 fn next(&mut self) -> Option<&'a str> {
151 if let Some((&first_byte, remaining)) = self.bytes.split_first() {
152 if self.ascii_set.should_percent_encode(first_byte) {
153 self.bytes = remaining;
154 Some(percent_encode_byte(first_byte))
155 } else {
156 for (i, &byte) in remaining.iter().enumerate() {
159 if self.ascii_set.should_percent_encode(byte) {
160 let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
162 self.bytes = remaining;
163 return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
164 }
165 }
166 let unchanged_slice = self.bytes;
167 self.bytes = &[][..];
168 Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
169 }
170 } else {
171 None
172 }
173 }
174
175 fn size_hint(&self) -> (usize, Option<usize>) {
176 if self.bytes.is_empty() {
177 (0, Some(0))
178 } else {
179 (1, Some(self.bytes.len()))
180 }
181 }
182}
183
184impl fmt::Display for PercentEncode<'_> {
185 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
186 for c in (*self).clone() {
187 formatter.write_str(c)?
188 }
189 Ok(())
190 }
191}
192
193#[cfg(feature = "alloc")]
194impl<'a> From<PercentEncode<'a>> for Cow<'a, str> {
195 fn from(mut iter: PercentEncode<'a>) -> Self {
196 match iter.next() {
197 None => "".into(),
198 Some(first) => match iter.next() {
199 None => first.into(),
200 Some(second) => {
201 let mut string = first.to_owned();
202 string.push_str(second);
203 string.extend(iter);
204 string.into()
205 }
206 },
207 }
208 }
209}
210
211#[inline]
217pub fn percent_decode_str(input: &str) -> PercentDecode<'_> {
218 percent_decode(input.as_bytes())
219}
220
221#[inline]
240pub fn percent_decode(input: &[u8]) -> PercentDecode<'_> {
241 PercentDecode {
242 bytes: input.iter(),
243 }
244}
245
246#[derive(Clone, Debug)]
248pub struct PercentDecode<'a> {
249 bytes: slice::Iter<'a, u8>,
250}
251
252fn after_percent_sign(iter: &mut slice::Iter<'_, u8>) -> Option<u8> {
253 let mut cloned_iter = iter.clone();
254 let h = char::from(*cloned_iter.next()?).to_digit(16)?;
255 let l = char::from(*cloned_iter.next()?).to_digit(16)?;
256 *iter = cloned_iter;
257 Some(h as u8 * 0x10 + l as u8)
258}
259
260impl Iterator for PercentDecode<'_> {
261 type Item = u8;
262
263 fn next(&mut self) -> Option<u8> {
264 self.bytes.next().map(|&byte| {
265 if byte == b'%' {
266 after_percent_sign(&mut self.bytes).unwrap_or(byte)
267 } else {
268 byte
269 }
270 })
271 }
272
273 fn size_hint(&self) -> (usize, Option<usize>) {
274 let bytes = self.bytes.len();
275 ((bytes + 2) / 3, Some(bytes))
276 }
277}
278
279#[cfg(feature = "alloc")]
280impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
281 fn from(iter: PercentDecode<'a>) -> Self {
282 match iter.if_any() {
283 Some(vec) => Cow::Owned(vec),
284 None => Cow::Borrowed(iter.bytes.as_slice()),
285 }
286 }
287}
288
289impl<'a> PercentDecode<'a> {
290 #[cfg(feature = "alloc")]
292 fn if_any(&self) -> Option<Vec<u8>> {
293 let mut bytes_iter = self.bytes.clone();
294 while bytes_iter.any(|&b| b == b'%') {
295 if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
296 let initial_bytes = self.bytes.as_slice();
297 let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
298 let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
299 decoded.push(decoded_byte);
300 decoded.extend(PercentDecode {
301 bytes: bytes_iter,
302 });
303 return Some(decoded);
304 }
305 }
306 None
308 }
309
310 #[cfg(feature = "alloc")]
314 pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
315 match self.clone().into() {
316 Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
317 Ok(s) => Ok(s.into()),
318 Err(e) => Err(e),
319 },
320 Cow::Owned(bytes) => match String::from_utf8(bytes) {
321 Ok(s) => Ok(s.into()),
322 Err(e) => Err(e.utf8_error()),
323 },
324 }
325 }
326
327 #[cfg(feature = "alloc")]
332 pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
333 decode_utf8_lossy(self.clone().into())
334 }
335}
336
337#[cfg(feature = "alloc")]
340#[allow(ambiguous_wide_pointer_comparisons)]
341fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
342 match input {
344 Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
345 Cow::Owned(bytes) => {
346 match String::from_utf8_lossy(&bytes) {
347 Cow::Borrowed(utf8) => {
348 let raw_utf8: *const [u8] = utf8.as_bytes();
356 debug_assert!(core::ptr::eq(raw_utf8, &*bytes));
357
358 Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
362 }
363 Cow::Owned(s) => Cow::Owned(s),
364 }
365 }
366 }
367}
368
369#[cfg(test)]
370mod tests {
371
372 use super::*;
373
374 #[test]
375 fn percent_encode_byte() {
376 for i in 0..=0xFF {
377 let encoded = super::percent_encode_byte(i);
378 assert_eq!(encoded, alloc::format!("%{:02X}", i));
379 }
380 }
381
382 #[test]
383 fn percent_encode_accepts_ascii_set_ref() {
384 let encoded = percent_encode(b"foo bar?", &AsciiSet::EMPTY);
385 assert_eq!(encoded.collect::<String>(), "foo bar?");
386 }
387
388 #[test]
389 fn percent_encode_collect() {
390 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
391 assert_eq!(encoded.collect::<String>(), String::from("foo%20bar%3F"));
392
393 let encoded = percent_encode(b"\x00\x01\x02\x03", CONTROLS);
394 assert_eq!(encoded.collect::<String>(), String::from("%00%01%02%03"));
395 }
396
397 #[test]
398 fn percent_encode_display() {
399 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
400 assert_eq!(alloc::format!("{}", encoded), "foo%20bar%3F");
401 }
402
403 #[test]
404 fn percent_encode_cow() {
405 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
406 assert_eq!(Cow::from(encoded), "foo%20bar%3F");
407 }
408
409 #[test]
410 fn utf8_percent_encode_accepts_ascii_set_ref() {
411 let encoded = super::utf8_percent_encode("foo bar?", &AsciiSet::EMPTY);
412 assert_eq!(encoded.collect::<String>(), "foo bar?");
413 }
414
415 #[test]
416 fn utf8_percent_encode() {
417 assert_eq!(
418 super::utf8_percent_encode("foo bar?", NON_ALPHANUMERIC),
419 percent_encode(b"foo bar?", NON_ALPHANUMERIC)
420 );
421 }
422
423 #[test]
424 fn percent_decode() {
425 assert_eq!(super::percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
426 }
427
428 #[test]
429 fn percent_decode_str() {
430 assert_eq!(super::percent_decode_str("foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
431 }
432
433 #[test]
434 fn percent_decode_collect() {
435 let decoded = super::percent_decode(b"foo%20bar%3f");
436 assert_eq!(decoded.collect::<Vec<u8>>(), b"foo bar?");
437 }
438
439 #[test]
440 fn percent_decode_cow() {
441 let decoded = super::percent_decode(b"foo%20bar%3f");
442 assert_eq!(Cow::from(decoded), Cow::Owned::<[u8]>(b"foo bar?".to_vec()));
443
444 let decoded = super::percent_decode(b"foo bar?");
445 assert_eq!(Cow::from(decoded), Cow::Borrowed(b"foo bar?"));
446 }
447
448 #[test]
449 fn percent_decode_invalid_utf8() {
450 let decoded = super::percent_decode(b"%00%9F%92%96").decode_utf8().unwrap_err();
452 assert_eq!(decoded.valid_up_to(), 1);
453 assert_eq!(decoded.error_len(), Some(1));
454 }
455
456 #[test]
457 fn percent_decode_utf8_lossy() {
458 assert_eq!(super::percent_decode(b"%F0%9F%92%96").decode_utf8_lossy(), "💖");
459 }
460
461 #[test]
462 fn percent_decode_utf8_lossy_invalid_utf8() {
463 assert_eq!(super::percent_decode(b"%00%9F%92%96").decode_utf8_lossy(), "\u{0}���");
464 }
465}