//! Text decoding and guiding texts. //! //! ChessBase does not record the code page of its texts: a text is UTF-8 or a //! single-byte code page. A database is decoded with one single-byte code page, //! detected from all its texts at once, while each text that is valid UTF-8 (and //! not plain ASCII) is taken as UTF-8. use chess_core::{TextEncoding, detect_encoding}; use super::be; /// The byte ChessBase uses in single-byte texts to place a diagram. const DIAGRAM: u8 = 0x9e; /// The same marker in UTF-8 texts (a private-use character). const DIAGRAM_UTF8: char = '\u{e005}'; /// Where a text embeds an object (a diagram, a picture, a link to a game or chapter); /// what the object is lies in formatting data whose layout is unknown. pub const OBJECT: char = '\u{4}'; /// Piece figurines in single-byte texts: bytes 0xa2-0xa7 stand for K Q N B R and a pawn /// when a square or a capture follows ("¤f3", "¥:g4"). const FIGURINES_SINGLE: [&str; 6] = ["K", "Q", "N", "B", "R", ""]; /// Piece figurines in UTF-8 texts: U+E024-U+E029 stand for K Q R B N and a pawn. const FIGURINES_UTF8: [&str; 6] = ["K", "Q", "R", "B", "N", ""]; pub fn detect(sample: &[u8]) -> TextEncoding { match detect_encoding(sample).encoding { // All ASCII or UTF-8: single-byte texts (if any) are most likely Western. TextEncoding::Utf8 => TextEncoding::Windows1252, e => e, } } pub struct Decoder { single_byte: TextEncoding, } impl Decoder { pub fn new(single_byte: TextEncoding) -> Decoder { Decoder { single_byte } } /// A comment or a guiding text. Control characters are dropped, apart from line /// breaks, tabs and [`OBJECT`]. pub fn decode(&self, bytes: &[u8]) -> String { let mut s = self.decode_raw(bytes); s.retain(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t' | OBJECT)); s } fn decode_raw(&self, bytes: &[u8]) -> String { if !bytes.is_ascii() && let Ok(s) = std::str::from_utf8(bytes) { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { DIAGRAM_UTF8 => {} '\u{e024}'..='\u{e029}' => { out.push_str(FIGURINES_UTF8[(c as u32 - 0xe024) as usize]); } c => out.push(c), } } return out; } let mut cleaned = Vec::with_capacity(bytes.len()); for (i, &b) in bytes.iter().enumerate() { let next = bytes.get(i + 1).copied().unwrap_or(0); match b { DIAGRAM => {} 0xa2..=0xa7 if matches!(next, b'a'..=b'h' | b'x' | b':') => { cleaned.extend_from_slice(FIGURINES_SINGLE[usize::from(b - 0xa2)].as_bytes()); } b => cleaned.push(b), } } self.single_byte.decode(&cleaned).0.into_owned() } /// A name of a player, tournament or annotator. ChessBase stores names in a Western /// code page even in a database whose texts are Cyrillic, but a name may also be /// typed in Cyrillic: the reading that does not mix Latin and Cyrillic letters /// within a word wins ("Nürnberg", not "Nьrnberg"). pub fn decode_name(&self, bytes: &[u8]) -> String { let own = self.decode(bytes).replace(OBJECT, " "); if bytes.is_ascii() || std::str::from_utf8(bytes).is_ok() || !matches!( self.single_byte, TextEncoding::Windows1251 | TextEncoding::Koi8R | TextEncoding::Ibm866 ) { return own; } let mut western = TextEncoding::Windows1252.decode(bytes).0.into_owned(); western.retain(|c| !c.is_control()); if mixed_words(&western) < mixed_words(&own) { western } else { own } } } /// Words that contain both Latin and Cyrillic letters. fn mixed_words(s: &str) -> usize { s.split(|c: char| !c.is_alphanumeric()) .filter(|w| { let latin = w.chars().any(|c| c.is_alphabetic() && (c as u32) < 0x250); let cyrillic = w.chars().any(|c| ('\u{400}'..='\u{4ff}').contains(&c)); latin && cyrillic }) .count() } pub struct Body { pub title: String, pub text: String, } /// Reads a guiding text record from `.cbg`: titles and contents in one or more /// languages; the first of each is used. pub fn guiding_text(cbg: &[u8], offset: u32, d: &Decoder) -> Result
{ let at = offset as usize; let size = be(cbg, at + 1, 3).ok_or("text outside the .cbg file")? as usize; let rec = cbg.get(at..at + size).ok_or("text outside the .cbg file")?; let mut r = Le { data: rec, pos: 4 }; let bad = || "damaged guiding text".to_owned(); let version = r.u16().ok_or_else(bad)?; let mut title = String::new(); for i in 0..r.u16().ok_or_else(bad)? { let _lang = r.u16().ok_or_else(bad)?; let len = usize::from(r.u16().ok_or_else(bad)?); let t = r.take(len).ok_or_else(bad)?; if i == 0 { title = d.decode(t).trim().to_owned(); } } r.take(1).ok_or_else(bad)?; let mut text = String::new(); for i in 0..r.u16().ok_or_else(bad)? { let _lang = r.u16().ok_or_else(bad)?; let body = match version { 1 => { let len = usize::from(r.u16().ok_or_else(bad)?); let t = r.take(len).ok_or_else(bad)?; let fmt = usize::from(r.u16().ok_or_else(bad)?); r.take(fmt).ok_or_else(bad)?; tidy(&objects_to_breaks(&d.decode(t))) } 2 => { let len = r.u32().ok_or_else(bad)? as usize; let t = r.take(len).ok_or_else(bad)?; let fmt = r.u32().ok_or_else(bad)? as usize; r.take(fmt).ok_or_else(bad)?; tidy(&objects_to_breaks(&d.decode(t))) } 3 => { let len = r.u32().ok_or_else(bad)? as usize; let t = r.take(len).ok_or_else(bad)?; r.take(4); html_to_text(&d.decode(t).replace(OBJECT, " ")) } v => return Err(format!("guiding text format {v} is not supported")), }; if i == 0 { text = body; } } Ok(Body { title, text }) } struct Le<'a> { data: &'a [u8], pos: usize, } impl<'a> Le<'a> { fn take(&mut self, n: usize) -> Option<&'a [u8]> { let s = self.data.get(self.pos..self.pos + n)?; self.pos += n; Some(s) } fn u16(&mut self) -> OptionFirst line & more
Second
third ч