mycommon-utils 0.1.2

Common utilities library for database operations, Redis caching and system utilities
Documentation
use std::io::{self, Read};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;

pub struct Base64Utils;

impl Base64Utils {
    /// 将字符串编码为 Base64
    pub fn encode(input: &str) -> String {
        STANDARD.encode(input)
    }

    /// 将 Base64 字符串解码为原始字符串
    pub fn decode(input: &str) -> Result<String, base64::DecodeError> {
        STANDARD
            .decode(input.trim()) // 修正标准输入可能带来的换行符问题
            .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
    }

    /// 从标准输入读取数据并编码为 Base64,输出到标准输出
    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(())
    }

    /// 从标准输入读取 Base64 数据并解码为原始字符串,输出到标准输出
    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),
    }

    // 与标准输入交互
    // println!("Enter a string to encode (Ctrl+D to end input):");
    // if let Err(e) = Base64Utils::encode_from_stdin() {
    //     eprintln!("Error: {}", e);
    // }

    // println!("Enter a Base64 string to decode (Ctrl+D to end input):");
    // if let Err(e) = Base64Utils::decode_to_stdout() {
    //     eprintln!("Error: {}", e);
    // }
}