use encoding_rs::{Encoding, ISO_8859_10, UTF_8};
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub enum EncodingType {
Utf8,
Iso885910,
}
impl EncodingType {
fn get_encoding(&self) -> &'static Encoding {
match self {
EncodingType::Utf8 => UTF_8,
EncodingType::Iso885910 => ISO_8859_10,
}
}
}
static DECODERS: Lazy<Mutex<HashMap<EncodingType, &'static Encoding>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
pub struct Binary;
impl Binary {
pub fn decode(data: &[u8], encoding: EncodingType) -> String {
let mut decoders = DECODERS.lock().unwrap();
if !decoders.contains_key(&encoding) {
decoders.insert(encoding, encoding.get_encoding());
}
let encoder = decoders.get(&encoding).unwrap();
let (cow, _encoding_used, had_errors) = encoder.decode(data);
if had_errors {
eprintln!("Warning: Errors occurred during decoding");
}
cow.into_owned()
}
pub fn encode(text: &str) -> Vec<u8> {
Self::encode_with(text, EncodingType::Utf8)
}
pub fn encode_with(text: &str, encoding: EncodingType) -> Vec<u8> {
let encoder = encoding.get_encoding();
let (cow, _encoding_used, had_errors) = encoder.encode(text);
if had_errors {
eprintln!("Warning: Errors occurred during encoding");
}
cow.into_owned()
}
}