Skip to main content

rsshogi_csa/
summary.rs

1//! Reading and writing the `BEGIN Game_Summary` block.
2//!
3//! The block is not a single line, so it does not go through
4//! [`parse_line`](crate::parse_line). Feed its lines to a [`GameSummaryReader`]
5//! instead, starting with `BEGIN Game_Summary` itself. The reader is a nested
6//! state machine: `BEGIN Time`, `BEGIN Time+`, `BEGIN Time-`, and
7//! `BEGIN Position` each push a sub-state, which is what lets the position body
8//! be captured verbatim instead of being mistaken for commands.
9
10use std::mem;
11
12use crate::error::{ParseError, ParseErrorKind};
13use crate::model::{Color, GameSummary, TimeConfig, TimeScale, TimeUnit};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16enum State {
17    AwaitBegin,
18    Summary,
19    Time(Option<Color>),
20    Position,
21    Done,
22}
23
24/// Assembles a [`GameSummary`] from the lines of one `BEGIN Game_Summary` block.
25///
26/// ```
27/// use rsshogi_csa::GameSummaryReader;
28///
29/// let block = "\
30/// BEGIN Game_Summary
31/// Protocol_Version:1.2
32/// Your_Turn:+
33/// BEGIN Time
34/// Time_Unit:1sec
35/// Total_Time:900
36/// END Time
37/// BEGIN Position
38/// PI
39/// +
40/// END Position
41/// END Game_Summary";
42///
43/// let mut reader = GameSummaryReader::new();
44/// let mut summary = None;
45/// for line in block.lines() {
46///     if let Some(done) = reader.feed(line).unwrap() {
47///         summary = Some(done);
48///     }
49/// }
50///
51/// let summary = summary.expect("block is complete");
52/// assert_eq!(summary.time_black.total_time, Some(900));
53/// assert_eq!(summary.position_lines, vec!["PI".to_string(), "+".to_string()]);
54/// ```
55#[derive(Debug, Clone)]
56pub struct GameSummaryReader {
57    state: State,
58    summary: GameSummary,
59}
60
61impl GameSummaryReader {
62    /// A reader waiting for `BEGIN Game_Summary`.
63    #[must_use]
64    pub fn new() -> Self {
65        Self { state: State::AwaitBegin, summary: GameSummary::default() }
66    }
67
68    /// Whether the block has been closed by `END Game_Summary`.
69    #[must_use]
70    pub const fn is_complete(&self) -> bool {
71        matches!(self.state, State::Done)
72    }
73
74    /// Feeds one line, returning the summary once `END Game_Summary` arrives.
75    ///
76    /// Lines inside `BEGIN Position` are stored verbatim apart from trailing
77    /// newline characters, because board rows carry significant trailing spaces.
78    pub fn feed(&mut self, raw: &str) -> Result<Option<GameSummary>, ParseError> {
79        let line = raw.trim_end_matches(['\r', '\n']);
80        match self.state {
81            State::AwaitBegin => {
82                if line.trim() == "BEGIN Game_Summary" {
83                    self.state = State::Summary;
84                    Ok(None)
85                } else {
86                    Err(ParseError::new(ParseErrorKind::UnexpectedLine, line))
87                }
88            }
89            State::Summary => self.feed_summary(line),
90            State::Time(color) => self.feed_time(line, color),
91            State::Position => {
92                if line.trim() == "END Position" {
93                    self.state = State::Summary;
94                } else if line.trim() == "END Game_Summary" {
95                    return Err(ParseError::new(ParseErrorKind::UnexpectedLine, line));
96                } else {
97                    self.summary.position_lines.push(line.to_owned());
98                }
99                Ok(None)
100            }
101            State::Done => Err(ParseError::new(ParseErrorKind::UnexpectedLine, line)),
102        }
103    }
104
105    fn feed_summary(&mut self, line: &str) -> Result<Option<GameSummary>, ParseError> {
106        let trimmed = line.trim();
107        if trimmed.is_empty() {
108            return Ok(None);
109        }
110        match trimmed {
111            "END Game_Summary" => {
112                self.state = State::Done;
113                return Ok(Some(mem::take(&mut self.summary)));
114            }
115            "BEGIN Time" => self.state = State::Time(None),
116            "BEGIN Time+" => self.state = State::Time(Some(Color::Black)),
117            "BEGIN Time-" => self.state = State::Time(Some(Color::White)),
118            "BEGIN Position" => self.state = State::Position,
119            _ => {
120                let (key, value) = split_field(trimmed)?;
121                self.set_summary_field(trimmed, key, value)?;
122            }
123        }
124        Ok(None)
125    }
126
127    fn feed_time(
128        &mut self,
129        line: &str,
130        color: Option<Color>,
131    ) -> Result<Option<GameSummary>, ParseError> {
132        let trimmed = line.trim();
133        if trimmed.is_empty() {
134            return Ok(None);
135        }
136        if trimmed == time_terminator(color) {
137            self.state = State::Summary;
138            return Ok(None);
139        }
140        let (key, value) = split_field(trimmed)?;
141        self.set_time_field(trimmed, key, value, color)?;
142        Ok(None)
143    }
144
145    fn set_summary_field(&mut self, line: &str, key: &str, value: &str) -> Result<(), ParseError> {
146        let summary = &mut self.summary;
147        match key {
148            "Protocol_Version" => summary.protocol_version = Some(value.to_owned()),
149            "Protocol_Mode" => summary.protocol_mode = Some(value.to_owned()),
150            "Format" => summary.format = Some(value.to_owned()),
151            "Declaration" => summary.declaration = Some(value.to_owned()),
152            "Game_ID" => summary.game_id = Some(value.to_owned()),
153            "Name+" => summary.name_black = Some(value.to_owned()),
154            "Name-" => summary.name_white = Some(value.to_owned()),
155            "Your_Turn" => summary.your_turn = Some(parse_color(line, "Your_Turn", value)?),
156            "To_Move" => summary.to_move = Some(parse_color(line, "To_Move", value)?),
157            "Rematch_On_Draw" => summary.rematch_on_draw = Some(value.to_owned()),
158            "Max_Moves" => summary.max_moves = Some(parse_u32(line, "Max_Moves", value)?),
159            _ => summary.extras.push((key.to_owned(), value.to_owned())),
160        }
161        Ok(())
162    }
163
164    fn set_time_field(
165        &mut self,
166        line: &str,
167        key: &str,
168        value: &str,
169        color: Option<Color>,
170    ) -> Result<(), ParseError> {
171        match key {
172            "Time_Unit" => {
173                let unit = parse_time_unit(line, value)?;
174                self.apply_time(color, |config| config.time_unit = Some(unit));
175            }
176            "Total_Time" => {
177                let parsed = parse_u64(line, "Total_Time", value)?;
178                self.apply_time(color, |config| config.total_time = Some(parsed));
179            }
180            "Byoyomi" => {
181                let parsed = parse_u64(line, "Byoyomi", value)?;
182                self.apply_time(color, |config| config.byoyomi = Some(parsed));
183            }
184            "Delay" => {
185                let parsed = parse_u64(line, "Delay", value)?;
186                self.apply_time(color, |config| config.delay = Some(parsed));
187            }
188            "Increment" => {
189                let parsed = parse_u64(line, "Increment", value)?;
190                self.apply_time(color, |config| config.increment = Some(parsed));
191            }
192            "Least_Time_Per_Move" => {
193                let parsed = parse_u64(line, "Least_Time_Per_Move", value)?;
194                self.apply_time(color, |config| config.least_time_per_move = Some(parsed));
195            }
196            "Time_Roundup" => {
197                let parsed = parse_yes_no(line, "Time_Roundup", value)?;
198                self.apply_time(color, |config| config.time_roundup = Some(parsed));
199            }
200            "Remaining_Time" => {
201                let parsed = parse_u64(line, "Remaining_Time", value)?;
202                self.apply_time(color, |config| config.remaining_time = Some(parsed));
203            }
204            "Remaining_Time+" => {
205                let parsed = parse_u64(line, "Remaining_Time+", value)?;
206                self.summary.time_black.remaining_time = Some(parsed);
207            }
208            "Remaining_Time-" => {
209                let parsed = parse_u64(line, "Remaining_Time-", value)?;
210                self.summary.time_white.remaining_time = Some(parsed);
211            }
212            "Last_Move" => self.summary.last_move = Some(value.to_owned()),
213            "Current_Turn" => {
214                self.summary.current_turn = Some(parse_u32(line, "Current_Turn", value)?);
215            }
216            _ => {
217                let entry = (key.to_owned(), value.to_owned());
218                self.apply_time(color, |config| config.extras.push(entry.clone()));
219            }
220        }
221        Ok(())
222    }
223
224    fn apply_time(&mut self, color: Option<Color>, mut apply: impl FnMut(&mut TimeConfig)) {
225        match color {
226            Some(Color::Black) => apply(&mut self.summary.time_black),
227            Some(Color::White) => apply(&mut self.summary.time_white),
228            None => {
229                apply(&mut self.summary.time_black);
230                apply(&mut self.summary.time_white);
231            }
232        }
233    }
234}
235
236const fn time_terminator(color: Option<Color>) -> &'static str {
237    match color {
238        None => "END Time",
239        Some(Color::Black) => "END Time+",
240        Some(Color::White) => "END Time-",
241    }
242}
243
244impl Default for GameSummaryReader {
245    fn default() -> Self {
246        Self::new()
247    }
248}
249
250impl TimeConfig {
251    /// Whether no field of this time control was declared.
252    #[must_use]
253    pub fn is_empty(&self) -> bool {
254        *self == Self::default()
255    }
256
257    fn push_body(&self, out: &mut Vec<String>) {
258        push_field(out, "Time_Unit", self.time_unit.map(|unit| unit.to_string()));
259        push_field(out, "Total_Time", self.total_time.map(|v| v.to_string()));
260        push_field(out, "Byoyomi", self.byoyomi.map(|v| v.to_string()));
261        push_field(out, "Delay", self.delay.map(|v| v.to_string()));
262        push_field(out, "Increment", self.increment.map(|v| v.to_string()));
263        push_field(out, "Least_Time_Per_Move", self.least_time_per_move.map(|v| v.to_string()));
264        push_field(
265            out,
266            "Time_Roundup",
267            self.time_roundup.map(|v| if v { "YES" } else { "NO" }.to_owned()),
268        );
269        for (key, value) in &self.extras {
270            out.push(format!("{key}:{value}"));
271        }
272    }
273}
274
275impl GameSummary {
276    /// Renders the summary as protocol lines, without trailing newlines.
277    ///
278    /// Field order follows `shogi-server`, so a proposal parsed from it renders
279    /// back byte for byte. A block that declared identical per-color time
280    /// sections is re-emitted as one shared `BEGIN Time` section.
281    #[must_use]
282    pub fn to_lines(&self) -> Vec<String> {
283        let mut out = vec!["BEGIN Game_Summary".to_owned()];
284        push_field(&mut out, "Protocol_Version", self.protocol_version.clone());
285        push_field(&mut out, "Protocol_Mode", self.protocol_mode.clone());
286        push_field(&mut out, "Format", self.format.clone());
287        push_field(&mut out, "Declaration", self.declaration.clone());
288        push_field(&mut out, "Game_ID", self.game_id.clone());
289        push_field(&mut out, "Name+", self.name_black.clone());
290        push_field(&mut out, "Name-", self.name_white.clone());
291        push_field(&mut out, "Your_Turn", self.your_turn.map(|c| c.to_string()));
292        push_field(&mut out, "Rematch_On_Draw", self.rematch_on_draw.clone());
293        push_field(&mut out, "To_Move", self.to_move.map(|c| c.to_string()));
294        push_field(&mut out, "Max_Moves", self.max_moves.map(|v| v.to_string()));
295        for (key, value) in &self.extras {
296            out.push(format!("{key}:{value}"));
297        }
298
299        self.push_time_section(&mut out);
300
301        if !self.position_lines.is_empty() {
302            out.push("BEGIN Position".to_owned());
303            out.extend(self.position_lines.iter().cloned());
304            out.push("END Position".to_owned());
305        }
306
307        out.push("END Game_Summary".to_owned());
308        out
309    }
310
311    fn push_time_section(&self, out: &mut Vec<String>) {
312        if self.time_black.is_empty() && self.time_white.is_empty() {
313            return;
314        }
315
316        if self.time_black.eq_ignoring_remaining(&self.time_white) {
317            out.push("BEGIN Time".to_owned());
318            self.time_black.push_body(out);
319            push_field(
320                out,
321                "Remaining_Time+",
322                self.time_black.remaining_time.map(|v| v.to_string()),
323            );
324            push_field(
325                out,
326                "Remaining_Time-",
327                self.time_white.remaining_time.map(|v| v.to_string()),
328            );
329            self.push_show_fields(out);
330            out.push("END Time".to_owned());
331            return;
332        }
333
334        out.push("BEGIN Time+".to_owned());
335        self.time_black.push_body(out);
336        push_field(out, "Remaining_Time+", self.time_black.remaining_time.map(|v| v.to_string()));
337        self.push_show_fields(out);
338        out.push("END Time+".to_owned());
339
340        out.push("BEGIN Time-".to_owned());
341        self.time_white.push_body(out);
342        push_field(out, "Remaining_Time-", self.time_white.remaining_time.map(|v| v.to_string()));
343        out.push("END Time-".to_owned());
344    }
345
346    fn push_show_fields(&self, out: &mut Vec<String>) {
347        push_field(out, "Last_Move", self.last_move.clone());
348        push_field(out, "Current_Turn", self.current_turn.map(|v| v.to_string()));
349    }
350}
351
352fn push_field(out: &mut Vec<String>, key: &str, value: Option<String>) {
353    if let Some(value) = value {
354        out.push(format!("{key}:{value}"));
355    }
356}
357
358fn split_field(line: &str) -> Result<(&str, &str), ParseError> {
359    line.split_once(':').ok_or_else(|| ParseError::new(ParseErrorKind::UnexpectedLine, line))
360}
361
362fn parse_color(line: &str, key: &'static str, value: &str) -> Result<Color, ParseError> {
363    let mut chars = value.chars();
364    let (Some(first), None) = (chars.next(), chars.next()) else {
365        return Err(ParseError::new(ParseErrorKind::InvalidField(key), line));
366    };
367    Color::from_csa(first).ok_or_else(|| ParseError::new(ParseErrorKind::InvalidField(key), line))
368}
369
370fn parse_u64(line: &str, key: &'static str, value: &str) -> Result<u64, ParseError> {
371    value.parse().map_err(|_| ParseError::new(ParseErrorKind::InvalidNumber(key), line))
372}
373
374fn parse_u32(line: &str, key: &'static str, value: &str) -> Result<u32, ParseError> {
375    value.parse().map_err(|_| ParseError::new(ParseErrorKind::InvalidNumber(key), line))
376}
377
378fn parse_yes_no(line: &str, key: &'static str, value: &str) -> Result<bool, ParseError> {
379    match value.to_ascii_uppercase().as_str() {
380        "YES" | "TRUE" | "1" => Ok(true),
381        "NO" | "FALSE" | "0" => Ok(false),
382        _ => Err(ParseError::new(ParseErrorKind::InvalidField(key), line)),
383    }
384}
385
386fn parse_time_unit(line: &str, value: &str) -> Result<TimeUnit, ParseError> {
387    const SCALES: [(&str, TimeScale); 3] =
388        [("msec", TimeScale::Msec), ("sec", TimeScale::Sec), ("min", TimeScale::Min)];
389
390    for (suffix, scale) in SCALES {
391        let Some(head) = value.strip_suffix(suffix) else {
392            continue;
393        };
394        let count = if head.is_empty() {
395            1
396        } else {
397            head.parse()
398                .map_err(|_| ParseError::new(ParseErrorKind::InvalidNumber("Time_Unit"), line))?
399        };
400        return Ok(TimeUnit { count, scale });
401    }
402    Err(ParseError::new(ParseErrorKind::InvalidField("Time_Unit"), line))
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    const PROPOSAL: &str = "\
410BEGIN Game_Summary
411Protocol_Version:1.2
412Protocol_Mode:Server
413Format:Shogi 1.0
414Declaration:Jishogi 1.1
415Game_ID:wdoor+floodgate-900-0+black+white+20260804120000
416Name+:black
417Name-:white
418Your_Turn:+
419Rematch_On_Draw:NO
420To_Move:+
421Max_Moves:256
422BEGIN Time
423Time_Unit:1sec
424Total_Time:900
425Byoyomi:0
426Increment:0
427Least_Time_Per_Move:0
428END Time
429BEGIN Position
430P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
431P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
432+
433END Position
434END Game_Summary";
435
436    fn read(block: &str) -> GameSummary {
437        let mut reader = GameSummaryReader::new();
438        let mut result = None;
439        for line in block.lines() {
440            let done = reader
441                .feed(line)
442                .unwrap_or_else(|err| panic!("`{line}` should be accepted: {err}"));
443            if let Some(summary) = done {
444                result = Some(summary);
445            }
446        }
447        assert!(reader.is_complete(), "reader should reach END Game_Summary");
448        result.expect("block should produce a summary")
449    }
450
451    #[test]
452    fn proposal_round_trips_byte_for_byte() {
453        let summary = read(PROPOSAL);
454        assert_eq!(summary.to_lines().join("\n"), PROPOSAL);
455    }
456
457    #[test]
458    fn proposal_fields_are_typed() {
459        let summary = read(PROPOSAL);
460        assert_eq!(summary.protocol_version.as_deref(), Some("1.2"));
461        assert_eq!(summary.your_turn, Some(Color::Black));
462        assert_eq!(summary.to_move, Some(Color::Black));
463        assert_eq!(summary.max_moves, Some(256));
464        assert_eq!(summary.name_black.as_deref(), Some("black"));
465        assert_eq!(summary.time_black.unit(), TimeUnit::SECOND);
466        assert_eq!(summary.time_black.total_time, Some(900));
467        assert_eq!(summary.time_white.total_time, Some(900));
468        assert_eq!(summary.position_lines.len(), 3);
469    }
470
471    #[test]
472    fn position_body_keeps_significant_trailing_spaces() {
473        // The board row is built here rather than written inline, because a
474        // trailing space in a source literal does not survive editors or hooks.
475        let row = format!("P2 * -HI *  *  *  *  * -KA *{}", ' ');
476        let block =
477            format!("BEGIN Game_Summary\nBEGIN Position\n{row}\n+\nEND Position\nEND Game_Summary");
478        let summary = read(&block);
479        assert_eq!(summary.position_lines[0], row);
480        assert_eq!(summary.to_lines().join("\n"), block);
481    }
482
483    #[test]
484    fn per_color_time_blocks_are_kept_apart() {
485        let block = "\
486BEGIN Game_Summary
487BEGIN Time+
488Time_Unit:1sec
489Total_Time:600
490END Time+
491BEGIN Time-
492Time_Unit:1sec
493Total_Time:900
494END Time-
495END Game_Summary";
496        let summary = read(block);
497        assert_eq!(summary.time_black.total_time, Some(600));
498        assert_eq!(summary.time_white.total_time, Some(900));
499        assert_eq!(summary.to_lines().join("\n"), block);
500    }
501
502    #[test]
503    fn time_blocks_require_matching_terminators() {
504        for (begin, end) in
505            [("BEGIN Time", "END Time+"), ("BEGIN Time+", "END Time-"), ("BEGIN Time-", "END Time")]
506        {
507            let mut reader = GameSummaryReader::new();
508            reader.feed("BEGIN Game_Summary").expect("begin summary");
509            reader.feed(begin).expect("begin time block");
510            assert!(reader.feed(end).is_err(), "{begin} must reject {end}");
511        }
512
513        for (begin, end, black, white) in [
514            ("BEGIN Time", "END Time", Some(60), Some(60)),
515            ("BEGIN Time+", "END Time+", Some(60), None),
516            ("BEGIN Time-", "END Time-", None, Some(60)),
517        ] {
518            let summary = read(&format!(
519                "BEGIN Game_Summary\n{begin}\nTotal_Time:60\n{end}\nEND Game_Summary"
520            ));
521            assert_eq!(summary.time_black.total_time, black);
522            assert_eq!(summary.time_white.total_time, white);
523        }
524    }
525
526    #[test]
527    fn position_block_must_end_before_the_summary() {
528        let mut reader = GameSummaryReader::new();
529        reader.feed("BEGIN Game_Summary").expect("begin summary");
530        reader.feed("BEGIN Position").expect("begin position");
531        reader.feed("PI").expect("position line");
532        assert!(reader.feed("END Game_Summary").is_err());
533    }
534
535    #[test]
536    fn show_output_round_trips() {
537        let block = "\
538BEGIN Game_Summary
539Protocol_Version:1.2
540Game_ID:game-1
541Rematch_On_Draw:NO
542To_Move:+
543Max_Moves:256
544BEGIN Time
545Time_Unit:1sec
546Total_Time:1500
547Byoyomi:0
548Increment:0
549Least_Time_Per_Move:0
550Remaining_Time+:1400
551Remaining_Time-:1450
552Last_Move:+7776FU,T12
553Current_Turn:2
554END Time
555END Game_Summary";
556        let summary = read(block);
557        assert_eq!(summary.time_black.remaining_time, Some(1400));
558        assert_eq!(summary.time_white.remaining_time, Some(1450));
559        assert_eq!(summary.last_move.as_deref(), Some("+7776FU,T12"));
560        assert_eq!(summary.current_turn, Some(2));
561        assert_eq!(summary.to_lines().join("\n"), block);
562    }
563
564    #[test]
565    fn resumed_position_carries_moves() {
566        let block = "\
567BEGIN Game_Summary
568Your_Turn:-
569BEGIN Position
570PI
571+
572+7776FU,T2
573-3334FU,T5
574END Position
575END Game_Summary";
576        let summary = read(block);
577        let (board, moves) = summary.position_split();
578        assert_eq!(board, ["PI".to_owned(), "+".to_owned()]);
579        assert_eq!(moves, ["+7776FU,T2".to_owned(), "-3334FU,T5".to_owned()]);
580    }
581
582    #[test]
583    fn unknown_fields_are_preserved_in_order() {
584        let block = "\
585BEGIN Game_Summary
586Protocol_Version:1.2
587Future_Field:whatever
588BEGIN Time
589Total_Time:60
590Future_Time_Field:7
591END Time
592END Game_Summary";
593        let summary = read(block);
594        assert_eq!(summary.extras, [("Future_Field".to_owned(), "whatever".to_owned())]);
595        assert_eq!(summary.time_black.extras, [("Future_Time_Field".to_owned(), "7".to_owned())]);
596        assert_eq!(summary.to_lines().join("\n"), block);
597    }
598
599    #[test]
600    fn time_unit_variants() {
601        assert_eq!(
602            parse_time_unit("Time_Unit:1sec", "1sec").expect("1sec"),
603            TimeUnit { count: 1, scale: TimeScale::Sec }
604        );
605        assert_eq!(
606            parse_time_unit("Time_Unit:1min", "1min").expect("1min"),
607            TimeUnit { count: 1, scale: TimeScale::Min }
608        );
609        assert_eq!(
610            parse_time_unit("Time_Unit:500msec", "500msec").expect("500msec"),
611            TimeUnit { count: 500, scale: TimeScale::Msec }
612        );
613        assert!(parse_time_unit("Time_Unit:1hour", "1hour").is_err());
614        assert!(parse_time_unit("Time_Unit:xsec", "xsec").is_err());
615    }
616
617    #[test]
618    fn reader_rejects_lines_outside_the_block() {
619        let mut reader = GameSummaryReader::new();
620        assert!(reader.feed("Protocol_Version:1.2").is_err());
621
622        let mut reader = GameSummaryReader::new();
623        reader.feed("BEGIN Game_Summary").expect("begin");
624        assert!(reader.feed("not a field").is_err());
625    }
626
627    #[test]
628    fn reader_rejects_lines_after_the_block() {
629        let mut reader = GameSummaryReader::new();
630        reader.feed("BEGIN Game_Summary").expect("begin");
631        reader.feed("END Game_Summary").expect("end");
632        assert!(reader.feed("Protocol_Version:1.2").is_err());
633    }
634
635    #[test]
636    fn malformed_numbers_are_reported() {
637        let mut reader = GameSummaryReader::new();
638        reader.feed("BEGIN Game_Summary").expect("begin");
639        assert!(reader.feed("Max_Moves:many").is_err());
640        assert!(reader.feed("Your_Turn:?").is_err());
641    }
642}