Open ChessBase databases (.cbh, .cbv) and zip/7z archives
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

New crate chess-import converts non-PGN sources to PGN in memory and returns
a PgnDatabase, so the library, notation and analysis work unchanged:
- .cbv archives (container rewritten after uncbv), .cbh with companion files
  (layout after the public Morphy format description): games, variations,
  comments with per-database code page detection, NAGs, squares/arrows, set-up
  positions, time spent, book chapters (guiding texts) as move-less records;
- ChessBase figurines become piece letters, diagram/object markers handled,
  Western names in Cyrillic databases read correctly;
- .zip/.7z with PGN (own encoding each), .cbh and .cbv; duplicates skipped;
- .cbz/encrypted archives and 2CBH rejected with clear messages.
Library: '+ Add database', format shown, import notes; comments keep
paragraph breaks. Tests on the user's sample books (skipped when absent).

Also: AUR PKGBUILD for 0.2.0 with the bundled Stockfish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubel 2026-10-18 13:18:27 +03:00
parent 26bf901124
commit bb7d3b3fa6
31 changed files with 3618 additions and 64 deletions

View file

@ -0,0 +1,198 @@
//! `.cba`: the annotations of a game, each attached to a move by its position in the
//! stored move order (−1 = the game as a whole). Big-endian.
use std::collections::BTreeMap;
use super::be;
use super::headers::Record;
use super::text::Decoder;
/// What can be shown in PGN. Other annotation types (training, game quotations,
/// pictures, clocks, …) are skipped.
#[derive(Clone, Debug, PartialEq)]
pub enum Item {
Before(String),
After(String),
Nags(Vec<u8>),
/// (colour letter, square index a1 = 0)
Squares(Vec<(char, u8)>),
Arrows(Vec<(char, u8, u8)>),
/// Time spent on the move: h, m, s.
TimeSpent(u8, u8, u8),
}
#[derive(Clone, Debug, Default)]
pub struct Annotations {
pub at: BTreeMap<i32, Vec<Item>>,
}
struct Raw<'a> {
position: i32,
kind: u8,
data: &'a [u8],
}
const RECORD_HEADER: usize = 14;
fn parse(cba: &[u8], offset: u32) -> Result<(u32, Vec<Raw<'_>>), String> {
let at = offset as usize;
let (Some(game), Some(size)) = (be(cba, at, 3), be(cba, at + 10, 4)) else {
return Err("annotations outside the .cba file".into());
};
let record = cba
.get(at..at + size as usize)
.filter(|r| r.len() >= RECORD_HEADER)
.ok_or("annotations outside the .cba file")?;
let mut items = Vec::new();
let mut i = RECORD_HEADER;
while i + 6 <= record.len() {
let pos = be(record, i, 3).unwrap_or(0);
// Sign-extend the 24-bit position.
let position = ((pos << 8) as i32) >> 8;
let kind = record[i + 3];
let len = be(record, i + 4, 2).unwrap_or(0) as usize;
if len < 6 || i + len > record.len() {
return Err("damaged annotation record".into());
}
items.push(Raw {
position,
kind,
data: &record[i + 6..i + len],
});
i += len;
}
Ok((game, items))
}
/// Adds the text bytes of every game's annotations to `buf` (for code page detection).
pub fn sample_texts(cba: &[u8], records: &[Record], buf: &mut Vec<u8>) {
for r in records {
if let Record::Game(h) = r
&& h.annotations_offset > 0
&& let Ok((_, items)) = parse(cba, h.annotations_offset)
{
for it in items {
if matches!(it.kind, 0x02 | 0x82) && it.data.len() > 2 {
buf.extend_from_slice(&it.data[2..]);
buf.push(b' ');
}
}
}
}
}
pub fn read(cba: &[u8], offset: u32, game_id: usize, d: &Decoder) -> Result<Annotations, String> {
let (game, items) = parse(cba, offset)?;
if game as usize != game_id {
return Err("annotations belong to another game".into());
}
let mut out = Annotations::default();
for it in items {
let item = match it.kind {
0x02 | 0x82 => {
let text = d
.decode(it.data.get(2..).unwrap_or(&[]))
.replace(super::text::OBJECT, " ")
.replace("\r\n", "\n")
.replace('\r', "\n");
let text = text.trim();
if text.is_empty() {
continue;
}
if it.kind == 0x02 {
Item::After(text.to_owned())
} else {
Item::Before(text.to_owned())
}
}
0x03 => {
let nags: Vec<u8> = it.data.iter().copied().filter(|n| *n != 0).collect();
if nags.is_empty() {
continue;
}
Item::Nags(nags)
}
0x04 => Item::Squares(
it.data
.as_chunks::<2>()
.0
.iter()
.filter_map(|c| Some((colour(c[0])?, c[1].checked_sub(1)?)))
.filter(|(_, sq)| *sq < 64)
.collect(),
),
0x05 => Item::Arrows(
it.data
.as_chunks::<3>()
.0
.iter()
.filter_map(|c| {
Some((colour(c[0])?, c[1].checked_sub(1)?, c[2].checked_sub(1)?))
})
.filter(|(_, a, b)| *a < 64 && *b < 64)
.collect(),
),
0x07 if it.data.len() >= 3 => Item::TimeSpent(it.data[0], it.data[1], it.data[2]),
_ => continue,
};
out.at.entry(it.position).or_default().push(item);
}
Ok(out)
}
/// ChessBase colours 2 green, 3 yellow, 4 red as PGN `%csl`/`%cal` letters.
fn colour(c: u8) -> Option<char> {
match c {
2 => Some('G'),
3 => Some('Y'),
4 => Some('R'),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use chess_core::TextEncoding;
fn ann(position: i32, kind: u8, data: &[u8]) -> Vec<u8> {
let mut v = (position as u32).to_be_bytes()[1..].to_vec();
v.push(kind);
v.extend_from_slice(&((data.len() + 6) as u16).to_be_bytes());
v.extend_from_slice(data);
v
}
#[test]
fn reads_texts_symbols_and_graphics() {
let mut body = Vec::new();
body.extend(ann(-1, 0x02, b"\x00\x00Intro"));
body.extend(ann(0, 0x03, &[1, 0, 0]));
body.extend(ann(0, 0x02, &[0, 0, 0xd0, 0xe0, 0xe7, 0x9e]));
body.extend(ann(1, 0x04, &[2, 1, 4, 64]));
body.extend(ann(1, 0x05, &[3, 13, 29, 9, 1, 2]));
let size = (RECORD_HEADER + body.len()) as u32;
let mut cba = vec![0u8; 26];
let offset = cba.len() as u32;
cba.extend_from_slice(&[0, 0, 7, 1, 0, 0x0e, 0x0e, 0, 0, 6]);
cba.extend_from_slice(&size.to_be_bytes());
cba.extend(body);
let d = Decoder::new(TextEncoding::Windows1251);
let a = read(&cba, offset, 7, &d).expect("record");
assert_eq!(a.at[&-1], vec![Item::After("Intro".into())]);
assert_eq!(
a.at[&0],
vec![Item::Nags(vec![1]), Item::After("Раз".into())],
"cp1251 text, diagram marker removed"
);
assert_eq!(
a.at[&1],
vec![
Item::Squares(vec![('G', 0), ('R', 63)]),
Item::Arrows(vec![('Y', 12, 28)]),
],
"unknown colour 9 dropped"
);
assert!(read(&cba, offset, 8, &d).is_err(), "wrong game id");
}
}

View file

@ -0,0 +1,109 @@
//! `.cbp` players, `.cbt` tournaments, `.cbc` annotators: fixed-size records after a
//! small little-endian header; an entity id is the record's index.
use super::le_i32;
use super::text::Decoder;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Player,
Tournament,
Annotator,
}
/// Raw string fields of every record (decoded later, once the code page is known).
#[derive(Clone, Debug, Default)]
pub struct Entities {
kind: Option<Kind>,
records: Vec<Vec<Vec<u8>>>,
/// Tournament start dates (packed), by id.
dates: Vec<u32>,
}
/// Node of the tree (9 bytes) before the data of each record.
const NODE: usize = 9;
pub fn read(bytes: Option<&[u8]>, kind: Kind) -> Entities {
let mut out = Entities {
kind: Some(kind),
..Entities::default()
};
let Some(bytes) = bytes else { return out };
let (Some(count), Some(data_size), Some(extra)) =
(le_i32(bytes, 0), le_i32(bytes, 0x0c), le_i32(bytes, 0x18))
else {
return out;
};
let header = 28 + usize::try_from(extra).unwrap_or(0).min(4);
let Ok(record) = usize::try_from(data_size).map(|d| d + NODE) else {
return out;
};
// Fields: (offset in data, length).
let fields: &[(usize, usize)] = match kind {
Kind::Player => &[(0x00, 30), (0x1e, 20)],
Kind::Tournament => &[(0x00, 40), (0x28, 30)],
Kind::Annotator => &[(0x00, 45)],
};
for i in 0..usize::try_from(count).unwrap_or(0) {
let Some(rec) = bytes.get(header + i * record..header + (i + 1) * record) else {
break;
};
let data = &rec[NODE..];
out.records.push(
fields
.iter()
.map(|&(at, len)| {
let f = data.get(at..at + len).unwrap_or(&[]);
let end = f.iter().position(|b| *b == 0).unwrap_or(f.len());
f[..end].to_vec()
})
.collect(),
);
if kind == Kind::Tournament {
out.dates.push(
le_i32(data, 0x46)
.and_then(|d| u32::try_from(d).ok())
.unwrap_or(0),
);
}
}
out
}
impl Entities {
pub fn sample(&self, buf: &mut Vec<u8>) {
for rec in &self.records {
for f in rec {
buf.extend_from_slice(f);
buf.push(b' ');
}
}
}
fn field(&self, id: u32, i: usize, d: &Decoder) -> Option<String> {
let f = self.records.get(id as usize)?.get(i)?;
let s = d.decode_name(f).trim().to_owned();
(!s.is_empty()).then_some(s)
}
/// "Last, First" for a player; the title of a tournament; an annotator's name.
pub fn name(&self, id: u32, d: &Decoder) -> Option<String> {
let first = self.field(id, 0, d);
if self.kind == Some(Kind::Player) {
return match (first, self.field(id, 1, d)) {
(Some(last), Some(given)) => Some(format!("{last}, {given}")),
(last, given) => last.or(given),
};
}
first
}
/// Tournament place.
pub fn place(&self, id: u32, d: &Decoder) -> Option<String> {
self.field(id, 1, d)
}
pub fn date(&self, id: u32) -> u32 {
self.dates.get(id as usize).copied().unwrap_or(0)
}
}

