chromium_base64_rs/
encode.rs

1/// Encode base64 data into [`Vec<u8>`]
2pub fn base64_encode(data: &[u8]) -> Vec<u8> {
3    let length = data.len();
4
5    // Lookup table for btoa(), which converts a six-bit number into the
6    // corresponding ASCII character.
7    let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".as_bytes();
8    let btoa_lookup = |index: i16| {
9        return chars[index as usize]
10    };
11
12    let mut output: Vec<u8> = Vec::with_capacity(((4 * length / 3) + 3) & !3);
13    for i in (0..length).step_by(3) {
14        let mut groups_of_six: [i16; 4] = [-1; 4];
15        groups_of_six[0] = (data[i] >> 2) as i16;
16        groups_of_six[1] = ((data[i] & 0x03) << 4) as i16;
17
18        if length > i + 1 {
19            groups_of_six[1] |= (data[i + 1] >> 4) as i16;
20            groups_of_six[2] = ((data[i + 1] & 0x0f) << 2) as i16;
21        }
22
23        if length > i + 2 {
24            groups_of_six[2] |= (data[i + 2] >> 6) as i16;
25            groups_of_six[3] = (data[i + 2] & 0x3f) as i16;
26        }
27
28        for k in groups_of_six {
29            if k != -1 {
30                output.push(btoa_lookup(k));
31            } else {
32                // '='
33                output.push(61);
34            }
35        }
36    }
37
38    output
39}
40
41/// uses [`base64_encode`] and converts the result to [`String`]
42pub fn base64_encode_to_string(data: &[u8]) -> String {
43    String::from_utf8_lossy(&base64_encode(data)).to_string()
44}