1use std::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Color {
12 Black,
14 White,
16}
17
18impl Color {
19 #[must_use]
21 pub const fn as_csa(self) -> char {
22 match self {
23 Self::Black => '+',
24 Self::White => '-',
25 }
26 }
27
28 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum TurnPreference {
60 Black,
62 White,
64 Either,
66}
67
68impl TurnPreference {
69 #[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 #[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
97const PIECE_NAMES: [&str; 14] =
99 ["FU", "KY", "KE", "GI", "KI", "KA", "HI", "OU", "TO", "NY", "NK", "NG", "UM", "RY"];
100
101#[derive(Debug, Clone, PartialEq, Eq, Hash)]
107pub struct CsaMove(String);
108
109impl CsaMove {
110 #[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 #[must_use]
143 pub fn as_str(&self) -> &str {
144 &self.0
145 }
146
147 #[must_use]
149 pub fn color(&self) -> Color {
150 if self.0.starts_with('+') {
152 Color::Black
153 } else {
154 Color::White
155 }
156 }
157
158 #[must_use]
160 pub fn is_drop(&self) -> bool {
161 &self.0[1..3] == "00"
162 }
163
164 #[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#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct MoveLine {
188 pub csa: CsaMove,
190 pub elapsed: Option<u64>,
196 pub comment: Option<String>,
198}
199
200impl MoveLine {
201 #[must_use]
203 pub const fn new(csa: CsaMove) -> Self {
204 Self { csa, elapsed: None, comment: None }
205 }
206}
207
208#[non_exhaustive]
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub enum SpecialMove {
212 Toryo,
214 Kachi,
216 Chudan,
219 Sennichite,
221 Hikiwake,
223 Jishogi,
225 MaxMoves,
227 Tsumi,
229 Fuzumi,
231 TimeUp,
233 IllegalMove,
235 IllegalActionBlack,
237 IllegalActionWhite,
239 Error,
241 Other(String),
243}
244
245impl SpecialMove {
246 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
293pub enum EndMarkerKind {
294 Outcome,
296 Reason,
298 Unknown,
300}
301
302#[non_exhaustive]
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum EndMarker {
309 Win,
311 Lose,
313 Draw,
315 Censored,
317 Chudan,
319 Resign,
321 TimeUp,
323 IllegalMove,
325 IllegalAction,
327 Jishogi,
329 Sennichite,
331 OuteSennichite,
333 MaxMoves,
335 Other(String),
337}
338
339impl EndMarker {
340 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct InfoLine {
404 pub tag: String,
406 pub rest: String,
411}
412
413impl InfoLine {
414 #[must_use]
416 pub fn body(&self) -> &str {
417 self.rest.trim_start()
418 }
419}
420
421#[non_exhaustive]
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub enum MetaCommand {
428 Game {
432 name: Option<String>,
434 turn: Option<TurnPreference>,
436 },
437 Challenge {
439 name: String,
441 turn: TurnPreference,
443 },
444 Who,
446 List,
448 Show(String),
450 Chat(String),
452 Rating,
454 Version,
456 Help,
458 Other {
460 name: String,
462 args: Vec<String>,
464 },
465}
466
467#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
469pub enum CsaCommandDirection {
470 ClientToServer,
472 ServerToClient,
474 Both,
476}
477
478#[non_exhaustive]
480#[derive(Debug, Clone, PartialEq, Eq)]
481pub enum CsaCommand {
482 Login {
484 name: String,
486 password: String,
488 x1: bool,
490 },
491 Logout,
493 Agree {
495 game_id: Option<String>,
497 },
498 Reject {
500 game_id: Option<String>,
502 },
503 Challenge,
505 Meta(MetaCommand),
507
508 LoginOk {
510 name: String,
512 },
513 LoginIncorrect,
515 LogoutCompleted,
517 ChallengeAccepted,
519 BeginGameSummary,
523 Start {
525 game_id: String,
527 },
528 RejectNotice {
530 game_id: String,
532 by: String,
534 },
535 End(EndMarker),
537 Info(InfoLine),
539
540 Move(MoveLine),
542 Special {
544 kind: SpecialMove,
546 elapsed: Option<u64>,
548 },
549 KeepAlive,
554}
555
556impl CsaCommand {
557 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
606pub enum TimeScale {
607 Msec,
609 Sec,
611 Min,
613}
614
615impl TimeScale {
616 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
639pub struct TimeUnit {
640 pub count: u64,
642 pub scale: TimeScale,
644}
645
646impl TimeUnit {
647 pub const SECOND: Self = Self { count: 1, scale: TimeScale::Sec };
649
650 #[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#[non_exhaustive]
675#[derive(Debug, Clone, Default, PartialEq, Eq)]
676pub struct TimeConfig {
677 pub time_unit: Option<TimeUnit>,
679 pub total_time: Option<u64>,
681 pub byoyomi: Option<u64>,
683 pub delay: Option<u64>,
685 pub increment: Option<u64>,
687 pub least_time_per_move: Option<u64>,
689 pub time_roundup: Option<bool>,
691 pub remaining_time: Option<u64>,
693 pub extras: Vec<(String, String)>,
695}
696
697impl TimeConfig {
698 #[must_use]
711 pub fn new(unit: TimeUnit) -> Self {
712 Self { time_unit: Some(unit), ..Self::default() }
713 }
714
715 #[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 #[must_use]
724 pub const fn with_byoyomi(mut self, units: u64) -> Self {
725 self.byoyomi = Some(units);
726 self
727 }
728
729 #[must_use]
731 pub const fn with_increment(mut self, units: u64) -> Self {
732 self.increment = Some(units);
733 self
734 }
735
736 #[must_use]
738 pub const fn with_delay(mut self, units: u64) -> Self {
739 self.delay = Some(units);
740 self
741 }
742
743 #[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 #[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 #[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 #[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 #[must_use]
782 pub fn unit(&self) -> TimeUnit {
783 self.time_unit.unwrap_or_default()
784 }
785}
786
787#[non_exhaustive]
794#[derive(Debug, Clone, Default, PartialEq, Eq)]
795pub struct GameSummary {
796 pub protocol_version: Option<String>,
798 pub protocol_mode: Option<String>,
800 pub format: Option<String>,
802 pub declaration: Option<String>,
804 pub game_id: Option<String>,
806 pub name_black: Option<String>,
808 pub name_white: Option<String>,
810 pub your_turn: Option<Color>,
812 pub to_move: Option<Color>,
814 pub rematch_on_draw: Option<String>,
816 pub max_moves: Option<u32>,
818 pub time_black: TimeConfig,
820 pub time_white: TimeConfig,
822 pub last_move: Option<String>,
824 pub current_turn: Option<u32>,
826 pub position_lines: Vec<String>,
828 pub extras: Vec<(String, String)>,
830}
831
832impl GameSummary {
833 #[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 #[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}