use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Color {
Black,
White,
}
impl Color {
#[must_use]
pub const fn as_csa(self) -> char {
match self {
Self::Black => '+',
Self::White => '-',
}
}
#[must_use]
pub const fn from_csa(value: char) -> Option<Self> {
match value {
'+' => Some(Self::Black),
'-' => Some(Self::White),
_ => None,
}
}
#[must_use]
pub const fn flip(self) -> Self {
match self {
Self::Black => Self::White,
Self::White => Self::Black,
}
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Black => "+",
Self::White => "-",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TurnPreference {
Black,
White,
Either,
}
impl TurnPreference {
#[must_use]
pub const fn as_csa(self) -> char {
match self {
Self::Black => '+',
Self::White => '-',
Self::Either => '*',
}
}
#[must_use]
pub const fn from_csa(value: char) -> Option<Self> {
match value {
'+' => Some(Self::Black),
'-' => Some(Self::White),
'*' => Some(Self::Either),
_ => None,
}
}
}
impl fmt::Display for TurnPreference {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_csa())
}
}
const PIECE_NAMES: [&str; 14] =
["FU", "KY", "KE", "GI", "KI", "KA", "HI", "OU", "TO", "NY", "NK", "NG", "UM", "RY"];
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CsaMove(String);
impl CsaMove {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
let bytes = value.as_bytes();
if bytes.len() != 7 {
return None;
}
if bytes[0] != b'+' && bytes[0] != b'-' {
return None;
}
if !(bytes[1..3] == *b"00" || is_board_square(&bytes[1..3]))
|| !is_board_square(&bytes[3..5])
{
return None;
}
let piece = &value[5..7];
if !PIECE_NAMES.contains(&piece) {
return None;
}
Some(Self(value.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn color(&self) -> Color {
if self.0.starts_with('+') {
Color::Black
} else {
Color::White
}
}
#[must_use]
pub fn is_drop(&self) -> bool {
&self.0[1..3] == "00"
}
#[must_use]
pub fn piece_name(&self) -> &str {
&self.0[5..7]
}
}
fn is_board_square(bytes: &[u8]) -> bool {
matches!(bytes, [b'1'..=b'9', b'1'..=b'9'])
}
impl fmt::Display for CsaMove {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoveLine {
pub csa: CsaMove,
pub elapsed: Option<u64>,
pub comment: Option<String>,
}
impl MoveLine {
#[must_use]
pub const fn new(csa: CsaMove) -> Self {
Self { csa, elapsed: None, comment: None }
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpecialMove {
Toryo,
Kachi,
Chudan,
Sennichite,
Hikiwake,
Jishogi,
MaxMoves,
Tsumi,
Fuzumi,
TimeUp,
IllegalMove,
IllegalActionBlack,
IllegalActionWhite,
Error,
Other(String),
}
impl SpecialMove {
#[must_use]
pub fn as_token(&self) -> &str {
match self {
Self::Toryo => "TORYO",
Self::Kachi => "KACHI",
Self::Chudan => "CHUDAN",
Self::Sennichite => "SENNICHITE",
Self::Hikiwake => "HIKIWAKE",
Self::Jishogi => "JISHOGI",
Self::MaxMoves => "MAX_MOVES",
Self::Tsumi => "TSUMI",
Self::Fuzumi => "FUZUMI",
Self::TimeUp => "TIME_UP",
Self::IllegalMove => "ILLEGAL_MOVE",
Self::IllegalActionBlack => "+ILLEGAL_ACTION",
Self::IllegalActionWhite => "-ILLEGAL_ACTION",
Self::Error => "ERROR",
Self::Other(token) => token,
}
}
#[must_use]
pub fn from_token(token: &str) -> Self {
match token {
"TORYO" => Self::Toryo,
"KACHI" => Self::Kachi,
"CHUDAN" => Self::Chudan,
"SENNICHITE" => Self::Sennichite,
"HIKIWAKE" => Self::Hikiwake,
"JISHOGI" => Self::Jishogi,
"MAX_MOVES" => Self::MaxMoves,
"TSUMI" => Self::Tsumi,
"FUZUMI" => Self::Fuzumi,
"TIME_UP" => Self::TimeUp,
"ILLEGAL_MOVE" => Self::IllegalMove,
"+ILLEGAL_ACTION" => Self::IllegalActionBlack,
"-ILLEGAL_ACTION" => Self::IllegalActionWhite,
"ERROR" => Self::Error,
other => Self::Other(other.to_owned()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EndMarkerKind {
Outcome,
Reason,
Unknown,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EndMarker {
Win,
Lose,
Draw,
Censored,
Chudan,
Resign,
TimeUp,
IllegalMove,
IllegalAction,
Jishogi,
Sennichite,
OuteSennichite,
MaxMoves,
Other(String),
}
impl EndMarker {
#[must_use]
pub fn as_token(&self) -> &str {
match self {
Self::Win => "WIN",
Self::Lose => "LOSE",
Self::Draw => "DRAW",
Self::Censored => "CENSORED",
Self::Chudan => "CHUDAN",
Self::Resign => "RESIGN",
Self::TimeUp => "TIME_UP",
Self::IllegalMove => "ILLEGAL_MOVE",
Self::IllegalAction => "ILLEGAL_ACTION",
Self::Jishogi => "JISHOGI",
Self::Sennichite => "SENNICHITE",
Self::OuteSennichite => "OUTE_SENNICHITE",
Self::MaxMoves => "MAX_MOVES",
Self::Other(token) => token,
}
}
#[must_use]
pub fn from_token(token: &str) -> Self {
match token {
"WIN" => Self::Win,
"LOSE" => Self::Lose,
"DRAW" => Self::Draw,
"CENSORED" => Self::Censored,
"CHUDAN" => Self::Chudan,
"RESIGN" => Self::Resign,
"TIME_UP" => Self::TimeUp,
"ILLEGAL_MOVE" => Self::IllegalMove,
"ILLEGAL_ACTION" => Self::IllegalAction,
"JISHOGI" => Self::Jishogi,
"SENNICHITE" => Self::Sennichite,
"OUTE_SENNICHITE" => Self::OuteSennichite,
"MAX_MOVES" => Self::MaxMoves,
other => Self::Other(other.to_owned()),
}
}
#[must_use]
pub const fn kind(&self) -> EndMarkerKind {
match self {
Self::Win | Self::Lose | Self::Draw | Self::Censored => EndMarkerKind::Outcome,
Self::Chudan
| Self::Resign
| Self::TimeUp
| Self::IllegalMove
| Self::IllegalAction
| Self::Jishogi
| Self::Sennichite
| Self::OuteSennichite
| Self::MaxMoves => EndMarkerKind::Reason,
Self::Other(_) => EndMarkerKind::Unknown,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InfoLine {
pub tag: String,
pub rest: String,
}
impl InfoLine {
#[must_use]
pub fn body(&self) -> &str {
self.rest.trim_start()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetaCommand {
Game {
name: Option<String>,
turn: Option<TurnPreference>,
},
Challenge {
name: String,
turn: TurnPreference,
},
Who,
List,
Show(String),
Chat(String),
Rating,
Version,
Help,
Other {
name: String,
args: Vec<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CsaCommandDirection {
ClientToServer,
ServerToClient,
Both,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CsaCommand {
Login {
name: String,
password: String,
x1: bool,
},
Logout,
Agree {
game_id: Option<String>,
},
Reject {
game_id: Option<String>,
},
Challenge,
Meta(MetaCommand),
LoginOk {
name: String,
},
LoginIncorrect,
LogoutCompleted,
ChallengeAccepted,
BeginGameSummary,
Start {
game_id: String,
},
RejectNotice {
game_id: String,
by: String,
},
End(EndMarker),
Info(InfoLine),
Move(MoveLine),
Special {
kind: SpecialMove,
elapsed: Option<u64>,
},
KeepAlive,
}
impl CsaCommand {
#[must_use]
pub const fn direction(&self) -> Option<CsaCommandDirection> {
match self {
Self::Login { .. }
| Self::Logout
| Self::Agree { .. }
| Self::Reject { .. }
| Self::Challenge => Some(CsaCommandDirection::ClientToServer),
Self::Meta(meta) => match meta {
MetaCommand::Other { .. } => None,
_ => Some(CsaCommandDirection::ClientToServer),
},
Self::LoginOk { .. }
| Self::LoginIncorrect
| Self::LogoutCompleted
| Self::ChallengeAccepted
| Self::BeginGameSummary
| Self::Start { .. }
| Self::RejectNotice { .. }
| Self::End(_)
| Self::Info(_) => Some(CsaCommandDirection::ServerToClient),
Self::Move(_) | Self::Special { .. } | Self::KeepAlive => {
Some(CsaCommandDirection::Both)
}
}
}
#[must_use]
pub const fn is_client_to_server(&self) -> bool {
matches!(
self.direction(),
Some(CsaCommandDirection::ClientToServer | CsaCommandDirection::Both)
)
}
#[must_use]
pub const fn is_server_to_client(&self) -> bool {
matches!(
self.direction(),
Some(CsaCommandDirection::ServerToClient | CsaCommandDirection::Both)
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimeScale {
Msec,
Sec,
Min,
}
impl TimeScale {
#[must_use]
pub const fn millis(self) -> u64 {
match self {
Self::Msec => 1,
Self::Sec => 1_000,
Self::Min => 60_000,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Msec => "msec",
Self::Sec => "sec",
Self::Min => "min",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeUnit {
pub count: u64,
pub scale: TimeScale,
}
impl TimeUnit {
pub const SECOND: Self = Self { count: 1, scale: TimeScale::Sec };
#[must_use]
pub const fn as_millis(self) -> u64 {
self.count.saturating_mul(self.scale.millis())
}
}
impl Default for TimeUnit {
fn default() -> Self {
Self::SECOND
}
}
impl fmt::Display for TimeUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.count, self.scale.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TimeConfig {
pub time_unit: Option<TimeUnit>,
pub total_time: Option<u64>,
pub byoyomi: Option<u64>,
pub delay: Option<u64>,
pub increment: Option<u64>,
pub least_time_per_move: Option<u64>,
pub time_roundup: Option<bool>,
pub remaining_time: Option<u64>,
pub extras: Vec<(String, String)>,
}
impl TimeConfig {
#[must_use]
pub fn new(unit: TimeUnit) -> Self {
Self { time_unit: Some(unit), ..Self::default() }
}
#[must_use]
pub const fn with_total_time(mut self, units: u64) -> Self {
self.total_time = Some(units);
self
}
#[must_use]
pub const fn with_byoyomi(mut self, units: u64) -> Self {
self.byoyomi = Some(units);
self
}
#[must_use]
pub const fn with_increment(mut self, units: u64) -> Self {
self.increment = Some(units);
self
}
#[must_use]
pub const fn with_delay(mut self, units: u64) -> Self {
self.delay = Some(units);
self
}
#[must_use]
pub const fn with_least_time_per_move(mut self, units: u64) -> Self {
self.least_time_per_move = Some(units);
self
}
#[must_use]
pub const fn with_time_roundup(mut self, roundup: bool) -> Self {
self.time_roundup = Some(roundup);
self
}
#[must_use]
pub const fn with_remaining_time(mut self, units: u64) -> Self {
self.remaining_time = Some(units);
self
}
#[must_use]
pub fn eq_ignoring_remaining(&self, other: &Self) -> bool {
self.time_unit == other.time_unit
&& self.total_time == other.total_time
&& self.byoyomi == other.byoyomi
&& self.delay == other.delay
&& self.increment == other.increment
&& self.least_time_per_move == other.least_time_per_move
&& self.time_roundup == other.time_roundup
&& self.extras == other.extras
}
#[must_use]
pub fn unit(&self) -> TimeUnit {
self.time_unit.unwrap_or_default()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GameSummary {
pub protocol_version: Option<String>,
pub protocol_mode: Option<String>,
pub format: Option<String>,
pub declaration: Option<String>,
pub game_id: Option<String>,
pub name_black: Option<String>,
pub name_white: Option<String>,
pub your_turn: Option<Color>,
pub to_move: Option<Color>,
pub rematch_on_draw: Option<String>,
pub max_moves: Option<u32>,
pub time_black: TimeConfig,
pub time_white: TimeConfig,
pub last_move: Option<String>,
pub current_turn: Option<u32>,
pub position_lines: Vec<String>,
pub extras: Vec<(String, String)>,
}
impl GameSummary {
#[must_use]
pub const fn time(&self, color: Color) -> &TimeConfig {
match color {
Color::Black => &self.time_black,
Color::White => &self.time_white,
}
}
#[must_use]
pub fn position_split(&self) -> (&[String], &[String]) {
let index = self
.position_lines
.iter()
.position(|line| Self::looks_like_move_line(line))
.unwrap_or(self.position_lines.len());
self.position_lines.split_at(index)
}
fn looks_like_move_line(line: &str) -> bool {
let bytes = line.as_bytes();
bytes.len() >= 7
&& (bytes[0] == b'+' || bytes[0] == b'-')
&& bytes[1..5].iter().all(u8::is_ascii_digit)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_parse_rejects_bad_shapes() {
assert!(CsaMove::parse("+7776FU").is_some());
assert!(CsaMove::parse("-3334FU").is_some());
assert!(CsaMove::parse("+0055KA").is_some());
assert!(CsaMove::parse("+0000FU").is_none());
assert!(CsaMove::parse("+1099FU").is_none());
assert!(CsaMove::parse("+9910FU").is_none());
assert!(CsaMove::parse("7776FU").is_none());
assert!(CsaMove::parse("+7776F").is_none());
assert!(CsaMove::parse("+7776FUU").is_none());
assert!(CsaMove::parse("+77a6FU").is_none());
assert!(CsaMove::parse("+7776fu").is_none());
assert!(CsaMove::parse("+7776XX").is_none());
}
#[test]
fn move_accessors_read_the_wire_text() {
let mv = CsaMove::parse("-0084FU").expect("valid drop");
assert_eq!(mv.color(), Color::White);
assert!(mv.is_drop());
assert_eq!(mv.piece_name(), "FU");
assert_eq!(mv.as_str(), "-0084FU");
let mv = CsaMove::parse("+7776FU").expect("valid move");
assert_eq!(mv.color(), Color::Black);
assert!(!mv.is_drop());
}
#[test]
fn end_marker_classification() {
assert_eq!(EndMarker::Win.kind(), EndMarkerKind::Outcome);
assert_eq!(EndMarker::Censored.kind(), EndMarkerKind::Outcome);
assert_eq!(EndMarker::Resign.kind(), EndMarkerKind::Reason);
assert_eq!(EndMarker::Chudan.kind(), EndMarkerKind::Reason);
assert_eq!(EndMarker::from_token("NOPE").kind(), EndMarkerKind::Unknown);
}
#[test]
fn time_unit_converts_to_millis() {
assert_eq!(TimeUnit::SECOND.as_millis(), 1_000);
assert_eq!(TimeUnit { count: 1, scale: TimeScale::Min }.as_millis(), 60_000);
assert_eq!(TimeUnit { count: 250, scale: TimeScale::Msec }.as_millis(), 250);
assert_eq!(TimeUnit { count: u64::MAX, scale: TimeScale::Min }.as_millis(), u64::MAX);
}
#[test]
fn position_split_finds_replayed_moves() {
let summary = GameSummary {
position_lines: vec![
"P1-KY-KE-GI-KI-OU-KI-GI-KE-KY".to_owned(),
"P+".to_owned(),
"+".to_owned(),
"+7776FU,T2".to_owned(),
"-3334FU,T5".to_owned(),
],
..GameSummary::default()
};
let (board, moves) = summary.position_split();
assert_eq!(board.len(), 3);
assert_eq!(moves.len(), 2);
assert_eq!(moves[0], "+7776FU,T2");
}
#[test]
fn position_split_without_moves_returns_everything_as_board() {
let summary = GameSummary {
position_lines: vec!["PI".to_owned(), "+".to_owned()],
..GameSummary::default()
};
let (board, moves) = summary.position_split();
assert_eq!(board.len(), 2);
assert!(moves.is_empty());
}
#[test]
fn direction_is_derived_not_stored() {
assert_eq!(CsaCommand::Logout.direction(), Some(CsaCommandDirection::ClientToServer));
assert_eq!(
CsaCommand::LoginIncorrect.direction(),
Some(CsaCommandDirection::ServerToClient)
);
assert_eq!(CsaCommand::KeepAlive.direction(), Some(CsaCommandDirection::Both));
assert_eq!(
CsaCommand::Meta(MetaCommand::Other { name: "X".to_owned(), args: Vec::new() })
.direction(),
None
);
assert!(CsaCommand::KeepAlive.is_client_to_server());
assert!(CsaCommand::KeepAlive.is_server_to_client());
}
}