cbvault 0.1.4

Read ChessBase databases as moves2 streams: Database, GameIter, PGN writer, and .cbv/.cbz archives that unarchive in full
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! PGN output: a game's tags and its move tree as standard algebraic
//! notation, with its annotations as the reading form writes them.
//!
//! The writer streams: it holds one game's nodes (its moves, their SAN and the
//! shape of the tree), never a database, and a caller that reuses one
//! [`PgnWriter`] keeps those buffers from game to game. SAN is generated by
//! `gigachess` at this boundary only. The annotations are placed by position
//! in stored order (the private `comments::Commentary`), and their buffers — the index
//! over the record, the parts of one comment — are the writer's and stay
//! filled for reuse: one annotated game costs no allocation after the first.
//!
//! Ported from `cbformat`'s `pgn/{mod,tree,comments}.rs` (MIT,
//! `oschess-cb-bridge` @ `ca9e8f8e`), re-based on `gigachess` (SAN from
//! `gigachess::san`), written to a caller's sink instead of a `String`, and
//! on the borrowed annotation model instead of the ancestor's owned
//! `BTreeMap` per game. The reading form follows ChessBase's own export —
//! the standard the gold comparison holds it to. See `docs/provenance.md`.
//!
//! **The SAN is rendered in two halves** (`gigachess` 0.1.5): the body from the
//! position a move is played from, the check/mate suffix from the position it
//! leaves behind, which this writer already has — the walk made the move to
//! reach the next ply. That is why the walk keeps the cached `checkers`
//! current ([`MoveSink::wants_checkers`]) and pays `+2 ns` per make: the
//! suffix reads that cache, *and so does `gigachess`'s own move generator,
//! which resolves SAN disambiguation.* Making the moves with `play_fast` and
//! its stale cache silently under-disambiguated five games in eleven million
//! (`Rg6` where two rooks reach g6, so `Rfg6`); the maintained cache is what
//! the exporter has used since.

mod comments;

/// The PGN text splitter: blank line outside a comment plus a tag line next.
pub mod split;
pub use split::{split_game_ranges, split_games};

/// The parallel export pipeline (Rayon, record-ordered output).
pub mod parallel;
pub use parallel::{
    DEFAULT_BATCH, ExportStats, export_parallel, export_range, export_range_from, export_span, export_span_report,
};

use std::io::{self, Write};

use cbvault_chess::decode::{GameRef, MoveSink, start_as_played, walk_from};
use cbvault_chess::start::{Start, StartCache, start_board_cached};
use cbvault_format::cbh::GameAnnotations;
use cbvault_format::cbh::bytes::NameBuf;
use cbvault_format::cbh::{Entities, GameMoves};
use cbvault_format::error::{Error, Result};
use cbvault_format::game::annotations::{Annotation, GAME_POSITION, timing};
use cbvault_format::game::{GameResult, Head, ROUND_TEXT_BYTES, RecordKind, round_text};
use comments::{At, Bare, Commentary, Notes};
use gigachess::san::{San, check_mate_suffix, move_to_san_body};
use gigachess::{Board, Color, Move};

/// No child of a node.
const NONE: u32 = u32::MAX;

/// The SAN body's disambiguation is `gigachess`' movegen-based query today, and
/// it need not be: chesscore (MIT, `cbformat::pgn::san::disambiguate`) asks each
/// candidate on its own, which is cheaper (8.1 ns per SAN body against 13.5 ns
/// over 13.9 M moves of the reference database) and, written carefully,
/// identical - 0 differing moves on that slice, and the same gold result
/// (407,350 of 419,385, the same twelve thousand diffs).
///
/// The two values that decide a candidate's legality are the *mover's* king and
/// the side that moves next, both taken from the caller's position: asking
/// about the side to move after the candidate, attacked by its own pieces, is a
/// question with no meaning (White's rook on h1 "defends" its own king on e1),
/// and it silently drops hints that should be there - the study's first attempt
/// did exactly that and lost 324,013 gold games, which read as a correctness
/// wall rather than as a bug in the question.
///
/// The change belongs upstream in `gigachess`, which owns the SAN rule here;
/// the hunk is `docs/gigachess-san-disambiguation.patch`, `examples/san_probe.rs`
/// measures both forms, and `docs/format-spec.md` §11.7 has the numbers.
///
/// One decoded move: its SAN and check/mate suffix inline — `gigachess` hands
/// the body over in a fixed-size [`San`] by value, so the walk stores it in
/// the node without a copy, and there is no shared text buffer to grow or to
/// read back — the move number and side it was played with, and its place in
/// the tree.
#[derive(Debug)]
struct Node {
    san: San,
    fullmove: u16,
    white: bool,
    first_child: u32,
    last_child: u32,
    next_sibling: u32,
}

