use encoding_rs::mem::{decode_latin1, encode_latin1_lossy, is_str_latin1};
use std::borrow::Cow;
pub trait StringWindows1252Ext {
fn from_windows_1252(bytes: Vec<u8>) -> Self;
}
impl StringWindows1252Ext for String {
fn from_windows_1252(bytes: Vec<u8>) -> Self {
match decode_latin1(&bytes) {
Cow::Borrowed(_) => unsafe { Self::from_utf8_unchecked(bytes) },
Cow::Owned(string) => string,
}
}
}
pub trait StrWindows1252Ext
where
Self: ToOwned,
{
fn from_windows_1252(bytes: &[u8]) -> Cow<'_, Self>;
fn encode_windows_1252(&self) -> Cow<'_, [u8]>;
}
impl StrWindows1252Ext for str {
fn from_windows_1252(bytes: &[u8]) -> Cow<'_, Self> {
decode_latin1(bytes)
}
fn encode_windows_1252(&self) -> Cow<'_, [u8]> {
if !is_str_latin1(self) {
panic!("string is unrepresentable in Windows-1252");
}
encode_latin1_lossy(self)
}
}