Skip to main content

rsshogi_csa/
model.rs

1//! Command model for the CSA server protocol.
2//!
3//! Everything here is line-shaped and board-agnostic. Moves are kept as
4//! validated text and the `BEGIN Position` body is kept verbatim, so this crate
5//! never needs a board representation.
6
7use std::fmt;
8
9/// Which side of the board a CSA `+` / `-` marker refers to.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Color {
12    /// Sente, spelled `+` on the wire.
13    Black,
14    /// Gote, spelled `-` on the wire.
15    White,
16}
17
18impl Color {
19    /// The wire character for this color.
20    #[must_use]
21    pub const fn as_csa(self) -> char {
22        match self {
23            Self::Black => '+',
24            Self::White => '-',
25        }
26    }
27
28    /// Reads a color from its wire character.
29    #[must_use]
30    pub const fn from_csa(value: char) -> Option<Self> {
31        match value {
32            '+' => Some(Self::Black),
33            '-' => Some(Self::White),
34            _ => None,
35        }
36    }
37
38    /// The opposite color.
39    #[must_use]
40    pub const fn flip(self) -> Self {
41        match self {
42            Self::Black => Self::White,
43            Self::White => Self::Black,
44        }
45    }
46}
47
48impl fmt::Display for Color {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.write_str(match self {
51            Self::Black => "+",
52            Self::White => "-",
53        })
54    }
55}
56
57/// The turn a client asks for in `%%GAME` / `%%CHALLENGE`.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum TurnPreference {
60    /// `+`
61    Black,
62    /// `-`
63    White,
64    /// `*`, meaning the server decides.
65    Either,
66}
67
68impl TurnPreference {
69    /// The wire character for this preference.
70    #[must_use]
71    pub const fn as_csa(self) -> char {
72        match self {
73            Self::Black => '+',
74            Self::White => '-',
75            Self::Either => '*',
76        }
77    }
78
79    /// Reads a preference from its wire character.
80    #[must_use]
81    pub const fn from_csa(value: char) -> Option<Self> {
82        match value {
83            '+' => Some(Self::Black),
84            '-' => Some(Self::White),
85            '*' => Some(Self::Either),
86            _ => None,
87        }
88    }
89}
90
91impl fmt::Display for TurnPreference {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        write!(f, "{}", self.as_csa())
94    }
95}
96
97/// The fourteen CSA piece names, in the spelling used by move records.
98const PIECE_NAMES: [&str; 14] =
99    ["FU", "KY", "KE", "GI", "KI", "KA", "HI", "OU", "TO", "NY", "NK", "NG", "UM", "RY"];
100
101/// A syntactically valid CSA move such as `+7776FU`.
102///
103/// Validation is syntactic only: sign, valid source and destination coordinates,
104/// and a known piece name.
105/// Whether the move is legal in a given position is not this crate's concern.
106#[derive(Debug, Clone, PartialEq, Eq, Hash)]
107pub struct CsaMove(String);
108
109impl CsaMove {
110    /// Parses a move, returning `None` if it is not syntactically a CSA move.
111    ///
112    /// ```
113    /// use rsshogi_csa::CsaMove;
114    ///
115    /// assert!(CsaMove::parse("+7776FU").is_some());
116    /// assert!(CsaMove::parse("+0076FU").is_some()); // drop
117    /// assert!(CsaMove::parse("+0000FU").is_none()); // destination is not a square
118    /// assert!(CsaMove::parse("+7776XX").is_none()); // unknown piece
119    /// ```
120    #[must_use]
121    pub fn parse(value: &str) -> Option<Self> {
122        let bytes = value.as_bytes();
123        if bytes.len() != 7 {
124            return None;
125        }
126        if bytes[0] != b'+' && bytes[0] != b'-' {
127            return None;
128        }
129        if !(bytes[1..3] == *b"00" || is_board_square(&bytes[1..3]))
130            || !is_board_square(&bytes[3..5])
131        {
132            return None;
133        }
134        let piece = &value[5..7];
135        if !PIECE_NAMES.contains(&piece) {
136            return None;
137        }
138        Some(Self(value.to_owned()))
139    }
140
141    /// The move as it appears on the wire.
142    #[must_use]
143    pub fn as_str(&self) -> &str {
144        &self.0
145    }
146
147    /// The side that plays this move.
148    #[must_use]
149    pub fn color(&self) -> Color {
150        // `parse` guarantees the first byte is `+` or `-`.
151        if self.0.starts_with('+') {
152            Color::Black
153        } else {
154            Color::White
155        }
156    }
157
158    /// Whether the move drops a piece from hand, spelled with a `00` origin.
159    #[must_use]
160    pub fn is_drop(&self) -> bool {
161        &self.0[1..3] == "00"
162    }
163
164    /// The piece name written after the destination square.
165    #[must_use]
166    pub fn piece_name(&self) -> &str {
167        &self.0[5..7]
168    }
169}
170
171fn is_board_square(bytes: &[u8]) -> bool {
172    matches!(bytes, [b'1'..=b'9', b'1'..=b'9'])
173}
174
175impl fmt::Display for CsaMove {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        f.write_str(&self.0)
178    }
179}
180
181/// A move line, optionally annotated with consumed time and a comment.
182///
183/// The server annotates broadcast moves with `,T<integer>`. Clients may
184/// annotate their own moves with a `,'` comment, which floodgate uses to carry
185/// evaluation and principal variation.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct MoveLine {
188    /// The move itself.
189    pub csa: CsaMove,
190    /// Raw integer time annotation, without unit conversion.
191    ///
192    /// Normally expressed in `Time_Unit` units. Server implementations may
193    /// differ (for example, stopwatch clocks); the session consumer must define
194    /// the normalization. Fractional annotations are not supported.
195    pub elapsed: Option<u64>,
196    /// Comment text, without the leading `'`.
197    pub comment: Option<String>,
198}
199
200impl MoveLine {
201    /// A bare move with no annotations.
202    #[must_use]
203    pub const fn new(csa: CsaMove) -> Self {
204        Self { csa, elapsed: None, comment: None }
205    }
206}
207
208/// A `%`-prefixed special move.
209#[non_exhaustive]
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub enum SpecialMove {
212    /// `%TORYO`, resignation.
213    Toryo,
214    /// `%KACHI`, an entering-king declaration.
215    Kachi,
216    /// `%CHUDAN`, an abort. Note that `shogi-server` treats this as an illegal
217    /// move and awards the game to the opponent.
218    Chudan,
219    /// `%SENNICHITE`
220    Sennichite,
221    /// `%HIKIWAKE`
222    Hikiwake,
223    /// `%JISHOGI`
224    Jishogi,
225    /// `%MAX_MOVES`
226    MaxMoves,
227    /// `%TSUMI`
228    Tsumi,
229    /// `%FUZUMI`
230    Fuzumi,
231    /// `%TIME_UP`
232    TimeUp,
233    /// `%ILLEGAL_MOVE`
234    IllegalMove,
235    /// `%+ILLEGAL_ACTION`
236    IllegalActionBlack,
237    /// `%-ILLEGAL_ACTION`
238    IllegalActionWhite,
239    /// `%ERROR`
240    Error,
241    /// Any other `%` token, stored without the leading `%`.
242    Other(String),
243}
244
245impl SpecialMove {
246    /// The token without its leading `%`.
247    #[must_use]
248    pub fn as_token(&self) -> &str {
249        match self {
250            Self::Toryo => "TORYO",
251            Self::Kachi => "KACHI",
252            Self::Chudan => "CHUDAN",
253            Self::Sennichite => "SENNICHITE",
254            Self::Hikiwake => "HIKIWAKE",
255            Self::Jishogi => "JISHOGI",
256            Self::MaxMoves => "MAX_MOVES",
257            Self::Tsumi => "TSUMI",
258            Self::Fuzumi => "FUZUMI",
259            Self::TimeUp => "TIME_UP",
260            Self::IllegalMove => "ILLEGAL_MOVE",
261            Self::IllegalActionBlack => "+ILLEGAL_ACTION",
262            Self::IllegalActionWhite => "-ILLEGAL_ACTION",
263            Self::Error => "ERROR",
264            Self::Other(token) => token,
265        }
266    }
267
268    /// Reads a special move from its token, without the leading `%`.
269    #[must_use]
270    pub fn from_token(token: &str) -> Self {
271        match token {
272            "TORYO" => Self::Toryo,
273            "KACHI" => Self::Kachi,
274            "CHUDAN" => Self::Chudan,
275            "SENNICHITE" => Self::Sennichite,
276            "HIKIWAKE" => Self::Hikiwake,
277            "JISHOGI" => Self::Jishogi,
278            "MAX_MOVES" => Self::MaxMoves,
279            "TSUMI" => Self::Tsumi,
280            "FUZUMI" => Self::Fuzumi,
281            "TIME_UP" => Self::TimeUp,
282            "ILLEGAL_MOVE" => Self::IllegalMove,
283            "+ILLEGAL_ACTION" => Self::IllegalActionBlack,
284            "-ILLEGAL_ACTION" => Self::IllegalActionWhite,
285            "ERROR" => Self::Error,
286            other => Self::Other(other.to_owned()),
287        }
288    }
289}
290
291/// How a `#`-prefixed end marker classifies.
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
293pub enum EndMarkerKind {
294    /// States who won: `#WIN`, `#LOSE`, `#DRAW`, `#CENSORED`.
295    Outcome,
296    /// States why the game ended: `#RESIGN`, `#TIME_UP`, and friends.
297    Reason,
298    /// An unrecognized marker.
299    Unknown,
300}
301
302/// A `#`-prefixed terminal marker.
303///
304/// A finished game normally produces a short burst of these, for example
305/// `%TORYO`, `#RESIGN`, `#WIN`. `#CHUDAN` can arrive on its own.
306#[non_exhaustive]
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum EndMarker {
309    /// `#WIN`
310    Win,
311    /// `#LOSE`
312    Lose,
313    /// `#DRAW`
314    Draw,
315    /// `#CENSORED`
316    Censored,
317    /// `#CHUDAN`
318    Chudan,
319    /// `#RESIGN`
320    Resign,
321    /// `#TIME_UP`
322    TimeUp,
323    /// `#ILLEGAL_MOVE`
324    IllegalMove,
325    /// `#ILLEGAL_ACTION`
326    IllegalAction,
327    /// `#JISHOGI`
328    Jishogi,
329    /// `#SENNICHITE`
330    Sennichite,
331    /// `#OUTE_SENNICHITE`
332    OuteSennichite,
333    /// `#MAX_MOVES`
334    MaxMoves,
335    /// Any other `#` token, stored without the leading `#`.
336    Other(String),
337}
338
339impl EndMarker {
340    /// The token without its leading `#`.
341    #[must_use]
342    pub fn as_token(&self) -> &str {
343        match self {
344            Self::Win => "WIN",
345            Self::Lose => "LOSE",
346            Self::Draw => "DRAW",
347            Self::Censored => "CENSORED",
348            Self::Chudan => "CHUDAN",
349            Self::Resign => "RESIGN",
350            Self::TimeUp => "TIME_UP",
351            Self::IllegalMove => "ILLEGAL_MOVE",
352            Self::IllegalAction => "ILLEGAL_ACTION",
353            Self::Jishogi => "JISHOGI",
354            Self::Sennichite => "SENNICHITE",
355            Self::OuteSennichite => "OUTE_SENNICHITE",
356            Self::MaxMoves => "MAX_MOVES",
357            Self::Other(token) => token,
358        }
359    }
360
361    /// Reads an end marker from its token, without the leading `#`.
362    #[must_use]
363    pub fn from_token(token: &str) -> Self {
364        match token {
365            "WIN" => Self::Win,
366            "LOSE" => Self::Lose,
367            "DRAW" => Self::Draw,
368            "CENSORED" => Self::Censored,
369            "CHUDAN" => Self::Chudan,
370            "RESIGN" => Self::Resign,
371            "TIME_UP" => Self::TimeUp,
372            "ILLEGAL_MOVE" => Self::IllegalMove,
373            "ILLEGAL_ACTION" => Self::IllegalAction,
374            "JISHOGI" => Self::Jishogi,
375            "SENNICHITE" => Self::Sennichite,
376            "OUTE_SENNICHITE" => Self::OuteSennichite,
377            "MAX_MOVES" => Self::MaxMoves,
378            other => Self::Other(other.to_owned()),
379        }
380    }
381
382    /// Whether this marker states an outcome or a reason.
383    #[must_use]
384    pub const fn kind(&self) -> EndMarkerKind {
385        match self {
386            Self::Win | Self::Lose | Self::Draw | Self::Censored => EndMarkerKind::Outcome,
387            Self::Chudan
388            | Self::Resign
389            | Self::TimeUp
390            | Self::IllegalMove
391            | Self::IllegalAction
392            | Self::Jishogi
393            | Self::Sennichite
394            | Self::OuteSennichite
395            | Self::MaxMoves => EndMarkerKind::Reason,
396            Self::Other(_) => EndMarkerKind::Unknown,
397        }
398    }
399}
400
401/// A `##[TAG] ...` informational line from the server.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct InfoLine {
404    /// The tag between the brackets, such as `ERROR` or `WHO`.
405    pub tag: String,
406    /// Everything after the closing bracket, kept verbatim so the line round-trips.
407    ///
408    /// Most lines have a single leading space here. Use [`InfoLine::body`] to
409    /// read the text without it.
410    pub rest: String,
411}
412
413impl InfoLine {
414    /// The informational text with leading whitespace removed.
415    #[must_use]
416    pub fn body(&self) -> &str {
417        self.rest.trim_start()
418    }
419}
420
421/// A `%%`-prefixed administrative command.
422///
423/// Only the commands the client flow needs are typed. Everything else round-trips
424/// through [`MetaCommand::Other`] rather than growing a variant per server dialect.
425#[non_exhaustive]
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub enum MetaCommand {
428    /// `%%GAME`, `%%GAME <name>`, or `%%GAME <name> <turn>`.
429    ///
430    /// The bare form cancels an outstanding game request.
431    Game {
432        /// The requested game name, such as `floodgate-900-0`.
433        name: Option<String>,
434        /// The requested turn.
435        turn: Option<TurnPreference>,
436    },
437    /// `%%CHALLENGE <name> <turn>`.
438    Challenge {
439        /// The requested game name.
440        name: String,
441        /// The requested turn.
442        turn: TurnPreference,
443    },
444    /// `%%WHO`
445    Who,
446    /// `%%LIST`
447    List,
448    /// `%%SHOW <game_id>`
449    Show(String),
450    /// `%%CHAT <message>`
451    Chat(String),
452    /// `%%RATING`
453    Rating,
454    /// `%%VERSION`
455    Version,
456    /// `%%HELP`
457    Help,
458    /// Any other `%%` command. `name` excludes the leading `%%`.
459    Other {
460        /// The command name without its `%%` prefix.
461        name: String,
462        /// Remaining whitespace-separated arguments.
463        args: Vec<String>,
464    },
465}
466
467/// Which way a command travels.
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
469pub enum CsaCommandDirection {
470    /// Only a client sends this.
471    ClientToServer,
472    /// Only a server sends this.
473    ServerToClient,
474    /// Both sides send this.
475    Both,
476}
477
478/// One line of the CSA server protocol.
479#[non_exhaustive]
480#[derive(Debug, Clone, PartialEq, Eq)]
481pub enum CsaCommand {
482    /// `LOGIN <name> <password>` with an optional ` x1` suffix.
483    Login {
484        /// The account name.
485        name: String,
486        /// The password field, which in CSA mode also carries the game name.
487        password: String,
488        /// Whether the `x1` extension was requested.
489        x1: bool,
490    },
491    /// `LOGOUT`
492    Logout,
493    /// `AGREE` or `AGREE <game_id>`.
494    Agree {
495        /// The game id echoed back to the server.
496        game_id: Option<String>,
497    },
498    /// `REJECT` or `REJECT <game_id>`, sent by the client.
499    Reject {
500        /// The game id echoed back to the server.
501        game_id: Option<String>,
502    },
503    /// `CHALLENGE`, a legacy no-op the server answers with `CHALLENGE ACCEPTED`.
504    Challenge,
505    /// A `%%` administrative command.
506    Meta(MetaCommand),
507
508    /// `LOGIN:<name> OK`
509    LoginOk {
510        /// The account name the server accepted.
511        name: String,
512    },
513    /// `LOGIN:incorrect`
514    LoginIncorrect,
515    /// `LOGOUT:completed`
516    LogoutCompleted,
517    /// `CHALLENGE ACCEPTED`
518    ChallengeAccepted,
519    /// `BEGIN Game_Summary`, the first line of a game proposal.
520    ///
521    /// Feed this line and everything after it to [`crate::GameSummaryReader`].
522    BeginGameSummary,
523    /// `START:<game_id>`
524    Start {
525        /// The game id that is now in progress.
526        game_id: String,
527    },
528    /// `REJECT:<game_id> by <name>`, sent by the server to both players.
529    RejectNotice {
530        /// The rejected game id.
531        game_id: String,
532        /// Who rejected it, or `the Server (timed out)`.
533        by: String,
534    },
535    /// A `#`-prefixed terminal marker.
536    End(EndMarker),
537    /// A `##[TAG] ...` informational line.
538    Info(InfoLine),
539
540    /// A move, optionally annotated with elapsed time and a comment.
541    Move(MoveLine),
542    /// A `%`-prefixed special move, optionally annotated with elapsed time.
543    Special {
544        /// Which special move.
545        kind: SpecialMove,
546        /// Raw integer time annotation, with the same unit contract as [`MoveLine::elapsed`].
547        elapsed: Option<u64>,
548    },
549    /// An empty line, used as an application-level keepalive.
550    ///
551    /// The CSA rule is that a client must not send these more often than once
552    /// every 30 seconds.
553    KeepAlive,
554}
555
556impl CsaCommand {
557    /// Which way this command travels, or `None` when the direction is unknown.
558    #[must_use]
559    pub const fn direction(&self) -> Option<CsaCommandDirection> {
560        match self {
561            Self::Login { .. }
562            | Self::Logout
563            | Self::Agree { .. }
564            | Self::Reject { .. }
565            | Self::Challenge => Some(CsaCommandDirection::ClientToServer),
566            Self::Meta(meta) => match meta {
567                MetaCommand::Other { .. } => None,
568                _ => Some(CsaCommandDirection::ClientToServer),
569            },
570            Self::LoginOk { .. }
571            | Self::LoginIncorrect
572            | Self::LogoutCompleted
573            | Self::ChallengeAccepted
574            | Self::BeginGameSummary
575            | Self::Start { .. }
576            | Self::RejectNotice { .. }
577            | Self::End(_)
578            | Self::Info(_) => Some(CsaCommandDirection::ServerToClient),
579            Self::Move(_) | Self::Special { .. } | Self::KeepAlive => {
580                Some(CsaCommandDirection::Both)
581            }
582        }
583    }
584
585    /// Whether a client may send this command.
586    #[must_use]
587    pub const fn is_client_to_server(&self) -> bool {
588        matches!(
589            self.direction(),
590            Some(CsaCommandDirection::ClientToServer | CsaCommandDirection::Both)
591        )
592    }
593
594    /// Whether a server may send this command.
595    #[must_use]
596    pub const fn is_server_to_client(&self) -> bool {
597        matches!(
598            self.direction(),
599            Some(CsaCommandDirection::ServerToClient | CsaCommandDirection::Both)
600        )
601    }
602}
603
604/// The scale part of a `Time_Unit` value.
605#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
606pub enum TimeScale {
607    /// `msec`
608    Msec,
609    /// `sec`
610    Sec,
611    /// `min`
612    Min,
613}
614
615impl TimeScale {
616    /// Milliseconds in one unit of this scale.
617    #[must_use]
618    pub const fn millis(self) -> u64 {
619        match self {
620            Self::Msec => 1,
621            Self::Sec => 1_000,
622            Self::Min => 60_000,
623        }
624    }
625
626    /// The suffix used on the wire.
627    #[must_use]
628    pub const fn as_str(self) -> &'static str {
629        match self {
630            Self::Msec => "msec",
631            Self::Sec => "sec",
632            Self::Min => "min",
633        }
634    }
635}
636
637/// A `Time_Unit` value such as `1sec` or `1min`.
638#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
639pub struct TimeUnit {
640    /// How many scale units make one time unit.
641    pub count: u64,
642    /// The scale.
643    pub scale: TimeScale,
644}
645
646impl TimeUnit {
647    /// One second, the value `shogi-server` always sends for chess-clock games.
648    pub const SECOND: Self = Self { count: 1, scale: TimeScale::Sec };
649
650    /// The unit expressed in milliseconds, saturating instead of overflowing.
651    #[must_use]
652    pub const fn as_millis(self) -> u64 {
653        self.count.saturating_mul(self.scale.millis())
654    }
655}
656
657impl Default for TimeUnit {
658    fn default() -> Self {
659        Self::SECOND
660    }
661}
662
663impl fmt::Display for TimeUnit {
664    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665        write!(f, "{}{}", self.count, self.scale.as_str())
666    }
667}
668
669/// The time control of one side, as declared in a `BEGIN Time` block.
670///
671/// All durations are in `Time_Unit` units, exactly as they appear on the wire.
672/// Converting to milliseconds is the caller's job, because only the caller knows
673/// whether it wants to apply a safety margin.
674#[non_exhaustive]
675#[derive(Debug, Clone, Default, PartialEq, Eq)]
676pub struct TimeConfig {
677    /// `Time_Unit`
678    pub time_unit: Option<TimeUnit>,
679    /// `Total_Time`
680    pub total_time: Option<u64>,
681    /// `Byoyomi`
682    pub byoyomi: Option<u64>,
683    /// `Delay`
684    pub delay: Option<u64>,
685    /// `Increment`, granted up front by the server.
686    pub increment: Option<u64>,
687    /// `Least_Time_Per_Move`
688    pub least_time_per_move: Option<u64>,
689    /// `Time_Roundup`
690    pub time_roundup: Option<bool>,
691    /// `Remaining_Time+` or `Remaining_Time-`, present only in `%%SHOW` output.
692    pub remaining_time: Option<u64>,
693    /// Unrecognized `Key:Value` pairs, kept in wire order.
694    pub extras: Vec<(String, String)>,
695}
696
697impl TimeConfig {
698    /// A control that declares only its time unit.
699    ///
700    /// The type is `#[non_exhaustive]` because CSA can add time fields, so it is
701    /// built with these rather than with a struct literal.
702    ///
703    /// ```
704    /// use rsshogi_csa::{TimeConfig, TimeUnit};
705    ///
706    /// let control = TimeConfig::new(TimeUnit::SECOND).with_total_time(900).with_byoyomi(10);
707    /// assert_eq!(control.total_time, Some(900));
708    /// assert_eq!(control.byoyomi, Some(10));
709    /// ```
710    #[must_use]
711    pub fn new(unit: TimeUnit) -> Self {
712        Self { time_unit: Some(unit), ..Self::default() }
713    }
714
715    /// Sets `Total_Time`.
716    #[must_use]
717    pub const fn with_total_time(mut self, units: u64) -> Self {
718        self.total_time = Some(units);
719        self
720    }
721
722    /// Sets `Byoyomi`.
723    #[must_use]
724    pub const fn with_byoyomi(mut self, units: u64) -> Self {
725        self.byoyomi = Some(units);
726        self
727    }
728
729    /// Sets `Increment`.
730    #[must_use]
731    pub const fn with_increment(mut self, units: u64) -> Self {
732        self.increment = Some(units);
733        self
734    }
735
736    /// Sets `Delay`.
737    #[must_use]
738    pub const fn with_delay(mut self, units: u64) -> Self {
739        self.delay = Some(units);
740        self
741    }
742
743    /// Sets `Least_Time_Per_Move`.
744    #[must_use]
745    pub const fn with_least_time_per_move(mut self, units: u64) -> Self {
746        self.least_time_per_move = Some(units);
747        self
748    }
749
750    /// Sets `Time_Roundup`.
751    #[must_use]
752    pub const fn with_time_roundup(mut self, roundup: bool) -> Self {
753        self.time_roundup = Some(roundup);
754        self
755    }
756
757    /// Sets `Remaining_Time`.
758    #[must_use]
759    pub const fn with_remaining_time(mut self, units: u64) -> Self {
760        self.remaining_time = Some(units);
761        self
762    }
763
764    /// Whether two sides declare the same control, ignoring remaining time.
765    ///
766    /// `shogi-server` sends one shared `BEGIN Time` block, so this is what
767    /// decides whether [`GameSummary::to_lines`] emits a shared or split block.
768    #[must_use]
769    pub fn eq_ignoring_remaining(&self, other: &Self) -> bool {
770        self.time_unit == other.time_unit
771            && self.total_time == other.total_time
772            && self.byoyomi == other.byoyomi
773            && self.delay == other.delay
774            && self.increment == other.increment
775            && self.least_time_per_move == other.least_time_per_move
776            && self.time_roundup == other.time_roundup
777            && self.extras == other.extras
778    }
779
780    /// The declared time unit, defaulting to one second when absent.
781    #[must_use]
782    pub fn unit(&self) -> TimeUnit {
783        self.time_unit.unwrap_or_default()
784    }
785}
786
787/// A parsed `BEGIN Game_Summary` block.
788///
789/// Field order in [`GameSummary::to_lines`] follows `shogi-server`. A block that
790/// declared identical per-color `BEGIN Time+` / `BEGIN Time-` sections is
791/// re-emitted as a single shared `BEGIN Time` section, so block round-trips are
792/// semantic rather than byte-exact.
793#[non_exhaustive]
794#[derive(Debug, Clone, Default, PartialEq, Eq)]
795pub struct GameSummary {
796    /// `Protocol_Version`
797    pub protocol_version: Option<String>,
798    /// `Protocol_Mode`, `Server` for every server this crate targets.
799    pub protocol_mode: Option<String>,
800    /// `Format`
801    pub format: Option<String>,
802    /// `Declaration`, such as `Jishogi 1.1`.
803    pub declaration: Option<String>,
804    /// `Game_ID`
805    pub game_id: Option<String>,
806    /// `Name+`
807    pub name_black: Option<String>,
808    /// `Name-`
809    pub name_white: Option<String>,
810    /// `Your_Turn`, absent in `%%SHOW` output.
811    pub your_turn: Option<Color>,
812    /// `To_Move`
813    pub to_move: Option<Color>,
814    /// `Rematch_On_Draw`
815    pub rematch_on_draw: Option<String>,
816    /// `Max_Moves`
817    pub max_moves: Option<u32>,
818    /// Time control for black.
819    pub time_black: TimeConfig,
820    /// Time control for white.
821    pub time_white: TimeConfig,
822    /// `Last_Move`, present only in `%%SHOW` output.
823    pub last_move: Option<String>,
824    /// `Current_Turn`, present only in `%%SHOW` output.
825    pub current_turn: Option<u32>,
826    /// The `BEGIN Position` body, verbatim and without trailing newlines.
827    pub position_lines: Vec<String>,
828    /// Unrecognized top-level `Key:Value` pairs, kept in wire order.
829    pub extras: Vec<(String, String)>,
830}
831
832impl GameSummary {
833    /// The time control for one side.
834    #[must_use]
835    pub const fn time(&self, color: Color) -> &TimeConfig {
836        match color {
837            Color::Black => &self.time_black,
838            Color::White => &self.time_white,
839        }
840    }
841
842    /// Splits the position body into the initial position and any replayed moves.
843    ///
844    /// A resumed or buoy game carries moves inside `BEGIN Position`. The split
845    /// point is the first line that looks like a move, which is purely syntactic:
846    /// a sign followed by four digits. Board rows start with `P` and the side-to-move
847    /// line is a bare `+` or `-`, so neither can be mistaken for a move.
848    #[must_use]
849    pub fn position_split(&self) -> (&[String], &[String]) {
850        let index = self
851            .position_lines
852            .iter()
853            .position(|line| Self::looks_like_move_line(line))
854            .unwrap_or(self.position_lines.len());
855        self.position_lines.split_at(index)
856    }
857
858    fn looks_like_move_line(line: &str) -> bool {
859        let bytes = line.as_bytes();
860        bytes.len() >= 7
861            && (bytes[0] == b'+' || bytes[0] == b'-')
862            && bytes[1..5].iter().all(u8::is_ascii_digit)
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    #[test]
871    fn move_parse_rejects_bad_shapes() {
872        assert!(CsaMove::parse("+7776FU").is_some());
873        assert!(CsaMove::parse("-3334FU").is_some());
874        assert!(CsaMove::parse("+0055KA").is_some());
875        assert!(CsaMove::parse("+0000FU").is_none());
876        assert!(CsaMove::parse("+1099FU").is_none());
877        assert!(CsaMove::parse("+9910FU").is_none());
878        assert!(CsaMove::parse("7776FU").is_none());
879        assert!(CsaMove::parse("+7776F").is_none());
880        assert!(CsaMove::parse("+7776FUU").is_none());
881        assert!(CsaMove::parse("+77a6FU").is_none());
882        assert!(CsaMove::parse("+7776fu").is_none());
883        assert!(CsaMove::parse("+7776XX").is_none());
884    }
885
886    #[test]
887    fn move_accessors_read_the_wire_text() {
888        let mv = CsaMove::parse("-0084FU").expect("valid drop");
889        assert_eq!(mv.color(), Color::White);
890        assert!(mv.is_drop());
891        assert_eq!(mv.piece_name(), "FU");
892        assert_eq!(mv.as_str(), "-0084FU");
893
894        let mv = CsaMove::parse("+7776FU").expect("valid move");
895        assert_eq!(mv.color(), Color::Black);
896        assert!(!mv.is_drop());
897    }
898
899    #[test]
900    fn end_marker_classification() {
901        assert_eq!(EndMarker::Win.kind(), EndMarkerKind::Outcome);
902        assert_eq!(EndMarker::Censored.kind(), EndMarkerKind::Outcome);
903        assert_eq!(EndMarker::Resign.kind(), EndMarkerKind::Reason);
904        assert_eq!(EndMarker::Chudan.kind(), EndMarkerKind::Reason);
905        assert_eq!(EndMarker::from_token("NOPE").kind(), EndMarkerKind::Unknown);
906    }
907
908    #[test]
909    fn time_unit_converts_to_millis() {
910        assert_eq!(TimeUnit::SECOND.as_millis(), 1_000);
911        assert_eq!(TimeUnit { count: 1, scale: TimeScale::Min }.as_millis(), 60_000);
912        assert_eq!(TimeUnit { count: 250, scale: TimeScale::Msec }.as_millis(), 250);
913        assert_eq!(TimeUnit { count: u64::MAX, scale: TimeScale::Min }.as_millis(), u64::MAX);
914    }
915
916    #[test]
917    fn position_split_finds_replayed_moves() {
918        let summary = GameSummary {
919            position_lines: vec![
920                "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY".to_owned(),
921                "P+".to_owned(),
922                "+".to_owned(),
923                "+7776FU,T2".to_owned(),
924                "-3334FU,T5".to_owned(),
925            ],
926            ..GameSummary::default()
927        };
928        let (board, moves) = summary.position_split();
929        assert_eq!(board.len(), 3);
930        assert_eq!(moves.len(), 2);
931        assert_eq!(moves[0], "+7776FU,T2");
932    }
933
934    #[test]
935    fn position_split_without_moves_returns_everything_as_board() {
936        let summary = GameSummary {
937            position_lines: vec!["PI".to_owned(), "+".to_owned()],
938            ..GameSummary::default()
939        };
940        let (board, moves) = summary.position_split();
941        assert_eq!(board.len(), 2);
942        assert!(moves.is_empty());
943    }
944
945    #[test]
946    fn direction_is_derived_not_stored() {
947        assert_eq!(CsaCommand::Logout.direction(), Some(CsaCommandDirection::ClientToServer));
948        assert_eq!(
949            CsaCommand::LoginIncorrect.direction(),
950            Some(CsaCommandDirection::ServerToClient)
951        );
952        assert_eq!(CsaCommand::KeepAlive.direction(), Some(CsaCommandDirection::Both));
953        assert_eq!(
954            CsaCommand::Meta(MetaCommand::Other { name: "X".to_owned(), args: Vec::new() })
955                .direction(),
956            None
957        );
958        assert!(CsaCommand::KeepAlive.is_client_to_server());
959        assert!(CsaCommand::KeepAlive.is_server_to_client());
960    }
961}