/// One step of the movetext traversal, on the writer's reused stack.
#[derive(Debug)]
enum EmitStep {
    /// Continue the line whose last written move is `node`.
    Line { node: u32, force_number: bool },
    /// Write the alternative `alt` to the main move `main`, and those after it.
    Alternatives { main: u32, alt: u32 },
    /// The alternatives end; return to the main move, repeating its number.
    Close,
}

/// A game's move tree while it is decoded: the nodes, each with its SAN, and
/// the open brackets.
#[derive(Debug, Default)]
struct Tree {
    nodes: Vec<Node>,
    cur: u32,
    parent_of_last: u32,
    branches: Vec<u32>,
    /// Whether the move just reported takes a check/mate suffix: a real move
    /// whose body rendered. A pass (`--`) and an unrenderable move (`??`) do
    /// not, exactly as the export wrote them before the split.
    suffix_pending: bool,
}

impl Tree {
    /// An empty tree with the root node.
    fn new() -> Tree {
        Tree {
            nodes: vec![Node {
                san: San::new(),
                fullmove: 0,
                white: true,
                first_child: NONE,
                last_child: NONE,
                next_sibling: NONE,
            }],
            ..Default::default()
        }
    }

    /// Empties the tree, keeping its buffers for the next game.
    fn clear(&mut self) {
        self.nodes.truncate(1);
        self.nodes[0].first_child = NONE;
        self.nodes[0].last_child = NONE;
        self.cur = 0;
        self.parent_of_last = 0;
        self.branches.clear();
    }

    /// The main line's last move in stored order — where the annotations past
    /// the game's last move are written — or `None` for a game without moves.
    /// The moves are numbered from 0 as they were played; node 0 is the root.
    fn main_line_last(&self) -> Option<u32> {
        let mut n = self.nodes.first()?.first_child;
        while n != NONE {
            let node = self.nodes.get(n as usize)?;
            if node.first_child == NONE {
                return Some(n - 1);
            }
            n = node.first_child;
        }
        None
    }
}

impl MoveSink for Tree {
    fn play(&mut self, before: &Board, mv: u16, _main: bool) {
        // The SAN body, built in a fixed-size buffer `gigachess` returns by
        // value: nothing is copied to record it.
        let mut san = San::new();
        // The body needs only this position; the check/mate suffix needs the one
        // the move leaves behind, which `played` is handed. `gigachess` 0.1.5
        // exposes the two halves (`san::move_to_san_body`,
        // `san::check_mate_suffix`), so the walk's own make answers the suffix
        // and the monolith's second make/unmake per ply is gone
        // (`pgn-export-sota-performance` task 6.4).
        self.suffix_pending = false;
        // No special case for a pass: since `gigachess` 0.1.9 `move_to_san_body`
        // renders `Move::NULL` as `--` itself, so the null word no longer needs a
        // branch here to be spelled. The one thing the caller still owns is
        // whether to ask for a suffix — a pass neither gives nor answers check,
        // so `--` must stay bare.
        let mv = Move::from_word(mv);
        match move_to_san_body(before, mv) {
            Some(body) => {
                san = body;
                self.suffix_pending = !mv.is_null();
            }
            None => san.push_str("??"),
        }
        let white = before.turn() == Color::White;
        // The number ChessBase's own export writes. A move from the root takes
        // the start position's own number; below it the number is inherited —
        // it advances only from Black to the next White, so a pass by White
        // leaves the Black move after it at the same number (`30. -- Qxd3
        // 31. Qxd3`, the Mega's export). The board's own counter is not read
        // past the first move: it advances after a pass by either side.
        let parent = &self.nodes[self.cur as usize];
        let fullmove = if self.cur == 0 {
            before.fullmove_number()
        } else if white {
            parent.fullmove.saturating_add(u16::from(!parent.white))
        } else {
            parent.fullmove
        };
        let id = self.nodes.len() as u32;
        self.nodes.push(Node {
            // Closed by `played`, once the suffix is in.
            san,
            fullmove,
            white,
            first_child: NONE,
            last_child: NONE,
            next_sibling: NONE,
        });
        let cur = self.cur as usize;
        match self.nodes[cur].last_child {
            NONE => self.nodes[cur].first_child = id,
            last => self.nodes[last as usize].next_sibling = id,
        }
        self.nodes[cur].last_child = id;
        self.parent_of_last = self.cur;
        self.cur = id;
    }

