url_escape/decode/
mod.rs

1use std::borrow::Cow;
2use std::io::{self, Write};
3use std::str::from_utf8_unchecked;
4
5use crate::percent_encoding::percent_decode_str;
6
7/// Decode percent-encoded bytes in a given string.
8#[inline]
9pub fn decode<S: ?Sized + AsRef<str>>(text: &S) -> Cow<str> {
10    let pd = percent_decode_str(text.as_ref());
11
12    pd.decode_utf8_lossy()
13}
14
15/// Decode percent-encoded bytes in a given string to a mutable `String` reference and return the decoded string slice.
16#[inline]
17pub fn decode_to_string<S: AsRef<str>>(text: S, output: &mut String) -> &str {
18    unsafe { from_utf8_unchecked(decode_to_vec(text, output.as_mut_vec())) }
19}
20
21/// Decode percent-encoded bytes in a given string to a mutable `Vec<u8>` reference and return the decoded data slice.
22#[inline]
23pub fn decode_to_vec<S: AsRef<str>>(text: S, output: &mut Vec<u8>) -> &[u8] {
24    let text = text.as_ref();
25    let text_bytes = text.as_bytes();
26    let text_length = text_bytes.len();
27
28    output.reserve(text_length);
29
30    let current_length = output.len();
31
32    let pd = percent_decode_str(text);
33
34    output.extend(pd);
35
36    &output[current_length..]
37}
38
39/// Decode percent-encoded bytes in a given string to a writer.
40#[inline]
41pub fn decode_to_writer<S: AsRef<str>, W: Write>(text: S, output: &mut W) -> Result<(), io::Error> {
42    let pd = percent_decode_str(text.as_ref());
43
44    for s in pd {
45        output.write_all(&[s])?;
46    }
47
48    Ok(())
49}