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
use super::*;
use base64::{engine::general_purpose::STANDARD, Engine};

pub fn base64_encode<T>(input: T) -> String
where
    T: AsRef<[u8]>,
{
    STANDARD.encode(input)
}

pub fn base64_decode<T>(input: T) -> AnyResult<String>
where
    T: AsRef<[u8]>,
{
    match STANDARD.decode(input) {
        Ok(result) => match std::str::from_utf8(&result) {
            Ok(output) => Ok(output.to_string()),
            Err(e) => Err(anyhow!("Failed to convert to UTF8: {}", e)),
        },
        Err(e) => Err(anyhow!("Failed to decode: {}", e)),
    }
}

pub fn base64_decode_mut(input: &mut String) -> AnyResult<()> {
    match STANDARD.decode(&input) {
        Ok(result) => match std::str::from_utf8(&result) {
            Ok(output) => {
                *input = output.to_owned();
                Ok(())
            }
            Err(e) => Err(anyhow!("Failed to convert to UTF8: {}", e)),
        },
        Err(e) => Err(anyhow!("Failed to decode: {}", e)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn encode() {
        eprintln!("Encoded: {}", base64_encode("ro_pass"));
    }

    #[test]
    fn decode() {
        let result = base64_decode("AABBCC");
        assert!(result.is_ok());
        eprintln!("Decoded: {}", result.unwrap());
    }
}