    fn played(&mut self, after: &Board) {
        // The suffix of the move just made. A pass carries none — the Mega's
        // export writes `--` and no `+` — and neither does a move whose body
        // could not be rendered, so the flag from `play` decides.
        if self.suffix_pending
            && let Some(c) = check_mate_suffix(after)
        {
            let cur = self.cur as usize;
            self.nodes[cur].san.push(c);
        }
    }

    fn branch(&mut self) {
        self.branches.push(self.parent_of_last);
    }

    fn resume(&mut self) {
        // The walk calls `resume` only with a branch outstanding.
        self.cur = self.branches.pop().unwrap_or(0);
    }

    fn wants_checkers(&self) -> bool {
        // `check_mate_suffix` reads the cached `checkers`, so the walk must make
        // moves that maintain it.
        true
    }
}

/// Writes move `n` and, when due, its number: the note before the number and
/// the notes after the SAN belong to the caller ([`emit`]).
#[inline]
fn write_move(out: &mut String, tree: &Tree, n: u32, force_number: bool) {
    let node = &tree.nodes[n as usize];
    // The number, the SAN and the space after it, in one reservation: this
    // runs 869,502,065 times over the reference database.
    out.reserve(node.san.len() + 8);
    if node.white {
        push_move_number(out, node.fullmove, false);
    } else if force_number {
        push_move_number(out, node.fullmove, true);
    }
    out.push_str(node.san.as_str());
}

/// A move's number: `12. ` for White, `12... ` where a number is forced (the
/// alternatives of a variation). Written without `core::fmt`: this runs once
/// per move, 869,502,065 times over the reference database.
#[inline]
fn push_move_number(out: &mut String, n: u16, black: bool) {
    push_u16(out, n);
    // Byte pushes, not a `push_str`: a three-byte copy is a `memcpy` call, and
    // this runs once per move — 869,502,065 times over the reference database.
    if black {
        out.push('.');
        out.push('.');
    }
    out.push('.');
    out.push(' ');
}

/// An unsigned number in decimal, without the formatting machinery: the
/// per-move and per-tag numbers, the medal, the evaluation, the time.
#[inline]
fn push_u16(out: &mut String, n: u16) {
    let mut digits = [0u8; 5];
    let mut i = digits.len();
    let mut n = u32::from(n);
    loop {
        i -= 1;
        digits[i] = b'0' + (n % 10) as u8;
        n /= 10;
        if n == 0 {
            break;
        }
    }
    push_ascii(out, &digits[i..]);
}

/// A `u32` in decimal, without the formatting machinery.
#[inline]
fn push_u32(out: &mut String, n: u32) {
    let mut digits = [0u8; 10];
    let mut i = digits.len();
    let mut n = n;
    loop {
        i -= 1;
        digits[i] = b'0' + (n % 10) as u8;
        n /= 10;
        if n == 0 {
            break;
        }
    }
    push_ascii(out, &digits[i..]);
}

/// ASCII bytes straight into the output. The callers build the bytes
/// themselves, so no validation is needed; validation would cost more than the
/// copy on these one-to-five byte runs.
#[inline]
fn push_ascii(out: &mut String, bytes: &[u8]) {
    out.reserve(bytes.len());
    for &b in bytes {
        out.push(char::from(b));
    }
}