View file

@ -0,0 +1,149 @@
//! `.cbh`: one 46-byte record per game or guiding text (big-endian).
use super::be;
use crate::ImportError;
const RECORD: usize = 46;
#[derive(Clone, Debug)]
pub enum Record {
Game(GameHeader),
Text(TextHeader),
Deleted,
}
#[derive(Clone, Debug, Default)]
pub struct GameHeader {
pub moves_offset: u32,
pub annotations_offset: u32,
pub white: u32,
pub black: u32,
pub tournament: u32,
pub annotator: u32,
pub date: u32,
pub result: u8,
pub round: u8,
pub subround: u8,
pub white_elo: u16,
pub black_elo: u16,
pub eco: u16,
}
#[derive(Clone, Debug, Default)]
pub struct TextHeader {
pub text_offset: u32,
pub tournament: u32,
pub annotator: u32,
pub round: u8,
pub subround: u8,
}
pub fn read(cbh: &[u8]) -> Result<Vec<Record>, ImportError> {
if cbh.len() < RECORD || be(cbh, 3, 2) != Some(RECORD as u32) {
return Err(ImportError::Corrupt(
"ChessBase database: the .cbh file has an unknown layout".into(),
));
}
let mut out = Vec::new();
for rec in cbh[RECORD..].as_chunks::<RECORD>().0 {
let kind = rec[0];
if kind & 1 == 0 {
// All-zero records lie past the last game.
break;
}
let u = |at, n| be(rec.as_slice(), at, n).unwrap_or(0);
out.push(if kind & 0x80 != 0 {
Record::Deleted
} else if kind & 0x02 != 0 {
Record::Text(TextHeader {
text_offset: u(0x01, 4),
tournament: u(0x07, 3),
annotator: u(0x0d, 3),
round: rec[0x10],
subround: rec[0x11],
})
} else {
Record::Game(GameHeader {
moves_offset: u(0x01, 4),
annotations_offset: u(0x05, 4),
white: u(0x09, 3),
black: u(0x0c, 3),
tournament: u(0x0f, 3),
annotator: u(0x12, 3),
date: u(0x18, 3),
result: rec[0x1b],
round: rec[0x1d],
subround: rec[0x1e],
white_elo: u(0x1f, 2) as u16,
black_elo: u(0x21, 2) as u16,
eco: u(0x23, 2) as u16,
})
});
}
Ok(out)
}
impl GameHeader {
pub fn result_tag(&self) -> &'static str {
match self.result {
0 | 4 => "0-1",
1 | 5 => "1/2-1/2",
2 | 6 => "1-0",
_ => "*",
}
}
/// "C41" (sub-codes are ChessBase-specific and dropped); `None` for no ECO or Chess960.
pub fn eco_tag(&self) -> Option<String> {
if self.eco == 0 || self.eco >= 64576 {
return None;
}
let code = usize::from(self.eco / 128).checked_sub(1)?;
let letter = *b"ABCDE".get(code / 100)?;
Some(format!("{}{:02}", letter as char, code % 100))
}
}
/// "1858.??.??" from a packed date (day bits 0-4, month 5-8, year 9-20).
pub fn date_tag(packed: u32) -> String {
let (day, month, year) = (packed & 31, (packed >> 5) & 15, (packed >> 9) & 0xfff);
let part = |v: u32, w: usize| {
if v == 0 {
"?".repeat(w)
} else {
format!("{v:0w$}")
}
};
format!("{}.{}.{}", part(year, 4), part(month, 2), part(day, 2))
}
pub fn round_tag(round: u8, subround: u8) -> String {
match (round, subround) {
(0, _) => "?".into(),
(r, 0) => r.to_string(),
(r, s) => format!("{r}.{s}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_eco_and_rounds() {
assert_eq!(date_tag((1905 << 9) | (8 << 5) | 31), "1905.08.31");
assert_eq!(date_tag(1907 << 9), "1907.??.??");
assert_eq!(date_tag(0), "????.??.??");
let h = |eco| GameHeader {
eco,
..GameHeader::default()
};
assert_eq!(h((201 + 1) * 128 + 5).eco_tag().as_deref(), Some("C01"));
assert_eq!(h(128).eco_tag().as_deref(), Some("A00"));
assert_eq!(h(0).eco_tag(), None);
assert_eq!(h(64576).eco_tag(), None);
assert_eq!(round_tag(0, 0), "?");
assert_eq!(round_tag(3, 0), "3");
assert_eq!(round_tag(3, 2), "3.2");
}
}

View file

@ -0,0 +1,235 @@
//! ChessBase databases (`.cbh` and companion files) converted to PGN text.
//!
//! The layout follows the public format description of the Morphy project
//! (`format/v1` in github.com/Yarin78/morphy), used as a source of facts; no code is taken
//! from it. Only reading is supported, and the source files are never written.
mod annotations;
mod entities;
mod headers;
mod moves;
mod text;
mod writer;
use std::collections::HashMap;
use std::path::Path;
use chess_core::TextEncoding;
use crate::ImportError;
/// The files of one database, by lower-case extension (`cbh`, `cbg`, …).
#[derive(Clone, Debug, Default)]
pub struct Files {
pub name: String,
files: HashMap<String, Vec<u8>>,
}
impl Files {
/// Reads `<dir>/<stem>.<ext>` for every extension the reader uses.
pub fn from_dir(cbh: &Path) -> Result<Files, ImportError> {
let dir = cbh.parent().unwrap_or(Path::new("."));
let stem = cbh
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let mut files = Files {
name: stem.clone(),
files: HashMap::new(),
};
let entries = std::fs::read_dir(dir).map_err(|source| ImportError::Io {
path: dir.to_owned(),
source,
})?;
for e in entries.flatten() {
let p = e.path();
let (Some(s), Some(ext)) = (p.file_stem(), p.extension()) else {
continue;
};
let ext = ext.to_string_lossy().to_ascii_lowercase();
if s.to_string_lossy() == stem && USED.contains(&ext.as_str()) {
let bytes = std::fs::read(&p).map_err(|source| ImportError::Io {
path: p.clone(),
source,
})?;
files.files.insert(ext, bytes);
}
}
Ok(files)
}
/// Picks the files of the database whose `.cbh` member is `cbh_name` from archive
/// members (`name`, bytes).
pub fn from_members<'a>(
cbh_name: &str,
members: impl IntoIterator<Item = (&'a str, &'a [u8])>,
) -> Files {
let stem = stem_of(cbh_name).to_owned();
let mut files = Files {
name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(),
files: HashMap::new(),
};
for (name, data) in members {
if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())
&& stem_of(name) == stem
&& USED.contains(&ext.as_str())
{
files.files.insert(ext, data.to_vec());
}
}
files
}
fn get(&self, ext: &str) -> Option<&[u8]> {
self.files.get(ext).map(Vec::as_slice)
}
fn required(&self, ext: &str) -> Result<&[u8], ImportError> {
self.get(ext).ok_or_else(|| {
ImportError::Corrupt(format!(
"ChessBase database {}: the .{ext} file is missing",
self.name
))
})
}
}
/// Files the reader uses; the others (search boosters, settings, media) are ignored.
const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"];
fn stem_of(name: &str) -> &str {
name.rsplit_once('.').map_or(name, |(s, _)| s)
}
/// Result of converting one database.
#[derive(Clone, Debug, Default)]
pub struct Conversion {
/// UTF-8 PGN text, games and guiding texts in game id order.
pub pgn: String,
pub games: usize,
pub texts: usize,
/// Single-byte code page of the database's texts (UTF-8 texts are recognized
/// individually).
pub encoding: Option<TextEncoding>,
/// Problems worth showing to the user, one line each.
pub notes: Vec<String>,
}
/// Converts a database to PGN. Games that cannot be decoded completely are kept up
/// to the last readable move and reported in the notes.
pub fn convert(files: &Files) -> Result<Conversion, ImportError> {
let cbh = files.required("cbh")?;
let cbg = files.required("cbg")?;
let cba = files.get("cba").unwrap_or(&[]);
let records = headers::read(cbh)?;
let players = entities::read(files.get("cbp"), entities::Kind::Player);
let tournaments = entities::read(files.get("cbt"), entities::Kind::Tournament);
let annotators = entities::read(files.get("cbc"), entities::Kind::Annotator);
// One code page for the whole database, detected from all its single-byte texts.
let mut sample = Vec::new();
for e in [&players, &tournaments, &annotators] {
e.sample(&mut sample);
}
annotations::sample_texts(cba, &records, &mut sample);
let encoding = text::detect(&sample);
let decoder = text::Decoder::new(encoding);
let mut out = Conversion {
encoding: Some(encoding),
..Conversion::default()
};
let mut problems = Problems::default();
for (id, rec) in records.iter().enumerate() {
let game_id = id + 1;
match rec {
headers::Record::Game(h) => {
let tags = writer::tags(h, &players, &tournaments, &annotators, &decoder);
let decoded = moves::decode(cbg, h.moves_offset);
let (tree, error) = match decoded {
Ok(t) => (t, None),
Err(moves::DecodeError { partial, reason }) => (partial, Some(reason)),
};
if let Some(reason) = &error {
problems.add(game_id, &tags, reason);
}
let notes = if h.annotations_offset > 0 {
annotations::read(cba, h.annotations_offset, game_id, &decoder)
} else {
Ok(annotations::Annotations::default())
};
let notes = notes.unwrap_or_else(|reason| {
problems.add(game_id, &tags, &reason);
annotations::Annotations::default()
});
writer::game(&mut out.pgn, &tags, &tree, &notes, h.result_tag());
out.games += 1;
}
headers::Record::Text(t) => match text::guiding_text(cbg, t.text_offset, &decoder) {
Ok(body) => {
let tags =
writer::text_tags(t, &body.title, &tournaments, &annotators, &decoder);
writer::text_game(&mut out.pgn, &tags, &body.text);
out.texts += 1;
}
Err(reason) => problems.add(game_id, &[], &reason),
},
headers::Record::Deleted => {}
}
}
out.notes = problems.into_notes();
Ok(out)
}
/// Collects per-game problems; reports each kind once with the number of games.
#[derive(Default)]
struct Problems {
by_reason: Vec<(String, Vec<String>)>,
}
impl Problems {
fn add(&mut self, game_id: usize, tags: &[(String, String)], reason: &str) {
let tag = |k: &str| {
tags.iter()
.find(|(n, _)| n == k)
.map(|(_, v)| v.as_str())
.unwrap_or("?")
};
let who = if tags.is_empty() {
format!("#{game_id}")
} else {
format!("#{game_id} {} – {}", tag("White"), tag("Black"))
};
match self.by_reason.iter_mut().find(|(r, _)| r == reason) {
Some((_, games)) => games.push(who),
None => self.by_reason.push((reason.to_owned(), vec![who])),
}
}
fn into_notes(self) -> Vec<String> {
self.by_reason
.into_iter()
.map(|(reason, games)| {
let shown: Vec<&str> = games.iter().take(5).map(String::as_str).collect();
let more = if games.len() > 5 {
format!(" (+{})", games.len() - 5)
} else {
String::new()
};
format!("{reason}: {}{more}", shown.join("; "))
})
.collect()
}
}
/// Big-endian unsigned integer of `n` bytes at `at`.
fn be(bytes: &[u8], at: usize, n: usize) -> Option<u32> {
let s = bytes.get(at..at + n)?;
Some(s.iter().fold(0u32, |acc, b| (acc << 8) | u32::from(*b)))
}
/// Little-endian signed 32-bit integer at `at`.
fn le_i32(bytes: &[u8], at: usize) -> Option<i32> {
let s = bytes.get(at..at + 4)?;
Some(i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}

View file

@ -0,0 +1,761 @@
//! `.cbg` game records: the start position and the move tree.
//!
//! Every byte of the move stream goes through a per-mode permutation together with
//! the number of moves decoded so far. The compact encoder then names a piece by
//! its index among the pieces of its kind (in the order they were found on the start
//! board) and gives a displacement modulo 8; the simple encoder stores squares.
use shakmaty::fen::Fen;
use shakmaty::san::SanPlus;
use shakmaty::{
Bitboard, CastlingMode, Chess, Color, EnPassantMode, File, FromSetup, Move, Piece, Position,
Rank, Role, Setup, Square,
};
use super::be;
/// The decoded move tree of one game.
#[derive(Clone, Debug, Default)]
pub struct Tree {
/// FEN of the start position when it is not the usual one.
pub start_fen: Option<String>,
/// `nodes[0]` is the start; every other node is a move.
pub nodes: Vec<Node>,
/// Node of each move in stored order (the annotation position numbering).
pub order: Vec<usize>,
}
#[derive(Clone, Debug, Default)]
pub struct Node {
/// SAN with check marks, or `--` for a null move.
pub san: String,
/// Move number and whether white made the move.
pub number: u32,
pub white: bool,
/// The first child is the main continuation.
pub children: Vec<usize>,
}
/// A game that could only be read in part.
pub struct DecodeError {
pub partial: Tree,
pub reason: String,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Encoder {
Compact,
Simple,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Modifier {
Pre,
Post,
}
pub fn decode(cbg: &[u8], offset: u32) -> Result<Tree, DecodeError> {
let fail = |reason: &str| DecodeError {
partial: Tree::default(),
reason: reason.into(),
};
let at = offset as usize;
let (Some(flags), Some(size)) = (cbg.get(at).copied(), be(cbg, at + 1, 3)) else {
return Err(fail("moves outside the .cbg file"));
};
let record = cbg
.get(at..at + size as usize)
.filter(|r| r.len() >= 4)
.ok_or_else(|| fail("moves outside the .cbg file"))?;
let mode = flags & 0x3f;
let (encoder, modifier, table) = match mode {
0 => (Encoder::Compact, Modifier::Pre, &TABLE_0),
4 => (Encoder::Compact, Modifier::Post, &TABLE_4),
5 => (Encoder::Simple, Modifier::Post, &TABLE_5),
10 | 11 => return Err(fail("Chess960 games are not supported")),
8 | 9 => return Err(fail("losing chess games are not supported")),
m => return Err(fail(&format!("move encoding {m} is not supported"))),
};
let mut body = &record[4..];
let (start, start_fen) = if flags & 0x40 != 0 {
let s = body
.get(..28)
.ok_or_else(|| fail("truncated start position"))?;
body = &body[28..];
let pos = start_position(s).ok_or_else(|| fail("invalid start position"))?;
let fen = Fen::from_position(&pos, EnPassantMode::Legal).to_string();
(pos, Some(fen))
} else {
(Chess::default(), None)
};
let mut d = Decoder {
tree: Tree {
start_fen,
nodes: vec![Node::default()],
order: Vec::new(),
},
table,
modifier,
count: 0,
};
let result = match encoder {
Encoder::Compact => d.compact(body, start),
Encoder::Simple => d.simple(body, start),
};
match result {
Ok(()) => Ok(d.tree),
Err(reason) => Err(DecodeError {
partial: d.tree,
reason,
}),
}
}
/// The 28-byte start position: marker, en passant file and side to move, castling
/// rights, move number, then 192 bits of board, square by square from a1, a2, … h8.
fn start_position(s: &[u8]) -> Option<Chess> {
let mut setup = Setup::empty();
let mut bits = BitReader {
data: &s[4..],
pos: 0,
};
for idx in 0..64 {
if bits.read(1)? == 0 {
continue;
}
let color = if bits.read(1)? == 0 {
Color::White
} else {
Color::Black
};
let role = match bits.read(3)? {
1 => Role::King,
2 => Role::Queen,
3 => Role::Knight,
4 => Role::Bishop,
5 => Role::Rook,
6 => Role::Pawn,
_ => return None,
};
setup
.board
.set_piece_at(cb_square(idx), Piece { color, role });
}
setup.turn = if s[1] & 0x10 != 0 {
Color::Black
} else {
Color::White
};
let mut rights = Bitboard::EMPTY;
for (bit, sq) in [
(0, Square::A1),
(1, Square::H1),
(2, Square::A8),
(3, Square::H8),
] {
if s[2] & (1 << bit) != 0 {
rights.add(sq);
}
}
setup.castling_rights = rights;
let ep = u32::from(s[1] & 0x0f);
if (1..=8).contains(&ep) {
let rank = if setup.turn == Color::White {
Rank::Sixth
} else {
Rank::Third
};
setup.ep_square = Some(Square::from_coords(File::new(ep - 1), rank));
}
setup.fullmoves = std::num::NonZeroU32::new(u32::from(s[3]).max(1))?;
// Positions with doubtful castling rights or en passant squares are still usable.
let pos = match Chess::from_setup(setup, CastlingMode::Standard) {
Ok(p) => p,
Err(e) => match e.ignore_invalid_castling_rights() {
Ok(p) => p,
Err(e) => e.ignore_invalid_ep_square().ok()?,
},
};
Some(pos)
}
/// ChessBase numbers squares file by file: a1 = 0, a2 = 1, … h8 = 63.
fn cb_square(idx: u32) -> Square {
Square::from_coords(File::new(idx / 8), Rank::new(idx % 8))
}
struct BitReader<'a> {
data: &'a [u8],
pos: usize,
}
impl BitReader<'_> {
fn read(&mut self, n: usize) -> Option<u32> {
let mut v = 0;
for _ in 0..n {
let byte = *self.data.get(self.pos / 8)?;
v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1);
self.pos += 1;
}
Some(v)
}
}
/// Which square each piece of a side is on, in ChessBase's numbering.
#[derive(Clone, Default)]
struct Side {
king: Option<Square>,
queens: Vec<Square>,
rooks: Vec<Square>,
bishops: Vec<Square>,
knights: Vec<Square>,
/// Pawns keep their number for the whole game; a captured pawn leaves a gap.
pawns: [Option<Square>; 8],
}
#[derive(Clone)]
struct State {
pos: Chess,
sides: [Side; 2],
node: usize,
}
impl State {
fn new(pos: Chess) -> State {
let mut sides: [Side; 2] = Default::default();
let mut pawn_count = [0usize; 2];
for idx in 0..64 {
let sq = cb_square(idx);
let Some(p) = pos.board().piece_at(sq) else {
continue;
};
let c = p.color as usize;
let s = &mut sides[c];
match p.role {
Role::King => s.king = Some(sq),
Role::Queen => s.queens.push(sq),
Role::Rook => s.rooks.push(sq),
Role::Bishop => s.bishops.push(sq),
Role::Knight => s.knights.push(sq),
Role::Pawn => {
if let Some(slot) = s.pawns.get_mut(pawn_count[c]) {
*slot = Some(sq);
}
pawn_count[c] += 1;
}
}
}
State {
pos,
sides,
node: 0,
}
}
fn side(&mut self, c: Color) -> &mut Side {
&mut self.sides[c as usize]
}
/// Keeps the piece lists in step with a move about to be played.
fn track(&mut self, m: &Move) {
let us = self.pos.turn();
match *m {
Move::Normal {
from,
to,
capture,
promotion,
..
} => {
if capture.is_some() {
self.side(!us).remove(to);
}
self.side(us).relocate(from, to);
if let Some(role) = promotion {
let s = self.side(us);
s.remove(to);
s.list(role).push(to);
}
}
Move::EnPassant { from, to } => {
self.side(!us)
.remove(Square::from_coords(to.file(), from.rank()));
self.side(us).relocate(from, to);
}
Move::Castle { king, rook } => {
let short = rook.file() > king.file();
let rank = king.rank();
let (k, r) = if short {
(File::G, File::F)
} else {
(File::C, File::D)
};
let s = self.side(us);
s.relocate(rook, Square::from_coords(r, rank));
s.relocate(king, Square::from_coords(k, rank));
}
Move::Put { .. } => {}
}
}
}
impl Side {
fn list(&mut self, role: Role) -> &mut Vec<Square> {
match role {
Role::Queen => &mut self.queens,
Role::Rook => &mut self.rooks,
Role::Bishop => &mut self.bishops,
_ => &mut self.knights,
}
}
/// A captured piece: later pieces of its kind move down one; a pawn leaves a gap.
fn remove(&mut self, sq: Square) {
for list in [
&mut self.queens,
&mut self.rooks,
&mut self.bishops,
&mut self.knights,
] {
if let Some(i) = list.iter().position(|s| *s == sq) {
list.remove(i);
return;
}
}
for p in &mut self.pawns {
if *p == Some(sq) {
*p = None;
return;
}
}
}
fn relocate(&mut self, from: Square, to: Square) {
if self.king == Some(from) {
self.king = Some(to);
return;
}
for list in [
&mut self.queens,
&mut self.rooks,
&mut self.bishops,
&mut self.knights,
] {
if let Some(s) = list.iter_mut().find(|s| **s == from) {
*s = to;
return;
}
}
for p in self.pawns.iter_mut().flatten() {
if *p == from {
*p = to;
return;
}
}
}
}
struct Decoder {
tree: Tree,
table: &'static [u8; 256],
modifier: Modifier,
/// Moves decoded so far, variations and null moves included.
count: u32,
}
/// What a byte of the compact encoder asks for.
enum Code {
Null,
/// Piece kind, its index, displacement.
Piece(Role, usize, (i32, i32)),
Pawn(usize, u8),
Castle {
short: bool,
},
TwoBytes,
Ignore,
Push,
Pop,
}
const KING: [(i32, i32); 8] = [
(0, 1),
(1, 1),
(1, 0),
(1, -1),
(0, -1),
(-1, -1),
(-1, 0),
(-1, 1),
];
const KNIGHT: [(i32, i32); 8] = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
];
/// Displacement of the `i`-th step of a line piece: groups of 7 steps in the
/// directions `dirs`.
fn line_step(i: usize, dirs: &[(i32, i32)]) -> (i32, i32) {
let (dx, dy) = dirs[i / 7];
let n = (i % 7 + 1) as i32;
(dx * n, dy * n)
}
const QUEEN_DIRS: [(i32, i32); 4] = [(0, 1), (1, 0), (1, 1), (1, -1)];
const ROOK_DIRS: [(i32, i32); 2] = [(0, 1), (1, 0)];
const BISHOP_DIRS: [(i32, i32); 2] = [(1, 1), (1, -1)];
fn classify(code: u8) -> Option<Code> {
let c = usize::from(code);
Some(match c {
0 => Code::Null,
1..=8 => Code::Piece(Role::King, 0, KING[c - 1]),
9 => Code::Castle { short: true },
10 => Code::Castle { short: false },
11..=38 => Code::Piece(Role::Queen, 0, line_step(c - 11, &QUEEN_DIRS)),
39..=52 => Code::Piece(Role::Rook, 0, line_step(c - 39, &ROOK_DIRS)),
53..=66 => Code::Piece(Role::Rook, 1, line_step(c - 53, &ROOK_DIRS)),
67..=80 => Code::Piece(Role::Bishop, 0, line_step(c - 67, &BISHOP_DIRS)),
81..=94 => Code::Piece(Role::Bishop, 1, line_step(c - 81, &BISHOP_DIRS)),
95..=102 => Code::Piece(Role::Knight, 0, KNIGHT[c - 95]),
103..=110 => Code::Piece(Role::Knight, 1, KNIGHT[c - 103]),
111..=142 => Code::Pawn((c - 111) / 4, ((c - 111) % 4) as u8),
143..=170 => Code::Piece(Role::Queen, 1, line_step(c - 143, &QUEEN_DIRS)),
171..=198 => Code::Piece(Role::Queen, 2, line_step(c - 171, &QUEEN_DIRS)),
199..=212 => Code::Piece(Role::Rook, 2, line_step(c - 199, &ROOK_DIRS)),
213..=226 => Code::Piece(Role::Bishop, 2, line_step(c - 213, &BISHOP_DIRS)),
227..=234 => Code::Piece(Role::Knight, 2, KNIGHT[c - 227]),
235 => Code::TwoBytes,
236 => Code::Ignore,
254 => Code::Push,
255 => Code::Pop,
_ => return None,
})
}
impl Decoder {
fn translate(&self, byte: u8) -> u8 {
let n = (self.count % 256) as u8;
match self.modifier {
Modifier::Pre => self.table[usize::from(byte.wrapping_sub(n))],
Modifier::Post => self.table[usize::from(byte)].wrapping_sub(n),
}
}
fn compact(&mut self, data: &[u8], start: Chess) -> Result<(), String> {
let mut state = State::new(start);
let mut stack: Vec<State> = Vec::new();
let mut i = 0;
while i < data.len() {
let raw = self.translate(data[i]);
i += 1;
let code = classify(raw).ok_or_else(|| format!("unknown move code {raw}"))?;
let m = match code {
Code::Push => {
stack.push(state.clone());
continue;
}
Code::Pop => match stack.pop() {
Some(s) => {
state = s;
continue;
}
None => return Ok(()),
},
Code::Ignore => continue,
Code::Null => None,
Code::TwoBytes => {
let (Some(&a), Some(&b)) = (data.get(i), data.get(i + 1)) else {
return Err("truncated move".into());
};
i += 2;
let v = (u16::from(self.translate(a)) << 8) | u16::from(self.translate(b));
Some(square_move(&state.pos, v)?)
}
Code::Castle { short } => Some(castle(&state.pos, short)?),
Code::Piece(role, index, delta) => {
let side = &state.sides[state.pos.turn() as usize];
let from = match role {
Role::King => side.king,
Role::Queen => side.queens.get(index).copied(),
Role::Rook => side.rooks.get(index).copied(),
Role::Bishop => side.bishops.get(index).copied(),
_ => side.knights.get(index).copied(),
}
.ok_or("move of a piece that is not on the board")?;
Some(find_move(&state.pos, from, displaced(from, delta), None)?)
}
Code::Pawn(index, kind) => {
let from = state.sides[state.pos.turn() as usize].pawns[index]
.ok_or("move of a pawn that is not on the board")?;
let white = state.pos.turn() == Color::White;
let delta = match (kind, white) {
(0, true) => (0, 1),
(1, true) => (0, 2),
(2, true) => (1, 1),
(_, true) => (-1, 1),
(0, false) => (0, -1),
(1, false) => (0, -2),
(2, false) => (-1, -1),
(_, false) => (1, -1),
};
Some(find_move(&state.pos, from, displaced(from, delta), None)?)
}
};
self.play(&mut state, m)?;
}
// A stream without its final end marker: keep what was read.
Ok(())
}
fn simple(&mut self, data: &[u8], start: Chess) -> Result<(), String> {
let mut state = State::new(start);
let mut stack: Vec<State> = Vec::new();
for pair in data.as_chunks::<2>().0 {
let v = (u16::from(self.translate(pair[0])) << 8) | u16::from(self.translate(pair[1]));
if v & 0x8000 != 0 {
stack.push(state.clone());
}
// A move from a square to itself is a null move.
let m = if (v & 63) == ((v >> 6) & 63) {
None
} else {
Some(square_move(&state.pos, v & 0x3fff)?)
};
self.play(&mut state, m)?;
if v & 0x4000 != 0 {
match stack.pop() {
Some(s) => state = s,
None => return Ok(()),
}
}
}
Ok(())
}
/// Adds the move (`None` = null move) as a child of the current node and plays it.
fn play(&mut self, state: &mut State, m: Option<Move>) -> Result<(), String> {
let pos = &state.pos;
let node = Node {
san: match m {
Some(m) => SanPlus::from_move(pos.clone(), m).to_string(),
None => "--".into(),
},
number: pos.fullmoves().get(),
white: pos.turn() == Color::White,
children: Vec::new(),
};
let next = match m {
Some(m) => {
state.track(&m);
let mut p = state.pos.clone();
p.play_unchecked(m);
p
}
None => null_move(&state.pos).ok_or("null move while in check")?,
};
let id = self.tree.nodes.len();
self.tree.nodes.push(node);
self.tree.nodes[state.node].children.push(id);
self.tree.order.push(id);
state.node = id;
state.pos = next;
self.count += 1;
Ok(())
}
}
fn displaced(from: Square, (dx, dy): (i32, i32)) -> Square {
let x = (from.file() as i32 + dx).rem_euclid(8) as u32;
let y = (from.rank() as i32 + dy).rem_euclid(8) as u32;
Square::from_coords(File::new(x), Rank::new(y))
}
/// Move given by squares: bits 0-5 from, 6-11 to, 12-13 promotion piece.
fn square_move(pos: &Chess, v: u16) -> Result<Move, String> {
let from = cb_square(u32::from(v & 63));
let to = cb_square(u32::from((v >> 6) & 63));
let promotion =
[Role::Queen, Role::Rook, Role::Bishop, Role::Knight][usize::from((v >> 12) & 3)];
find_move(pos, from, to, Some(promotion))
}
/// The legal move from `from` to `to` (the king's destination for castling); a
/// promotion takes `promotion`, or a queen.
fn find_move(
pos: &Chess,
from: Square,
to: Square,
promotion: Option<Role>,
) -> Result<Move, String> {
let wanted = promotion.unwrap_or(Role::Queen);
pos.legal_moves()
.into_iter()
.find(|m| {
m.from() == Some(from)
&& king_target(m) == to
&& m.promotion().is_none_or(|p| p == wanted)
})
.ok_or_else(|| "illegal move".to_owned())
}
fn castle(pos: &Chess, short: bool) -> Result<Move, String> {
pos.legal_moves()
.into_iter()
.find(|m| matches!(m, Move::Castle { king, rook } if (rook.file() > king.file()) == short))
.ok_or_else(|| "illegal castling".to_owned())
}
/// Destination as a player sees it: castling goes to the g or c file.
fn king_target(m: &Move) -> Square {
match *m {
Move::Castle { king, rook } => {
let file = if rook.file() > king.file() {
File::G
} else {
File::C
};
Square::from_coords(file, king.rank())
}
_ => m.to(),
}
}
/// Teaching null move: the side to move passes (as `--` in PGN).
fn null_move(pos: &Chess) -> Option<Chess> {
if pos.is_check() {
return None;
}
let mut setup = pos.to_setup(EnPassantMode::Legal);
let was_black = setup.turn == Color::Black;
setup.swap_turn();
setup.ep_square = None;
setup.halfmoves = setup.halfmoves.saturating_add(1);
if was_black {
setup.fullmoves = setup.fullmoves.saturating_add(1);
}
Chess::from_setup(setup, CastlingMode::Standard).ok()
}
const TABLE_0: [u8; 256] = [
0xa2, 0x95, 0x43, 0xf5, 0xc1, 0x3d, 0x4a, 0x6c, 0x53, 0x83, 0xcc, 0x7c, 0xff, 0xae, 0x68, 0xad,
0xd1, 0x92, 0x8b, 0x8d, 0x35, 0x81, 0x5e, 0x74, 0x26, 0x8e, 0xab, 0xca, 0xfd, 0x9a, 0xf3, 0xa0,
0xa5, 0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 0x9d, 0xab, 0xba, 0xe7,
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tables_are_permutations() {
for t in [&TABLE_0, &TABLE_4, &TABLE_5] {
let mut seen = [false; 256];
for v in t.iter() {
assert!(!seen[usize::from(*v)]);
seen[usize::from(*v)] = true;
}
}
}
#[test]
fn start_board_bits() {
// The example from the format description: white pawn a2, black rook b1,
// white knight b4 (bits 0 10110 000000 11101 00 10011), plus both kings.
let mut s = vec![1, 0, 0, 1];
let mut board = vec![0x58, 0x0e, 0x93];
board.resize(24, 0);
s.extend(board);
// Kings are needed for a valid position: add them on h1 (white) and h8 (black).
let mut bits: Vec<u8> = Vec::new();
let mut pos = BitReader {
data: &s[4..],
pos: 0,
};
for _ in 0..24 {
bits.push(pos.read(1).unwrap_or(0) as u8);
}
assert_eq!(bits[..6], [0, 1, 0, 1, 1, 0]);
assert!(start_position(&s).is_none(), "no kings: invalid");
}
#[test]
fn displacement_wraps_modulo_8() {
// A queen on c2 moving (+7, 0) reaches b2.
assert_eq!(displaced(Square::C2, (7, 0)), Square::B2);
assert_eq!(displaced(Square::A1, (-1, -1)), Square::H8);
assert_eq!(line_step(7, &QUEEN_DIRS), (1, 0));
assert_eq!(line_step(13, &QUEEN_DIRS), (7, 0));
assert_eq!(line_step(27, &QUEEN_DIRS), (7, -7));
}
#[test]
fn piece_numbering_follows_the_start_board() {
let s = State::new(Chess::default());
let w = &s.sides[Color::White as usize];
assert_eq!(w.rooks, vec![Square::A1, Square::H1]);
assert_eq!(w.knights, vec![Square::B1, Square::G1]);
assert_eq!(w.pawns[0], Some(Square::A2));
assert_eq!(w.pawns[7], Some(Square::H2));
let b = &s.sides[Color::Black as usize];
assert_eq!(b.rooks, vec![Square::A8, Square::H8]);
assert_eq!(b.pawns[0], Some(Square::A7));
}
}

