use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Encoding {
Utf8,
Cp437,
ShiftJis,
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Encoding as T;
match self {
T::Utf8 => write!(f, "utf-8"),
T::Cp437 => write!(f, "cp-437"),
T::ShiftJis => write!(f, "shift-jis"),
}
}
}
#[derive(Debug)]
pub enum DecodingError {
Utf8Error(std::str::Utf8Error),
StringTooLarge,
EncodingError(&'static str),
}
impl From<std::str::Utf8Error> for DecodingError {
fn from(e: std::str::Utf8Error) -> Self {
DecodingError::Utf8Error(e)
}
}
impl Encoding {
pub(crate) fn decode(&self, i: &[u8]) -> Result<String, DecodingError> {
match self {
Encoding::Utf8 => {
let s = std::str::from_utf8(i)?;
Ok(s.to_string())
}
Encoding::Cp437 => {
use codepage_437::{BorrowFromCp437, CP437_CONTROL};
let s = String::borrow_from_cp437(i, &CP437_CONTROL);
Ok(s.to_string())
}
Encoding::ShiftJis => self.decode_as(i, encoding_rs::SHIFT_JIS),
}
}
fn decode_as(
&self,
i: &[u8],
encoding: &'static encoding_rs::Encoding,
) -> Result<String, DecodingError> {
let mut decoder = encoding.new_decoder();
let len = decoder
.max_utf8_buffer_length(i.len())
.ok_or(DecodingError::StringTooLarge)?;
let mut v = vec![0u8; len];
let last = true;
let (_decoder_result, _decoder_read, decoder_written, had_errors) =
decoder.decode_to_utf8(i, &mut v, last);
if had_errors {
return Err(DecodingError::EncodingError(encoding.name()));
}
v.resize(decoder_written, 0u8);
Ok(unsafe { String::from_utf8_unchecked(v) })
}
}
pub(crate) fn detect_utf8(input: &[u8]) -> (bool, bool) {
match std::str::from_utf8(input) {
Err(_) => {
(false, false)
}
Ok(s) => {
let mut require = false;
for c in s.chars() {
if c < 0x20 as char || c > 0x7d as char || c == 0x5c as char {
require = true
}
}
(true, require)
}
}
}