/// Writes the tree below the root as movetext, in PGN order: iterative, so a
/// deeply nested game costs heap and not stack. `notes` writes what follows
/// each move's number and SAN: its comments, NAGs and graphics.
fn emit(tree: &Tree, notes: &mut impl Notes, out: &mut String, steps: &mut Vec<EmitStep>) -> Result<()> {
    use EmitStep::*;
    // Writes move `n`, its number when due and its notes. Comments do not
    // force the following number: ChessBase's export writes `e5` after a
    // comment, not `1... e5` — a number is due at the game's first move and
    // around variations only (see `docs/format-spec.md` §8).
    let mut write = |out: &mut String, n: u32, force_number: bool| -> Result<()> {
        // Node 0 is the root; the moves are numbered from 1 as they were
        // played, and annotation positions count them the same way from 0.
        let at = At { stored: n - 1 };
        notes.before(at, out)?;
        write_move(out, tree, n, force_number);
        notes.after(at, out)?;
        out.push(' ');
        Ok(())
    };
    let nodes = &tree.nodes;
    // The writer's own step stack, reused game to game: a `Vec` per game would
    // be eleven million allocations for the megabase run.
    steps.clear();
    steps.push(EmitStep::Line { node: 0, force_number: true });
    while let Some(step) = steps.pop() {
        match step {
            Line { node, force_number } => {
                let main = nodes[node as usize].first_child;
                if main == NONE {
                    continue;
                }
                write(out, main, force_number)?;
                match nodes[main as usize].next_sibling {
                    NONE => steps.push(Line { node: main, force_number: false }),
                    alt => steps.push(Alternatives { main, alt }),
                }
            }
            Alternatives { main, alt } => {
                if alt == NONE {
                    // Back on the main line after its alternatives: repeat the number.
                    steps.push(Line { node: main, force_number: true });
                } else {
                    steps.push(Alternatives { main, alt: nodes[alt as usize].next_sibling });
                    steps.push(Close);
                    out.push('(');
                    write(out, alt, true)?;
                    steps.push(Line { node: alt, force_number: false });
                }
            }
            Close => {
                if out.ends_with(' ') {
                    out.pop();
                }
                out.push_str(") ");
            }
        }
    }
    Ok(())
}

/// The tag roster of a game: its tournament, players, date, result and start.
/// Every value is written into `out` — no `format!`, no intermediate
/// `String`, and the entity names decoded into `names`, the writer's buffers:
/// the whole tag block of a game costs no allocation after warm-up.
fn write_tags<H: Head>(
    out: &mut String,
    header: &H,
    entities: &Entities,
    start: &Start,
    board: &Board,
    total_plies: u32,
    names: &mut Names,
) -> Result<()> {
    let id = |v: i64| -> Option<u32> { (v >= 0).then_some(v as u32) };
    let (event, place) = match id(header.tournament())
        .map(|id| entities.tournament_into(id, &mut names.title, &mut names.place))
        .transpose()?
        .flatten()
    {
        Some((_start, title, place)) => {
            (if title.is_empty() { "?" } else { title }, if place.is_empty() { "?" } else { place })
        }
        None => ("?", "?"),
    };
    push_escaped_tag(out, "[Event \"", event);
    push_escaped_tag(out, "[Site \"", place);
    push_tag(out, "[Date \"", str_from_bytes(&header.played_date().text()));
    push_round(out, header.round(), names);
    let white = id(header.white())
        .map(|id| entities.player_into(id, &mut names.white_last, &mut names.white_first))
        .transpose()?
        .flatten();
    push_escaped_player(out, "[White \"", white);
    let black = id(header.black())
        .map(|id| entities.player_into(id, &mut names.black_last, &mut names.black_first))
        .transpose()?
        .flatten();
    push_escaped_player(out, "[Black \"", black);
    push_tag(out, "[Result \"", result_tag(header.result()));
    if let Some(eco) = header.eco().code_text() {
        // The code is three ASCII bytes; `Eco::pgn` would allocate a `String`
        // for every game that has one, which is most of them.
        push_ascii_tag(out, "[ECO \"", &eco);
    }
    let (white_elo, black_elo) = header.elo();
    if white_elo > 0 {
        push_number_tag(out, "[WhiteElo \"", white_elo as u32);
    }
    if black_elo > 0 {
        push_number_tag(out, "[BlackElo \"", black_elo as u32);
    }
    if total_plies == 0 {
        push_tag(out, "[PlyCount \"", "0");
    }
    if *start != Start::Standard {
        if matches!(start, Start::Chess960(_)) || matches!(start, Start::Setup(s) if s.chess960) {
            push_tag(out, "[Variant \"", "Chess960");
        }
        push_tag(out, "[SetUp \"", "1");
        let fen = fen_tag(board, start);
        push_tag(out, "[FEN \"", &fen);
    }
    out.push('\n');
    Ok(())
}

