use std::io::{self, Read};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
pub struct Base64Utils;
impl Base64Utils {
pub fn encode(input: &str) -> String {
STANDARD.encode(input)
}
pub fn decode(input: &str) -> Result<String, base64::DecodeError> {
STANDARD
.decode(input.trim()) .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
}
pub fn encode_from_stdin() -> Result<(), Box<dyn std::error::Error>> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let encoded = Self::encode(&input);
println!("{}", encoded);
Ok(())
}
pub fn decode_to_stdout() -> Result<(), Box<dyn std::error::Error>> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
match Self::decode(&input) {
Ok(decoded) => println!("{}", decoded),
Err(e) => eprintln!("Error decoding Base64: {}", e),
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Base64Utils;
#[test]
fn test_base64_encode() {
let input = "Hello, Rust!";
let encoded = Base64Utils::encode(input);
assert_eq!(encoded, "SGVsbG8sIFJ1c3Qh");
}
#[test]
fn test_base64_decode() {
let input = "SGVsbG8sIFJ1c3Qh";
let decoded = Base64Utils::decode(input).unwrap();
assert_eq!(decoded, "Hello, Rust!");
}
#[test]
fn test_base64_decode_invalid() {
let input = "Invalid_Base64!";
assert!(Base64Utils::decode(input).is_err());
}
}
#[test]
fn main() {
let original = "API:a123456";
let encoded = Base64Utils::encode(original);
println!("Encoded: {}", encoded);
match Base64Utils::decode(&encoded) {
Ok(decoded) => println!("Decoded: {}", decoded),
Err(e) => println!("Error: {}", e),
}
}