use encoding::all::GB18030;
use encoding::{DecoderTrap, Encoding};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum FileEncodingHint {
#[default]
Auto,
Utf8,
Gb18030,
}
pub(crate) fn decode(bytes: &[u8], hint: FileEncodingHint) -> String {
match hint {
FileEncodingHint::Utf8 => String::from_utf8_lossy(bytes).into_owned(),
FileEncodingHint::Gb18030 => decode_gb18030(bytes),
FileEncodingHint::Auto => match std::str::from_utf8(bytes) {
Ok(text) => text.to_owned(),
Err(_) => decode_gb18030(bytes),
},
}
}
fn decode_gb18030(bytes: &[u8]) -> String {
GB18030
.decode(bytes, DecoderTrap::Strict)
.unwrap_or_else(|_| String::from_utf8_lossy(bytes).into_owned())
}