use alloc::{string::String, vec::Vec};
pub use crate::charsets::Charset;
pub use crate::decode::Decoder;
pub use crate::multibyte::MultiByte;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Encoding {
Utf8,
Utf8Bom,
Utf16Le,
Utf16Be,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Invalid,
Unsupported,
Limit,
Unmappable(char),
}
pub fn decode(bytes: &[u8], limit: usize) -> Result<(String, Encoding), Error> {
if bytes.len() > limit {
return Err(Error::Limit);
}
if bytes.starts_with(&[0xff, 0xfe, 0, 0]) || bytes.starts_with(&[0, 0, 0xfe, 0xff]) {
return Err(Error::Unsupported);
}
let (b, enc) = if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
(&bytes[3..], Encoding::Utf8Bom)
} else if bytes.starts_with(&[0xff, 0xfe]) {
(&bytes[2..], Encoding::Utf16Le)
} else if bytes.starts_with(&[0xfe, 0xff]) {
(&bytes[2..], Encoding::Utf16Be)
} else {
(bytes, Encoding::Utf8)
};
let text = match enc {
Encoding::Utf8 | Encoding::Utf8Bom => {
String::from(core::str::from_utf8(b).map_err(|_| Error::Invalid)?)
}
_ => {
if b.len() % 2 != 0 {
return Err(Error::Invalid);
}
let units = b.chunks_exact(2).map(|p| {
if enc == Encoding::Utf16Le {
u16::from_le_bytes([p[0], p[1]])
} else {
u16::from_be_bytes([p[0], p[1]])
}
});
let mut s = String::new();
for c in core::char::decode_utf16(units) {
s.push(c.map_err(|_| Error::Invalid)?);
}
s
}
};
if text.len() > limit {
return Err(Error::Limit);
}
Ok((text, enc))
}
pub fn encode(text: &str, enc: Encoding) -> Vec<u8> {
let mut out = Vec::new();
match enc {
Encoding::Utf8 => out.extend_from_slice(text.as_bytes()),
Encoding::Utf8Bom => {
out.extend_from_slice(&[0xef, 0xbb, 0xbf]);
out.extend_from_slice(text.as_bytes());
}
Encoding::Utf16Le | Encoding::Utf16Be => {
out.extend_from_slice(if enc == Encoding::Utf16Le {
&[0xff, 0xfe]
} else {
&[0xfe, 0xff]
});
for u in text.encode_utf16() {
out.extend_from_slice(&if enc == Encoding::Utf16Le {
u.to_le_bytes()
} else {
u.to_be_bytes()
});
}
}
}
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Label {
Utf8,
Utf16Le,
Utf16Be,
Single(Charset),
Multi(MultiByte),
Replacement,
}
impl Label {
pub const fn name(self) -> &'static str {
match self {
Label::Utf8 => "UTF-8",
Label::Utf16Le => "UTF-16LE",
Label::Utf16Be => "UTF-16BE",
Label::Single(c) => c.name(),
Label::Multi(m) => m.name(),
Label::Replacement => "replacement",
}
}
}
pub fn from_code_page(cp: u16) -> Option<Label> {
match cp {
65001 => Some(Label::Utf8),
1200 => Some(Label::Utf16Le),
1201 => Some(Label::Utf16Be),
_ => Charset::from_code_page(cp).map(Label::Single).or_else(|| MultiByte::from_code_page(cp).map(Label::Multi)),
}
}
pub fn label(name: &str) -> Option<Label> {
let t = name.trim_matches(|c| matches!(c, '\t' | '\n' | '\x0C' | '\r' | ' '));
if t.is_empty() || t.len() > 32 || !t.is_ascii() {
return None;
}
let mut buf = [0u8; 32];
for (d, s) in buf.iter_mut().zip(t.bytes()) {
*d = s.to_ascii_lowercase();
}
crate::charsets::lookup(core::str::from_utf8(&buf[..t.len()]).ok()?)
}
pub fn decode_label(label: &str, bytes: &[u8], limit: usize) -> Result<String, Error> {
if bytes.len() > limit {
return Err(Error::Limit);
}
let (named, body) = if let Some(rest) = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]) {
(Some(Label::Utf8), rest)
} else if let Some(rest) = bytes.strip_prefix(&[0xff, 0xfe]) {
(Some(Label::Utf16Le), rest)
} else if let Some(rest) = bytes.strip_prefix(&[0xfe, 0xff]) {
(Some(Label::Utf16Be), rest)
} else {
(self::label(label), bytes)
};
let named = named.ok_or(Error::Unsupported)?;
let cap = if named == Label::Replacement { 0 } else { body.len().min(limit) + body.len().min(limit) / 2 };
let mut text = String::with_capacity(cap);
Decoder::new(named).decode(body, true, &mut text);
if text.len() > limit {
return Err(Error::Limit);
}
Ok(text)
}
impl Charset {
pub fn from_label(name: &str) -> Option<Charset> {
match label(name)? {
Label::Single(c) => Some(c),
_ => None,
}
}
pub fn decode(self, bytes: &[u8]) -> String {
if bytes.is_ascii() {
return String::from(core::str::from_utf8(bytes).unwrap_or(""));
}
let t = self.table();
let mut s = String::with_capacity(bytes.len() + bytes.len() / 2);
for &b in bytes {
s.push(if b < 0x80 { b as char } else { char_of(t[b as usize - 0x80]).unwrap_or(char::REPLACEMENT_CHARACTER) });
}
s
}
pub fn decode_char(self, b: u8) -> Option<char> {
if b < 0x80 {
Some(b as char)
} else {
char_of(self.table()[b as usize - 0x80])
}
}
pub fn encode_char(self, c: char) -> Option<u8> {
let u = c as u32;
if u < 0x80 {
return Some(u as u8);
}
self.table().iter().position(|&v| v != 0 && v as u32 == u).map(|i| 0x80 + i as u8)
}
pub fn encode(self, text: &str) -> Result<Vec<u8>, Error> {
let mut out = Vec::with_capacity(text.len());
for c in text.chars() {
out.push(self.encode_char(c).ok_or(Error::Unmappable(c))?);
}
Ok(out)
}
}
fn char_of(v: u16) -> Option<char> {
if v == 0 {
None
} else {
char::from_u32(v as u32)
}
}