View file

@ -0,0 +1,386 @@
//! 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<Body, String> {
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) -> Option<u16> {
self.take(2).map(|b| u16::from_le_bytes([b[0], b[1]]))
}
fn u32(&mut self) -> Option<u32> {
self.take(4)
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
}
/// Readable text from the HTML of a guiding text: block elements become line
/// breaks, scripts and styles are dropped, entities are decoded.
pub fn html_to_text(html: &str) -> String {
let mut out = String::new();
let mut rest = html;
while let Some(lt) = rest.find('<') {
out.push_str(&decode_entities(&rest[..lt]));
let Some(gt) = rest[lt..].find('>') else {
rest = "";
break;
};
let tag = rest[lt + 1..lt + gt].trim().to_ascii_lowercase();
rest = &rest[lt + gt + 1..];
let name: String = tag
.trim_start_matches('/')
.chars()
.take_while(|c| c.is_ascii_alphanumeric())
.collect();
if !tag.starts_with('/') && matches!(name.as_str(), "script" | "style" | "head" | "title") {
let close = format!("</{name}");
match rest.to_ascii_lowercase().find(&close) {
Some(end) => {
rest = &rest[end..];
if let Some(gt) = rest.find('>') {
rest = &rest[gt + 1..];
}
}
None => rest = "",
}
continue;
}
if matches!(
name.as_str(),
"br" | "p" | "div" | "li" | "tr" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table"
) && !out.ends_with('\n')
{
out.push('\n');
}
}
out.push_str(&decode_entities(rest));
tidy(&out)
}
/// Plain guiding texts carry no line breaks: paragraphs start after an embedded
/// object (a diagram, a link). A run of objects becomes a paragraph break when a
/// capital letter or a digit follows, and a space otherwise ("games (• and •)").
pub fn objects_to_breaks(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c != OBJECT {
out.push(c);
continue;
}
while chars
.peek()
.is_some_and(|c| *c == OBJECT || c.is_whitespace())
{
chars.next();
}
let next = chars.peek().copied();
if next.is_none_or(|n| n.is_uppercase() || n.is_ascii_digit()) {
out.push('\n');
} else {
out.push(' ');
}
}
out
}
/// One paragraph per non-empty line, separated by a blank line; whitespace inside a
/// line collapsed.
pub fn tidy(text: &str) -> String {
// Line breaks may be "\r\n", "\n" or a lone "\r" (older ChessBase texts).
text.replace("\r\n", "\n")
.replace('\r', "\n")
.lines()
.map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join("\n\n")
}
fn decode_entities(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
let tail = &rest[amp..];
let Some(semi) = tail.find(';').filter(|i| *i <= 10) else {
out.push('&');
rest = &tail[1..];
continue;
};
let name = &tail[1..semi];
let ch = match name {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some(' '),
_ => name
.strip_prefix("#x")
.or_else(|| name.strip_prefix("#X"))
.and_then(|h| u32::from_str_radix(h, 16).ok())
.or_else(|| name.strip_prefix('#').and_then(|n| n.parse().ok()))
.and_then(char::from_u32),
};
match ch {
Some(c) => {
out.push(c);
rest = &tail[semi + 1..];
}
None => {
out.push('&');
rest = &tail[1..];
}
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utf8_texts_win_over_the_code_page() {
let d = Decoder::new(TextEncoding::Windows1251);
assert_eq!(d.decode("Привет".as_bytes()), "Привет");
assert_eq!(d.decode(&[0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]), "Привет");
assert_eq!(d.decode(b"plain"), "plain");
}
#[test]
fn figurines_and_diagrams() {
let d = Decoder::new(TextEncoding::Windows1252);
assert_eq!(
d.decode(b"3...\xa5g4 4 \xa4:e5 \xa6xh5 \xa7b2+ \x9e"),
"3...Bg4 4 N:e5 Rxh5 b2+ "
);
assert_eq!(
d.decode(b"price \xa3 5"),
"price £ 5",
"not before a square"
);
assert_eq!(
d.decode("plan \u{e027}e3, \u{e025}d2 \u{e028}c6 \u{e005}".as_bytes()),
"plan Be3, Qd2 Nc6 "
);
}
#[test]
fn names_pick_the_code_page_per_name() {
let d = Decoder::new(TextEncoding::Windows1251);
assert_eq!(d.decode_name(b"N\xfcrnberg"), "Nürnberg");
assert_eq!(d.decode_name(b"\xc0\xeb\xe5\xf5\xe8\xed"), "Алехин");
assert_eq!(
d.decode_name(b"1.7.\xe0"),
"1.7.а",
"a tie keeps the database code page"
);
// Comments keep the database code page even when Latin squares follow Cyrillic.
assert_eq!(d.decode(b"\xcaf3"), "Кf3");
}
#[test]
fn embedded_objects_split_paragraphs() {
let t =
"Title! \u{4} Body text (\u{4} and \u{4}) here. \u{4}\u{4} \u{4}УПРАЖНЕНИЯ \u{4} \u{4}";
assert_eq!(
tidy(&objects_to_breaks(t)),
"Title!\n\nBody text ( and ) here.\n\nУПРАЖНЕНИЯ"
);
let d = Decoder::new(TextEncoding::Windows1252);
assert_eq!(d.decode(b"a\x01b\x81c\x04d"), "abc\u{4}d");
}
#[test]
fn html_becomes_text() {
let html = "<html><head><title>x</title><style>p{}</style></head><body>\
<p>First&nbsp;line &amp; more</p><p>Second<br>third &#1095;</p>\
<script>alert(1)</script></body></html>";
assert_eq!(html_to_text(html), "First line & more\n\nSecond\n\nthird ч");
assert_eq!(tidy("\t\n A b \n\n\n\tc\n "), "A b\n\nc");
assert_eq!(tidy("One\r\rTwo\r\nThree"), "One\n\nTwo\n\nThree");
assert_eq!(html_to_text("a & b; <b>c</b>"), "a & b; c");
}
}

View file

@ -0,0 +1,345 @@
//! PGN text for decoded games and guiding texts.
use std::fmt::Write as _;
use super::annotations::{Annotations, Item};
use super::entities::Entities;
use super::headers::{GameHeader, TextHeader, date_tag, round_tag};
use super::moves::Tree;
use super::text::Decoder;
pub type Tags = Vec<(String, String)>;
pub fn tags(
h: &GameHeader,
players: &Entities,
tournaments: &Entities,
annotators: &Entities,
d: &Decoder,
) -> Tags {
let or_q = |s: Option<String>| s.unwrap_or_else(|| "?".into());
let event_date = tournaments.date(h.tournament);
let mut t: Tags = vec![
("Event".into(), or_q(tournaments.name(h.tournament, d))),
("Site".into(), or_q(tournaments.place(h.tournament, d))),
("Date".into(), date_tag(h.date)),
("Round".into(), round_tag(h.round, h.subround)),
("White".into(), or_q(players.name(h.white, d))),
("Black".into(), or_q(players.name(h.black, d))),
("Result".into(), h.result_tag().into()),
];
if h.white_elo > 0 {
t.push(("WhiteElo".into(), h.white_elo.to_string()));
}
if h.black_elo > 0 {
t.push(("BlackElo".into(), h.black_elo.to_string()));
}
if let Some(eco) = h.eco_tag() {
t.push(("ECO".into(), eco));
}
if let Some(a) = annotators.name(h.annotator, d) {
t.push(("Annotator".into(), a));
}
if event_date != 0 {
t.push(("EventDate".into(), date_tag(event_date)));
}
t
}
/// A guiding text is shown as a game without moves: the title in place of the
/// players and the text as the opening comment.
pub fn text_tags(
h: &TextHeader,
title: &str,
tournaments: &Entities,
annotators: &Entities,
d: &Decoder,
) -> Tags {
let mut t: Tags = vec![
(
"Event".into(),
tournaments
.name(h.tournament, d)
.unwrap_or_else(|| "?".into()),
),
("Site".into(), "?".into()),
("Date".into(), "????.??.??".into()),
("Round".into(), round_tag(h.round, h.subround)),
(
"White".into(),
if title.is_empty() {
"?".into()
} else {
title.into()
},
),
("Black".into(), String::new()),
("Result".into(), "*".into()),
];
if let Some(a) = annotators.name(h.annotator, d) {
t.push(("Annotator".into(), a));
}
t
}
pub fn text_game(out: &mut String, tags: &Tags, text: &str) {
write_tags(out, tags, None);
let mut w = Movetext::default();
if !text.trim().is_empty() {
w.comment(text);
}
w.token("*");
out.push_str(&w.finish());
}
pub fn game(out: &mut String, tags: &Tags, tree: &Tree, notes: &Annotations, result: &str) {
// Main-line length, for the library's move count.
let mut plies = 0;
let mut node = 0;
while let Some(&next) = tree.nodes[node].children.first() {
plies += 1;
node = next;
}
let mut tags = tags.clone();
if plies > 0 {
tags.push(("PlyCount".into(), plies.to_string()));
}
write_tags(out, &tags, tree.start_fen.as_deref());
// Annotation position of each node.
let mut position = vec![None; tree.nodes.len()];
for (i, n) in tree.order.iter().enumerate() {
position[*n] = i32::try_from(i).ok();
}
let mut w = Movetext::default();
if let Some(items) = notes.at.get(&-1) {
// Before-move texts of the whole game read as an introduction too.
let mut intro: Vec<&Item> = items.iter().collect();
intro.sort_by_key(|i| !matches!(i, Item::Before(_)));
w.after_comment(&intro);
}
let ctx = Ctx {
tree,
notes,
position: &position,
};
ctx.line(&mut w, 0);
w.token(result);
out.push_str(&w.finish());
}
struct Ctx<'a> {
tree: &'a Tree,
notes: &'a Annotations,
position: &'a [Option<i32>],
}
impl Ctx<'_> {
/// Writes the continuation of `node`: its main move, the alternatives to that
/// move as variations, then the rest of the main line.
fn line(&self, w: &mut Movetext, mut node: usize) {
loop {
let children = &self.tree.nodes[node].children;
let Some(&main) = children.first() else {
return;
};
self.write_move(w, main);
for &alt in &children[1..] {
w.open();
self.write_move(w, alt);
self.line(w, alt);
w.close();
}
node = main;
}
}
fn write_move(&self, w: &mut Movetext, id: usize) {
let n = &self.tree.nodes[id];
let items: &[Item] = self.position[id]
.and_then(|p| self.notes.at.get(&p))
.map(Vec::as_slice)
.unwrap_or(&[]);
for it in items {
if let Item::Before(t) = it {
w.comment(t);
}
}
// The number and the move stay on one line.
let number = if n.white {
format!("{}. ", n.number)
} else if w.need_number {
format!("{}... ", n.number)
} else {
String::new()
};
w.need_number = false;
w.token(&format!("{number}{}", n.san));
for it in items {
if let Item::Nags(nags) = it {
for nag in nags {
w.token(&format!("${nag}"));
}
}
}
let after: Vec<&Item> = items
.iter()
.filter(|i| !matches!(i, Item::Before(_) | Item::Nags(_)))
.collect();
w.after_comment(&after);
}
}
fn write_tags(out: &mut String, tags: &Tags, fen: Option<&str>) {
for (k, v) in tags {
let _ = writeln!(out, "[{k} \"{}\"]", escape_tag(v));
}
if let Some(fen) = fen {
let _ = writeln!(out, "[SetUp \"1\"]");
let _ = writeln!(out, "[FEN \"{}\"]", escape_tag(fen));
}
out.push('\n');
}
fn escape_tag(v: &str) -> String {
v.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace(['\r', '\n'], " ")
}
/// Movetext builder with line wrapping at 80 columns.
#[derive(Default)]
struct Movetext {
lines: Vec<String>,
current: String,
need_number: bool,
}
impl Movetext {
fn token(&mut self, t: &str) {
if !self.current.is_empty() && self.current.chars().count() + 1 + t.chars().count() > 80 {
self.lines.push(std::mem::take(&mut self.current));
}
if !self.current.is_empty() && !self.current.ends_with('(') {
self.current.push(' ');
}
self.current.push_str(t);
}
fn comment(&mut self, text: &str) {
// '}' would end the comment early; ChessBase texts rarely contain it.
let clean = text.replace('}', ")");
self.token(&format!("{{{clean}}}"));
self.need_number = true;
}
/// One comment with the graphics as `[%csl]`/`[%cal]`/`[%emt]` commands and the texts.
fn after_comment(&mut self, items: &[&Item]) {
let mut parts: Vec<String> = Vec::new();
for it in items {
match it {
Item::Squares(list) if !list.is_empty() => parts.push(format!(
"[%csl {}]",
list.iter()
.map(|(c, s)| format!("{c}{}", square(*s)))
.collect::<Vec<_>>()
.join(",")
)),
Item::Arrows(list) if !list.is_empty() => parts.push(format!(
"[%cal {}]",
list.iter()
.map(|(c, a, b)| format!("{c}{}{}", square(*a), square(*b)))
.collect::<Vec<_>>()
.join(",")
)),
Item::TimeSpent(h, m, s) => parts.push(format!("[%emt {h}:{m:02}:{s:02}]")),
Item::After(t) | Item::Before(t) => parts.push(t.clone()),
_ => {}
}
}
if !parts.is_empty() {
self.comment(&parts.join(" "));
}
}
fn open(&mut self) {
self.token("(");
self.need_number = true;
}
fn close(&mut self) {
self.current.push(')');
self.need_number = true;
}
fn finish(mut self) -> String {
if !self.current.is_empty() {
self.lines.push(self.current);
}
let mut s = self.lines.join("\n");
s.push_str("\n\n");
s
}
}
/// Square name from ChessBase numbering (a1 = 0, a2 = 1, … h8 = 63).
fn square(idx: u8) -> String {
let file = (b'a' + idx / 8) as char;
let rank = (b'1' + idx % 8) as char;
format!("{file}{rank}")
}
#[cfg(test)]
mod tests {
use super::super::moves::Node;
use super::*;
fn node(san: &str, number: u32, white: bool, children: Vec<usize>) -> Node {
Node {
san: san.into(),
number,
white,
children,
}
}
#[test]
fn variations_comments_and_graphics() {
// 1. e4 c5 (1... c6 2. d4) 2. Nf3
let tree = Tree {
start_fen: None,
nodes: vec![
node("", 0, true, vec![1]),
node("e4", 1, true, vec![2, 4]),
node("c5", 1, false, vec![3]),
node("Nf3", 2, true, vec![]),
node("c6", 1, false, vec![5]),
node("d4", 2, true, vec![]),
],
order: vec![1, 2, 3, 4, 5],
};
let mut notes = Annotations::default();
notes.at.insert(-1, vec![Item::After("Intro".into())]);
notes.at.insert(
0,
vec![
Item::Nags(vec![1]),
Item::Arrows(vec![('G', 35, 36)]),
Item::After("Best by test }".into()),
],
);
notes.at.insert(3, vec![Item::Before("Also".into())]);
let mut out = String::new();
game(
&mut out,
&vec![("Event".into(), "Test \"x\"".into())],
&tree,
&notes,
"*",
);
assert_eq!(
out,
"[Event \"Test \\\"x\\\"\"]\n[PlyCount \"3\"]\n\n{Intro} 1. e4 $1 {[%cal Ge4e5] Best by test )} 1... c5 ({Also} 1... c6 2. d4)\n\
2. Nf3 *\n\n"
);
}
}