mycommon_utils/utils/
base64.rs1use std::io::{self, Read};
2use base64::engine::general_purpose::STANDARD;
3use base64::Engine;
4
5pub struct Base64Utils;
6
7impl Base64Utils {
8 pub fn encode(input: &str) -> String {
10 STANDARD.encode(input)
11 }
12
13 pub fn decode(input: &str) -> Result<String, base64::DecodeError> {
15 STANDARD
16 .decode(input.trim()) .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
18 }
19
20 pub fn encode_from_stdin() -> Result<(), Box<dyn std::error::Error>> {
22 let mut input = String::new();
23 io::stdin().read_to_string(&mut input)?;
24 let encoded = Self::encode(&input);
25 println!("{}", encoded);
26 Ok(())
27 }
28
29 pub fn decode_to_stdout() -> Result<(), Box<dyn std::error::Error>> {
31 let mut input = String::new();
32 io::stdin().read_to_string(&mut input)?;
33 match Self::decode(&input) {
34 Ok(decoded) => println!("{}", decoded),
35 Err(e) => eprintln!("Error decoding Base64: {}", e),
36 }
37 Ok(())
38 }
39}
40
41#[cfg(test)]
42mod tests {
43 use super::Base64Utils;
44
45 #[test]
46 fn test_base64_encode() {
47 let input = "Hello, Rust!";
48 let encoded = Base64Utils::encode(input);
49 assert_eq!(encoded, "SGVsbG8sIFJ1c3Qh");
50 }
51
52 #[test]
53 fn test_base64_decode() {
54 let input = "SGVsbG8sIFJ1c3Qh";
55 let decoded = Base64Utils::decode(input).unwrap();
56 assert_eq!(decoded, "Hello, Rust!");
57 }
58
59 #[test]
60 fn test_base64_decode_invalid() {
61 let input = "Invalid_Base64!";
62 assert!(Base64Utils::decode(input).is_err());
63 }
64}
65
66#[test]
67fn main() {
68 let original = "API:a123456";
70 let encoded = Base64Utils::encode(original);
71 println!("Encoded: {}", encoded);
72
73 match Base64Utils::decode(&encoded) {
74 Ok(decoded) => println!("Decoded: {}", decoded),
75 Err(e) => println!("Error: {}", e),
76 }
77
78 }