rust_auth_utils/
binary.rs1use encoding_rs::{Encoding, ISO_8859_10, UTF_8};
4use once_cell::sync::Lazy;
5use std::collections::HashMap;
6use std::sync::Mutex;
7
8#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
10pub enum EncodingType {
11 Utf8,
12 Iso885910,
13}
14impl EncodingType {
15 fn get_encoding(&self) -> &'static Encoding {
16 match self {
17 EncodingType::Utf8 => UTF_8,
18 EncodingType::Iso885910 => ISO_8859_10,
19 }
20 }
21}
22
23static DECODERS: Lazy<Mutex<HashMap<EncodingType, &'static Encoding>>> =
24 Lazy::new(|| Mutex::new(HashMap::new()));
25
26pub struct Binary;
27
28impl Binary {
29 pub fn decode(data: &[u8], encoding: EncodingType) -> String {
30 let mut decoders = DECODERS.lock().unwrap();
31
32 if !decoders.contains_key(&encoding) {
33 decoders.insert(encoding, encoding.get_encoding());
34 }
35
36 let encoder = decoders.get(&encoding).unwrap();
37 let (cow, _encoding_used, had_errors) = encoder.decode(data);
38
39 if had_errors {
40 eprintln!("Warning: Errors occurred during decoding");
41 }
42
43 cow.into_owned()
44 }
45
46 pub fn encode(text: &str) -> Vec<u8> {
47 Self::encode_with(text, EncodingType::Utf8)
48 }
49
50 pub fn encode_with(text: &str, encoding: EncodingType) -> Vec<u8> {
51 let encoder = encoding.get_encoding();
52 let (cow, _encoding_used, had_errors) = encoder.encode(text);
53
54 if had_errors {
55 eprintln!("Warning: Errors occurred during encoding");
56 }
57
58 cow.into_owned()
59 }
60}