Skip to content

Commit c1535c0

Browse files
committed
feat: check AI move format before parsing
1 parent 8b0bd2a commit c1535c0

File tree

3 files changed

+25
-15
lines changed

3 files changed

+25
-15
lines changed

backend/Cargo.lock

+3-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ edition = "2021"
66
[dependencies]
77
async-process = "2.2.3"
88
envconfig = "0.10.0"
9+
regex = "1.10.6"
910
rocket = { version = "0.5.1", features = ["json"] }
1011
serde = { version = "1.0.204", features = ["derive"] }
1112
serde_json = "1.0.120"

backend/src/api/play.rs

+21-13
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
use super::{submissions::Submission, AppState, Error, User};
22
use crate::game::{GameState, GameStatus, Move, Player, TurnStatus};
3+
use regex::Regex;
34
use rocket::{
45
futures::{io::BufReader, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt},
56
get, post,
67
serde::json::Json,
78
tokio::sync::Mutex,
89
};
9-
use std::sync::Arc;
10+
use std::sync::{Arc, LazyLock};
11+
12+
static AI_OUTPUT_REGEX: LazyLock<Regex> =
13+
LazyLock::new(|| Regex::new("^([A-J]\\d,[A-J]\\d;)+$").unwrap());
1014

1115
#[derive(Debug)]
1216
pub struct Game {
@@ -39,18 +43,22 @@ impl Game {
3943
let mut ai_output = String::new();
4044
stderr.read_to_string(&mut ai_output).await?;
4145

42-
let seq = line
43-
.split(";")
44-
.map(|m| {
45-
let chars = m.chars().collect::<Vec<_>>();
46-
Move {
47-
from: convert_cell_id(&chars[0..=1]),
48-
to: convert_cell_id(&chars[2..=3]),
49-
}
50-
})
51-
.collect::<Vec<_>>();
52-
53-
if let Err(Error::InvalidMove) = self.checkers.apply_sequence(&seq) {
46+
if AI_OUTPUT_REGEX.is_match(&line) {
47+
let seq = line
48+
.split(";")
49+
.map(|m| {
50+
let chars = m.chars().collect::<Vec<_>>();
51+
Move {
52+
from: convert_cell_id(&chars[0..=1]),
53+
to: convert_cell_id(&chars[2..=3]),
54+
}
55+
})
56+
.collect::<Vec<_>>();
57+
58+
if let Err(Error::InvalidMove) = self.checkers.apply_sequence(&seq) {
59+
self.checkers.status = GameStatus::Victory(self.human_player)
60+
}
61+
} else {
5462
self.checkers.status = GameStatus::Victory(self.human_player)
5563
}
5664

0 commit comments

Comments
 (0)