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
use crate::alloc::vec::Vec;

/// Decode a Base64-URL string to data.
#[inline]
pub fn decode<T: ?Sized + AsRef<[u8]>>(input: &T) -> Result<Vec<u8>, base64::DecodeError> {
    base64::decode_config(input, base64::URL_SAFE_NO_PAD)
}

/// Decode a Base64-URL string to data into a slice and return the slice with a valid length.
#[inline]
pub fn decode_in_place<'a, T: ?Sized + AsRef<[u8]>>(
    input: &T,
    output: &'a mut [u8],
) -> Result<&'a [u8], base64::DecodeError> {
    let length = base64::decode_config_slice(input, base64::URL_SAFE_NO_PAD, output)?;

    Ok(&output[..length])
}

/// Decode a Base64-URL string to data and directly store into a mutable `Vec<u8>` reference by concatenating them and return the slice of the decoded data.
#[inline]
pub fn decode_to_vec<'a, T: ?Sized + AsRef<[u8]>>(
    input: &T,
    output: &'a mut Vec<u8>,
) -> Result<&'a [u8], base64::DecodeError> {
    let bytes = input.as_ref();

    let current_length = output.len();

    let original_max_length = ((bytes.len() + 3) >> 2) * 3;

    let min_capacity = current_length + original_max_length;

    let capacity = output.capacity();

    if capacity < min_capacity {
        output.reserve(min_capacity - capacity);
    }

    unsafe {
        output.set_len(min_capacity);
    }

    let original_len = decode_in_place(bytes, &mut output[current_length..min_capacity])?.len();

    unsafe {
        output.set_len(current_length + original_len);
    }

    Ok(&output[current_length..])
}

#[deprecated(since = "1.4.0", note = "Please use the `decode_in_place` function instead")]
/// Decode a Base64-URL string to data into a slice and return the valid length.
#[inline]
pub fn decode_to_slice<T: ?Sized + AsRef<[u8]>>(
    input: &T,
    output: &mut [u8],
) -> Result<usize, base64::DecodeError> {
    Ok(decode_in_place(input, output)?.len())
}

#[deprecated(since = "1.4.0", note = "Please use the `decode_to_vec` function instead")]
/// Decode a Base64-URL string to data and directly store into a Vec instance by concatenating them.
#[inline]
pub fn decode_and_push_to_vec<T: ?Sized + AsRef<[u8]>>(
    input: &T,
    mut output: Vec<u8>,
) -> Result<Vec<u8>, base64::DecodeError> {
    decode_to_vec(input, &mut output)?;

    Ok(output)
}

#[deprecated(since = "1.4.0", note = "Please use the `decode_to_vec` function instead")]
/// Decode a Base64-URL string to data and directly store into a mutable Vec reference by concatenating them.
pub fn decode_and_push_to_vec_mut<T: ?Sized + AsRef<[u8]>>(
    input: &T,
    output: &mut Vec<u8>,
) -> Result<(), base64::DecodeError> {
    decode_to_vec(input, output)?;

    Ok(())
}