use std::sync::OnceLock;
pub const MAX_STRING_BYTES: usize = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Charset {
Latin1,
ShiftJisX0213,
EucKr,
EucCn,
Big5,
}
impl Charset {
pub fn from_code(code: u8) -> Charset {
match code & 7 {
3 => Charset::ShiftJisX0213,
4 => Charset::EucKr,
5 => Charset::EucCn,
6 => Charset::Big5,
_ => Charset::Latin1,
}
}
}
const NONE: u32 = u32::MAX;
const PAIR_FLAG: u32 = 0x8000_0000;
struct Table {
single: Vec<u32>,
pairs: Vec<u32>,
double: Vec<(u32, u32)>,
}
impl Table {
fn parse(src: &str) -> Table {
let mut t = Table { single: vec![NONE; 256], pairs: vec![NONE; 65536], double: Vec::new() };
for line in src.lines() {
let line = line.strip_suffix('\r').unwrap_or(line);
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((seq, cps)) = line.split_once('\t') else { continue };
let mut points = cps
.split(' ')
.filter_map(|c| c.strip_prefix("U+").and_then(|h| u32::from_str_radix(h, 16).ok()));
let (Some(first), second) = (points.next(), points.next()) else { continue };
let value = match second {
None => first,
Some(second) => {
let Ok(idx) = u32::try_from(t.double.len()) else { continue };
t.double.push((first, second));
PAIR_FLAG | idx
}
};
let Ok(key) = u16::from_str_radix(seq, 16) else { continue };
match seq.len() {
2 => {
if let Some(slot) = t.single.get_mut(usize::from(key)) {
*slot = value;
}
}
4 => {
if let Some(slot) = t.pairs.get_mut(usize::from(key)) {
*slot = value;
}
}
_ => {}
}
}
t
}
fn push(&self, value: u32, out: &mut String) {
if value & PAIR_FLAG != 0 {
let idx = (value & !PAIR_FLAG) as usize;
if let Some(&(a, b)) = self.double.get(idx) {
push_cp(a, out);
push_cp(b, out);
} else {
out.push('\u{FFFD}');
}
} else {
push_cp(value, out);
}
}
}
fn push_cp(cp: u32, out: &mut String) {
out.push(char::from_u32(cp).unwrap_or('\u{FFFD}'));
}
fn table(cs: Charset) -> Option<&'static Table> {
static SJIS: OnceLock<Table> = OnceLock::new();
static EUCKR: OnceLock<Table> = OnceLock::new();
static EUCCN: OnceLock<Table> = OnceLock::new();
static BIG5: OnceLock<Table> = OnceLock::new();
Some(match cs {
Charset::Latin1 => return None,
Charset::ShiftJisX0213 => {
SJIS.get_or_init(|| Table::parse(include_str!("../data/charsets/set3-shift-jisx0213.txt")))
}
Charset::EucKr => {
EUCKR.get_or_init(|| Table::parse(include_str!("../data/charsets/set4-euc-kr.txt")))
}
Charset::EucCn => {
EUCCN.get_or_init(|| Table::parse(include_str!("../data/charsets/set5-euc-cn.txt")))
}
Charset::Big5 => BIG5.get_or_init(|| Table::parse(include_str!("../data/charsets/set6-big5.txt"))),
})
}
const SJIS_RESERVED: [u16; 10] =
[0x879F, 0x889E, 0x9873, 0x989E, 0xEAA5, 0xEFF8, 0xEFF9, 0xEFFA, 0xEFFB, 0xEFFC];
pub fn decode(bytes: &[u8], cs: Charset) -> String {
let Some(t) = table(cs) else { return latin1(bytes) };
let mut out = String::with_capacity(bytes.len());
let mut i = 0usize;
while let Some(&b0) = bytes.get(i) {
if let Some(&b1) = bytes.get(i + 1) {
let pair = u16::from_be_bytes([b0, b1]);
let v = t.pairs.get(usize::from(pair)).copied().unwrap_or(NONE);
if v != NONE {
t.push(v, &mut out);
i += 2;
continue;
}
if cs == Charset::ShiftJisX0213 && SJIS_RESERVED.contains(&pair) {
out.push('\u{FFFD}');
i += 2;
continue;
}
}
let v = t.single.get(usize::from(b0)).copied().unwrap_or(NONE);
if v == NONE {
out.push('\u{FFFD}');
} else {
t.push(v, &mut out);
}
i += 1;
}
out
}
fn latin1(bytes: &[u8]) -> String {
if bytes.is_ascii() {
return String::from_utf8(bytes.to_vec()).unwrap_or_default();
}
let mut s = String::with_capacity(2 * bytes.len());
s.extend(bytes.iter().map(|&b| char::from(b)));
s
}
pub fn string_bytes(buf: &[u8], q: usize) -> &[u8] {
let end = q.saturating_add(MAX_STRING_BYTES).min(buf.len());
let Some(range) = buf.get(q..end) else { return &[] };
let len = range.iter().position(|&b| b == 0).unwrap_or(range.len());
range.get(..len).unwrap_or(range)
}
pub fn decode_string(bytes: &[u8], cs: Charset) -> Option<String> {
let mut s = decode(bytes, cs);
if s.bytes().any(|b| b < 0x20) {
s = s.replace(|c: char| c < '\u{20}', " ");
}
(!s.is_empty()).then_some(s)
}
pub fn text_string(buf: &[u8], q: usize, cs: Charset) -> Option<String> {
decode_string(string_bytes(buf, q), cs)
}
fn is_w(c: char) -> bool {
matches!(
c,
'\u{09}'..='\u{0D}' | '\u{1C}'..='\u{20}' | '\u{85}' | '\u{A0}'
)
}
pub fn fixed_text(field: &[u8]) -> String {
let bytes = fixed_bytes(field);
let start = bytes.iter().position(|&b| !is_w(char::from(b))).unwrap_or(bytes.len());
let end = bytes.iter().rposition(|&b| !is_w(char::from(b))).map_or(start, |i| i + 1);
latin1(bytes.get(start..end).unwrap_or_default())
}
pub fn fixed_bytes(field: &[u8]) -> &[u8] {
let len = field.iter().position(|&b| b == 0).unwrap_or(field.len());
field.get(..len).unwrap_or(field)
}
pub fn language(code: [u8; 2]) -> String {
let s: String = code.iter().map(|&b| char::from(b)).collect();
s.trim_end_matches(['\u{0}', ' ']).to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn latin1_and_controls() {
assert_eq!(decode_string(b"a\x01\x7f\xe9", Charset::Latin1).unwrap(), "a \u{7f}\u{e9}");
assert_eq!(decode_string(b"", Charset::Latin1), None);
assert_eq!(Charset::from_code(0xFF), Charset::Latin1);
assert_eq!(Charset::from_code(0x0B), Charset::ShiftJisX0213);
}
fn decode_string_before(bytes: &[u8], cs: Charset) -> Option<String> {
let s: String = decode(bytes, cs).chars().map(|c| if c < '\u{20}' { ' ' } else { c }).collect();
(!s.is_empty()).then_some(s)
}
fn fixed_text_before(field: &[u8]) -> String {
let s: String = fixed_bytes(field).iter().map(|&b| char::from(b)).collect();
s.trim_matches(is_w).to_owned()
}
#[test]
fn latin1_decoding_is_unchanged() {
let every: Vec<u8> = (0..=255).collect();
let mut cases: Vec<Vec<u8>> = vec![every.clone(), b"plain ASCII".to_vec(), Vec::new()];
cases.extend(every.iter().map(|&b| vec![b' ', b, b'x', b, 0x85, 0xA0]));
cases.extend(every.iter().map(|&b| vec![b]));
for bytes in &cases {
assert_eq!(decode_string(bytes, Charset::Latin1), decode_string_before(bytes, Charset::Latin1));
assert_eq!(fixed_text(bytes), fixed_text_before(bytes), "{bytes:?}");
}
}
#[test]
#[cfg_attr(miri, ignore = "parses large tables")]
fn table_decoding_is_unchanged() {
let bytes: Vec<u8> = (0..4096u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
for cs in [Charset::ShiftJisX0213, Charset::EucKr, Charset::EucCn, Charset::Big5] {
for chunk in bytes.chunks(97) {
assert_eq!(decode_string(chunk, cs), decode_string_before(chunk, cs), "{cs:?}");
}
}
}
#[test]
fn string_bytes_bounds() {
let buf = [b'a'; 5000];
assert_eq!(string_bytes(&buf, 0).len(), 4096);
assert_eq!(string_bytes(&buf, 4990).len(), 10);
assert_eq!(string_bytes(&buf, 5000).len(), 0);
assert_eq!(string_bytes(&buf, usize::MAX).len(), 0);
assert_eq!(string_bytes(b"ab\0cd", 0), b"ab");
}
#[test]
fn fixed_text_and_language() {
assert_eq!(fixed_text(b" \x85AB C\xa0\0junk"), "AB C");
assert_eq!(fixed_text(b"\x01X\x01"), "\u{1}X\u{1}");
assert_eq!(fixed_bytes(b" \x85AB C\xa0\0junk"), b" \x85AB C\xa0");
assert_eq!(fixed_bytes(b"AB "), b"AB ");
assert_eq!(fixed_bytes(b"\0AB"), b"");
assert_eq!(language(*b"e\0"), "e");
assert_eq!(language([0, b'e']), "\u{0}e");
assert_eq!(language(*b" "), "");
}
#[test]
#[cfg_attr(miri, ignore = "parses large tables")]
fn notable_table_positions() {
let sj = Charset::ShiftJisX0213;
assert_eq!(decode(b"\x5c\x7e", sj), "\u{a5}\u{203e}");
assert_eq!(decode(b"\x81\x5f\x81\x60", sj), "\u{5c}\u{301c}");
assert_eq!(decode(b"\x87\x9f", sj), "\u{fffd}");
assert_eq!(decode(b"\x81", sj), "\u{fffd}");
assert_eq!(decode(&[0xA1, 0xA4, 0xA1, 0xAA], Charset::EucCn), "\u{30fb}\u{2015}");
assert_eq!(decode(&[0xA1, 0x45, 0xA2, 0x44], Charset::Big5), "\u{2022}\u{a5}");
assert_eq!(decode(&[0xA2, 0xE6], Charset::EucKr), "\u{20ac}");
assert_eq!(decode(&[0xA4, 0xD4, b'a'], Charset::EucKr).chars().next(), Some('\u{fffd}'));
}
#[test]
#[cfg_attr(miri, ignore = "parses large tables")]
fn tables_have_documented_sizes() {
for (cs, src) in [
(Charset::ShiftJisX0213, include_str!("../data/charsets/set3-shift-jisx0213.txt")),
(Charset::EucKr, include_str!("../data/charsets/set4-euc-kr.txt")),
(Charset::EucCn, include_str!("../data/charsets/set5-euc-cn.txt")),
(Charset::Big5, include_str!("../data/charsets/set6-big5.txt")),
] {
let t = table(cs).unwrap();
let singles = t.single.iter().filter(|&&v| v != NONE).count();
let pairs = t.pairs.iter().filter(|&&v| v != NONE).count();
let header = src.lines().find(|l| l.contains("single-byte and")).unwrap();
let expected = format!("# {singles} single-byte and {pairs} two-byte entries.");
assert_eq!(header, expected, "{cs:?}");
}
}
}