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());
}
}