1#![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 { bytes: bytes_iter });
301 return Some(decoded);
302 }
303 }
304 None
306 }
307
308 #[cfg(feature = "alloc")]
312 pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
313 match self.clone().into() {
314 Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
315 Ok(s) => Ok(s.into()),
316 Err(e) => Err(e),
317 },
318 Cow::Owned(bytes) => match String::from_utf8(bytes) {
319 Ok(s) => Ok(s.into()),
320 Err(e) => Err(e.utf8_error()),
321 },
322 }
323 }
324
325 #[cfg(feature = "alloc")]
330 pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
331 decode_utf8_lossy(self.clone().into())
332 }
333}
334
335#[cfg(feature = "alloc")]
338#[allow(ambiguous_wide_pointer_comparisons)]
339fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
340 match input {
342 Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
343 Cow::Owned(bytes) => {
344 match String::from_utf8_lossy(&bytes) {
345 Cow::Borrowed(utf8) => {
346 let raw_utf8: *const [u8] = utf8.as_bytes();
354 debug_assert!(core::ptr::eq(raw_utf8, &*bytes));
355
356 Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
360 }
361 Cow::Owned(s) => Cow::Owned(s),
362 }
363 }
364 }
365}
366
367#[cfg(test)]
368mod tests {
369
370 use super::*;
371
372 #[test]
373 fn percent_encode_byte() {
374 for i in 0..=0xFF {
375 let encoded = super::percent_encode_byte(i);
376 assert_eq!(encoded, alloc::format!("%{:02X}", i));
377 }
378 }
379
380 #[test]
381 fn percent_encode_accepts_ascii_set_ref() {
382 let encoded = percent_encode(b"foo bar?", &AsciiSet::EMPTY);
383 assert_eq!(encoded.collect::<String>(), "foo bar?");
384 }
385
386 #[test]
387 fn percent_encode_collect() {
388 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
389 assert_eq!(encoded.collect::<String>(), String::from("foo%20bar%3F"));
390
391 let encoded = percent_encode(b"\x00\x01\x02\x03", CONTROLS);
392 assert_eq!(encoded.collect::<String>(), String::from("%00%01%02%03"));
393 }
394
395 #[test]
396 fn percent_encode_display() {
397 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
398 assert_eq!(alloc::format!("{}", encoded), "foo%20bar%3F");
399 }
400
401 #[test]
402 fn percent_encode_cow() {
403 let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
404 assert_eq!(Cow::from(encoded), "foo%20bar%3F");
405 }
406
407 #[test]
408 fn utf8_percent_encode_accepts_ascii_set_ref() {
409 let encoded = super::utf8_percent_encode("foo bar?", &AsciiSet::EMPTY);
410 assert_eq!(encoded.collect::<String>(), "foo bar?");
411 }
412
413 #[test]
414 fn utf8_percent_encode() {
415 assert_eq!(
416 super::utf8_percent_encode("foo bar?", NON_ALPHANUMERIC),
417 percent_encode(b"foo bar?", NON_ALPHANUMERIC)
418 );
419 }
420
421 #[test]
422 fn percent_decode() {
423 assert_eq!(
424 super::percent_decode(b"foo%20bar%3f")
425 .decode_utf8()
426 .unwrap(),
427 "foo bar?"
428 );
429 }
430
431 #[test]
432 fn percent_decode_str() {
433 assert_eq!(
434 super::percent_decode_str("foo%20bar%3f")
435 .decode_utf8()
436 .unwrap(),
437 "foo bar?"
438 );
439 }
440
441 #[test]
442 fn percent_decode_collect() {
443 let decoded = super::percent_decode(b"foo%20bar%3f");
444 assert_eq!(decoded.collect::<Vec<u8>>(), b"foo bar?");
445 }
446
447 #[test]
448 fn percent_decode_cow() {
449 let decoded = super::percent_decode(b"foo%20bar%3f");
450 assert_eq!(Cow::from(decoded), Cow::Owned::<[u8]>(b"foo bar?".to_vec()));
451
452 let decoded = super::percent_decode(b"foo bar?");
453 assert_eq!(Cow::from(decoded), Cow::Borrowed(b"foo bar?"));
454 }
455
456 #[test]
457 fn percent_decode_invalid_utf8() {
458 let decoded = super::percent_decode(b"%00%9F%92%96")
460 .decode_utf8()
461 .unwrap_err();
462 assert_eq!(decoded.valid_up_to(), 1);
463 assert_eq!(decoded.error_len(), Some(1));
464 }
465
466 #[test]
467 fn percent_decode_utf8_lossy() {
468 assert_eq!(
469 super::percent_decode(b"%F0%9F%92%96").decode_utf8_lossy(),
470 "💖"
471 );
472 }
473
474 #[test]
475 fn percent_decode_utf8_lossy_invalid_utf8() {
476 assert_eq!(
477 super::percent_decode(b"%00%9F%92%96").decode_utf8_lossy(),
478 "\u{0}���"
479 );
480 }
481}