Spawn a separate thread to receive UCI messages via mpsc channel, simplify output to println

This commit is contained in:
stefiosif
2025-03-01 23:54:51 +02:00
parent 7accc28aba
commit 91345848c6
3 changed files with 38 additions and 94 deletions

View File

@@ -1,7 +1,9 @@
use std::{
collections::HashMap,
io::{BufRead, Write},
io::{self, BufRead},
str::SplitWhitespace,
sync::mpsc,
thread,
};
use anyhow::{anyhow, bail};
@@ -51,12 +53,6 @@ pub enum Response {
Info(String),
}
pub fn write_response(handle_out: &mut impl Write, response: &Response) -> anyhow::Result<()> {
writeln!(handle_out, "{response}").map_err(|e| anyhow!(e))?;
handle_out.flush().map_err(|e| anyhow!(e))?;
Ok(())
}
use std::fmt;
impl fmt::Display for Response {
@@ -220,16 +216,24 @@ fn parse_next<T: std::str::FromStr>(iter: &mut SplitWhitespace, val: &str) -> an
.and_then(|v| v.parse::<T>().map_err(|_| anyhow!("Invalid {val}")))
}
pub fn uci_loop<R: BufRead, W: Write>(input: R, mut output: W) -> anyhow::Result<()> {
pub fn uci_loop() -> anyhow::Result<()> {
let mut params = UciParameters::new();
let (uci_sender, uci_receiver) = mpsc::channel();
for line in input.lines() {
thread::spawn(move || {
let input = io::stdin().lock();
for line in input.lines() {
uci_sender.send(line).expect("Failed to send line");
}
});
while let Ok(line) = uci_receiver.recv() {
let line_str = line.unwrap_or_else(|_| "quit".to_string());
let mut parts = line_str.split_whitespace();
let command = parse_command(&mut parts)?;
match command {
Command::Uci => write_response(&mut output, &Response::UciOk)?,
Command::IsReady => write_response(&mut output, &Response::ReadyOk)?,
Command::Uci => println!("{}", Response::UciOk),
Command::IsReady => println!("{}", Response::ReadyOk),
Command::UciNewGame => {
if let Some(game) = params.game.as_mut() {
game.tt = TranspositionTable::new();
@@ -243,17 +247,16 @@ pub fn uci_loop<R: BufRead, W: Write>(input: R, mut output: W) -> anyhow::Result
Command::Go => {
if let Some(game) = params.game.as_mut() {
match uci_go(&mut parts, game) {
Ok(best_move) => write_response(
&mut output,
&Response::BestMove(best_move.parse_into_str()),
),
Err(e) => write_response(&mut output, &Response::Info(e.to_string())),
}?;
Ok(best_move) => {
println!("{}", Response::BestMove(best_move.parse_into_str()))
}
Err(e) => println!("{}", Response::Info(e.to_string())),
}
} else {
write_response(
&mut output,
&Response::Info("Failed to unwrap from UciParameter".to_string()),
)?;
println!(
"{}",
Response::Info("Failed to unwrap from UciParameter".to_string())
)
};
}
Command::Stop => break,
@@ -267,8 +270,6 @@ pub fn uci_loop<R: BufRead, W: Write>(input: R, mut output: W) -> anyhow::Result
};
}
};
output.flush().map_err(|e| anyhow!(e))?
}
Ok(())
@@ -276,8 +277,6 @@ pub fn uci_loop<R: BufRead, W: Write>(input: R, mut output: W) -> anyhow::Result
#[cfg(test)]
mod tests {
use std::io::Cursor;
use crate::{
board::{fen::from_fen, square::Square},
interface::uci::{parse_command, Command},
@@ -285,7 +284,6 @@ mod tests {
};
use super::uci_go;
use super::uci_loop;
use super::uci_position;
const FEN: [&str; 2] = [
@@ -326,28 +324,4 @@ mod tests {
Ok(())
}
#[test]
fn test_uci_loop() -> anyhow::Result<()> {
init_attacks();
let commands = "uci\n\
ucinewgame\n\
position fen 8/8/8/8/8/4q1k1/8/5K2 b - - 0 1\n\
go\n\
quit";
let input = Cursor::new(commands);
let mut output: Vec<_> = vec![];
uci_loop(input, &mut output)?;
let expected_response = "id name zeal\n\
id author stefiosif\n\
uciok\n\
bestmove e3f2\n";
let actual_response = String::from_utf8(output).expect("Invalid UTF-8 in output");
assert_eq!(expected_response, actual_response);
Ok(())
}
}