/// The buffers the tag path decodes entity names and the round into, reused
/// game to game: one name at a time, so a game's tags cost no allocation.
#[derive(Debug, Default)]
struct Names {
    white_last: NameBuf,
    white_first: NameBuf,
    black_last: NameBuf,
    black_first: NameBuf,
    title: NameBuf,
    place: NameBuf,
    round: [u8; ROUND_TEXT_BYTES],
}

/// `[<name> "<value>"]` and its newline, the value as it stands.
#[inline]
fn push_tag(out: &mut String, head: &str, value: &str) {
    // `head` is the whole `[Name \"` in one literal: three writes a tag become
    // two, and this runs nine times per game.
    out.push_str(head);
    out.push_str(value);
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// `[<name> "<value>"]` and its newline, the value escaped: a quote or a
/// backslash is escaped and a figurine code becomes its letter.
#[inline]
fn push_escaped_tag(out: &mut String, head: &str, value: &str) {
    out.push_str(head);
    escape_into(out, value);
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// `[<name> "<value>"]` and its newline for a value that is ASCII bytes.
#[inline]
fn push_ascii_tag(out: &mut String, head: &str, value: &[u8]) {
    out.push_str(head);
    push_ascii(out, value);
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// `[<name> "<number>"]` and its newline, the number written by hand.
#[inline]
fn push_number_tag(out: &mut String, head: &str, value: u32) {
    out.push_str(head);
    push_u32(out, value);
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// `[<name> "<value>"]` and its newline for a player: `Last, First` escaped.
#[inline]
fn push_escaped_player(out: &mut String, head: &str, player: Option<(&str, &str)>) {
    out.push_str(head);
    match player {
        Some((last, first)) => {
            escape_into(out, last);
            if !first.is_empty() {
                out.push_str(", ");
                escape_into(out, first);
                // A first name of one or two uppercase letters or digits is
                // initials and takes a period (`Delaire, H.`, `Ward, JH.`).
                if (1..=2).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
                {
                    out.push('.');
                }
            } else if last.is_empty() {
                out.push('?');
            }
        }
        None => out.push('?'),
    }
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// The ten ASCII bytes of a date, borrowed as a string (every byte is ASCII,
/// so the check is a fixed-length one the compiler folds away).
#[inline]
fn str_from_bytes(bytes: &[u8; 10]) -> &str {
    std::str::from_utf8(bytes).unwrap_or("????.??.??")
}

/// `[Round "..."]` and its newline: the round and sub-round as ChessBase's
/// export writes them, `5`, `5.2` for the second game of round 5, or `?.4`
/// when only the sub-round is known.
fn push_round(out: &mut String, (round, sub): (i32, i32), names: &mut Names) {
    out.push_str("[Round \"");
    if round <= 0 && sub > 0 {
        out.push_str("?.");
        push_u32(out, sub as u32);
    } else {
        let text = round_text(round, sub, &mut names.round);
        if text.is_empty() {
            out.push('?');
        } else {
            match (text.find('('), text.find(')')) {
                (Some(open), Some(close)) => {
                    out.push_str(&text[..open]);
                    out.push('.');
                    out.push_str(&text[open + 1..close]);
                }
                _ => out.push_str(text),
            }
        }
    }
    out.push('"');
    out.push(']');
    out.push('\n');
}

/// The FEN tag ChessBase's export writes: the stored move number verbatim —
/// a record holding 0 writes `… 0 0` even though the board's own FEN, parsed
/// from 1, cannot carry it back (`docs/format-spec.md` §8).
fn fen_tag(board: &Board, start: &Start) -> String {
    let fen = board.to_fen();
    match start {
        Start::Setup(setup) if setup.move_number == 0 && fen.ends_with(" 1") => format!("{}0", &fen[..fen.len() - 1]),
        _ => fen,
    }
}

/// A PGN tag value written into `out`: a quote or a backslash is escaped, and
/// ChessBase's figurine codes are written as letters. `None` becomes `?` at
/// the call site. Writes into the caller's buffer; nothing is allocated.
fn escape_into(out: &mut String, text: &str) {
    // 0xEE is the lead byte of the figurine codes U+E024..U+E029 in UTF-8, so
    // one byte test per character covers all three cases.
    if !text.bytes().any(|b| b == b'"' || b == b'\\' || b == 0xee) {
        out.push_str(text);
        return;
    }
    for c in text.chars() {
        if let Some(letter) = figurine(c) {
            out.push(letter);
            continue;
        }
        if c == '"' || c == '\\' {
            out.push('\\');
        }
        out.push(c);
    }
}

/// The letter of a ChessBase figurine code, if `c` is one. The tournament
/// titles that record piece odds carry the codes `U+E025`…`U+E029` for
/// queen, rook, bishop, knight and pawn — `Odds <Q>d1`, `Odds <R>a1+ <N>b1`
/// — and ChessBase's own PGN export writes them as the letters. `U+E024`
/// completes the sequence for a king; no title in the local database uses it.
fn figurine(c: char) -> Option<char> {
    match c {
        '\u{e024}' => Some('K'),
        '\u{e025}' => Some('Q'),
        '\u{e026}' => Some('R'),
        '\u{e027}' => Some('B'),
        '\u{e028}' => Some('N'),
        '\u{e029}' => Some('P'),
        _ => None,
    }
}

/// The result as ChessBase's export writes it: `*` where the record has
/// result 7 (both players lost); `0-0` is no PGN result token.
pub fn result_tag(result: GameResult) -> &'static str {
    match result {
        GameResult::BothLost => "*",
        other => other.pgn(),
    }
}

/// A game's decode error as an I/O error carrying it.
fn as_io(e: Error) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, e)
}

/// Writes PGN into a caller's sink, reusing its buffers from game to game.
#[derive(Debug, Default)]
pub struct PgnWriter {
    tree: Tree,
    /// One game whole: its tags, its movetext, its result token and the blank
    /// line after it, so the sink is written once per game.
    game: String,
    /// Every annotation's (position, byte offset), ascending: the game's
    /// index for [`Commentary`], reused game to game.
    index: Vec<(i32, u32)>,
    /// The game comment's `[%evp …]`, empty when the game has none.
    evp: String,
    /// The parts of the comment being written, reused: each [`comments::Part`]
    /// keeps its buffer across games.
    parts: comments::Parts,
    /// The tag path's entity-name and round buffers, reused game to game.
    names: Names,
    /// The boards of the starts seen, so a standard start is built once
    /// instead of parsed from a FEN per game.
    starts: StartCache,
    /// The movetext traversal's step stack, reused game to game.
    steps: Vec<EmitStep>,
}

impl PgnWriter {
    /// A writer with empty buffers.
    pub fn new() -> PgnWriter {
        PgnWriter { tree: Tree::new(), ..Default::default() }
    }

    /// The bytes the writer keeps for reuse (its high-water mark): a caller
    /// exporting many games holds one game's worth, not a database's.
    pub fn capacity(&self) -> usize {
        self.game.capacity()
            + self.tree.nodes.capacity() * size_of::<Node>()
            + self.index.capacity() * size_of::<(i32, u32)>()
            + self.evp.capacity()
            + self.parts.capacity()
            + std::mem::size_of::<Names>()
            + self.starts.len() * std::mem::size_of::<(Start, Board)>()
    }

    /// Writes game `game` of `header` as PGN: the tags, the movetext with its
    /// variations and annotations, and the result. Entities come from
    /// `entities`; the game must be a game (not a guiding text). `anns` is the
    /// game's annotations as [`GameAnnotations::parse`] read them; `None`
    /// writes the moves alone.
    pub fn write_game<H: Head>(
        &mut self,
        out: &mut impl Write,
        header: &H,
        entities: &Entities,
        game: &GameMoves<'_>,
        anns: Option<&GameAnnotations<'_>>,
    ) -> io::Result<()> {
        if header.kind() != RecordKind::Game {
            return Err(io::Error::new(io::ErrorKind::InvalidData, format!("record {} is not a game", header.id())));
        }
        let what = GameRef::new(header.id());
        let start = start_as_played(what, game).map_err(as_io)?;
        let board = start_board_cached(&start, &mut self.starts).map_err(as_io)?;
        self.tree.clear();
        // The whole game — tags, movetext, result token, blank line — in one
        // buffer, written with one `write_all`: two buffers meant two calls
        // into the sink per game, eleven million times over.
        self.game.clear();
        let stats = walk_from(what, game, &start, &mut self.tree).map_err(as_io)?;
        write_tags(&mut self.game, header, entities, &start, &board, stats.total_plies, &mut self.names)
            .map_err(as_io)?;
        // An annotation record with no items writes nothing anywhere: no game
        // comment, no note before or after a move, no `[%evp]`. Treating it as
        // no annotations at all takes the movetext's direct path, which is the
        // same bytes without the per-move annotation machinery - 10.8 million
        // of the 11.1 million games in the reference database have no
        // annotations, and the machinery cost them 45 seconds of the export.
        let anns = anns.filter(|a| !a.is_empty());
        match anns {
            None => emit(&self.tree, &mut Bare, &mut self.game, &mut self.steps).map_err(as_io)?,
            Some(a) => {
                a.check_positions(stats.total_plies).map_err(as_io)?;
                self.prepare(a).map_err(as_io)?;
                let mut notes = Commentary {
                    anns: a,
                    index: &self.index,
                    evp: &self.evp,
                    parts: &mut self.parts,
                    moves: stats.total_plies,
                    last: self.tree.main_line_last(),
                };
                notes.game_comment(&mut self.game).map_err(as_io)?;
                emit(&self.tree, &mut notes, &mut self.game, &mut self.steps).map_err(as_io)?;
            }
        }
        // The result token and the blank line that ends a game, in the same
        // buffer, so the sink is written once.
        // Short strings go in byte by byte: a `push_str` of one or two bytes is
        // a `memcpy` call, and this is once per game.
        for b in result_tag(header.result()).as_bytes() {
            self.game.push(char::from(*b));
        }
        self.game.push('\n');
        self.game.push('\n');
        out.write_all(self.game.as_bytes())
    }

    /// Fills the writer's index and `[%evp …]` from a game's annotations:
    /// one walk over the record, no allocation past the buffers' growth.
    fn prepare(&mut self, a: &GameAnnotations<'_>) -> Result<()> {
        self.index.clear();
        self.evp.clear();
        let mut ascending = true;
        let mut prev = i32::MIN;
        let mut evp = false;
        for item in a.iter() {
            let item = item?;
            ascending &= item.position >= prev;
            prev = item.position;
            self.index.push((item.position, item.offset));
            if let Annotation::Other { code: 0x26, data } = item.annotation
                && !evp
                && item.position == GAME_POSITION
            {
                // Entry `k` is the position after the main line's ply `k`,
                // the first the start position; ChessBase writes the list
                // as `[%evp 0,<count−1>,…]` in the game's comment.
                if let Some(entries) = timing::evaluations(data, true) {
                    comments::write_evp(&mut self.evp, &entries);
                    evp = !self.evp.is_empty();
                }
            }
        }
        if !ascending {
            // The format promises positions in ascending order; a record that
            // breaks it sorts once here, stably, so that same-position order
            // (which is meaningful) survives.
            self.index.sort_by_key(|&(p, _)| p);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Write as _;

    /// The hand-written number writers agree with `core::fmt` on the values
    /// the format can hold.
    #[test]
    fn number_writers_match_the_formatting_machinery() {
        for n in [0u16, 1, 9, 10, 99, 100, 999, 9999, u16::MAX] {
            let mut want = String::new();
            let _ = write!(want, "{n}");
            let mut got = String::new();
            push_u16(&mut got, n);
            assert_eq!(got, want, "u16 {n}");
            let mut want = String::new();
            let _ = write!(want, "{n}... ");
            let mut got = String::new();
            push_move_number(&mut got, n, true);
            assert_eq!(got, want, "black {n}");
            let mut want = String::new();
            let _ = write!(want, "{n}. ");
            let mut got = String::new();
            push_move_number(&mut got, n, false);
            assert_eq!(got, want, "white {n}");
        }
        for n in [0u32, 7, 10, 4096, 32768, u32::from(u16::MAX), u32::MAX] {
            let mut want = String::new();
            let _ = write!(want, "{n}");
            let mut got = String::new();
            push_u32(&mut got, n);
            assert_eq!(got, want, "u32 {n}");
        }
    }

    /// The tag writers produce what `writeln!` produced, escaping and all.
    #[test]
    fn tag_writers_match_the_formatting_machinery() {
        let cases = [
            ("Paris", "FRA"),
            ("a\\\"b", "c\\\\d"),
            ("Odds \u{e025}d1", ""),
            ("\u{201e}Zitat\u{201c}", "M\u{fc}nchen"),
            ("", ""),
        ];
        for (value, _) in cases {
            let mut want = String::new();
            let _ = writeln!(want, r#"[Event "{}"]"#, escape_old(value));
            let mut got = String::new();
            push_escaped_tag(&mut got, "[Event \"", value);
            assert_eq!(got, want, "Event {value:?}");
        }
        for (last, first) in [("Morphy", ""), ("Delaire", "H."), ("Ward", "JH"), ("Keres", "Paul"), ("", "")] {
            let name = player_name_old(last, first);
            let mut want = String::new();
            let _ = writeln!(want, r#"[White "{}"]"#, escape_old(&name));
            let mut got = String::new();
            push_escaped_player(&mut got, "[White \"", Some((last, first)));
            assert_eq!(got, want, "player {last:?} {first:?}");
        }
        let mut got = String::new();
        push_escaped_player(&mut got, "[White \"", None);
        assert_eq!(got, "[White \"?\"]\n");
        for n in [0u32, 1, 2404, 32767] {
            let mut want = String::new();
            let _ = writeln!(want, r#"[WhiteElo "{n}"]"#);
            let mut got = String::new();
            push_number_tag(&mut got, "[WhiteElo \"", n);
            assert_eq!(got, want, "elo {n}");
        }
    }

    /// The round tag writes what the old `round_tag` wrote.
    #[test]
    fn round_tag_matches_the_old_writer() {
        for (round, sub) in [(0, 0), (0, 4), (5, 0), (5, 2), (-1, 0), (1, 1), (0, 12)] {
            let mut want = String::new();
            let text = round_tag_old(round, sub);
            let _ = writeln!(want, r#"[Round "{}"]"#, if text.is_empty() { "?" } else { &text });
            let mut names = Names::default();
            let mut got = String::new();
            push_round(&mut got, (round, sub), &mut names);
            assert_eq!(got, want, "round {round}.{sub}");
        }
    }

    /// The escaping writer, against the returning `String` it replaces.
    fn escape_old(text: &str) -> String {
        let has_figurine = text.chars().any(|c| figurine(c).is_some());
        if !text.contains(['"', '\\']) && !has_figurine {
            return text.to_owned();
        }
        let mut out = String::with_capacity(text.len() + 2);
        for c in text.chars() {
            if let Some(letter) = figurine(c) {
                out.push(letter);
                continue;
            }
            if c == '"' || c == '\\' {
                out.push('\\');
            }
            out.push(c);
        }
        out
    }

    /// The player name, as the old `player_name` built it.
    fn player_name_old(last: &str, first: &str) -> String {
        if first.is_empty() {
            return if last.is_empty() { "?".to_owned() } else { last.to_owned() };
        }
        let initials =
            (1..=2).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit());
        format!("{last}, {first}{}", if initials { "." } else { "" })
    }

    /// The round text, as the old `round_tag` built it.
    fn round_tag_old(round: i32, sub: i32) -> String {
        if round <= 0 && sub > 0 {
            return format!("?.{sub}");
        }
        let mut buf = [0u8; ROUND_TEXT_BYTES];
        let text = round_text(round, sub, &mut buf);
        match (text.find('('), text.find(')')) {
            (Some(open), Some(close)) => format!("{}.{}", &text[..open], &text[open + 1..close]),
            _ => text.to_owned(),
        }
    }
}