diff options
Diffstat (limited to 'src/play.rs')
| -rw-r--r-- | src/play.rs | 30 |
1 files changed, 19 insertions, 11 deletions
diff --git a/src/play.rs b/src/play.rs index af5314a..574e8b8 100644 --- a/src/play.rs +++ b/src/play.rs @@ -1,9 +1,9 @@ use crate::AppState; +use crate::session::HandObject; use axum::extract::ws::{Message, Utf8Bytes, WebSocket}; use serde::{Deserialize, Serialize}; use std::error::Error; use std::sync::Arc; -use crate::session::HandObject; #[derive(Deserialize)] enum IncomingPlayMessage { @@ -25,17 +25,19 @@ pub async fn handle_play(mut socket: WebSocket, app_state: Arc<AppState>) { let mut play_state = PlayState { id: None }; while let Some(msg) = socket.recv().await { - let mut process = async |msg: Result<Message, axum::Error>, play_state: &mut PlayState| -> Result<(), Box<dyn Error>> { + let mut process = async |msg: Result<Message, axum::Error>, + play_state: &mut PlayState| + -> Result<(), Box<dyn Error>> { let msg: IncomingPlayMessage = serde_json::from_str(msg?.to_text()?)?; match msg { IncomingPlayMessage::Initialize { id } => { - // Blocked so that the mutex guard is dropped after cloning the color names, + // Blocked so that the guard is dropped after cloning the color names, // preventing a potential deadlock when using .await after sending something // through the socket, which would be possible if using tokio::sync::Mutex. - // Of course, the sessions Mutex is std::sync::Mutex instead, which does not - // allow locking the mutex through .await anyway. + // Of course, the sessions HashMap is wrapped instd::sync types instead, which + // does not enable locking the mutex through .await anyway. let colors: Vec<String> = { - let sessions = app_state.sessions.lock().unwrap(); + let sessions = app_state.sessions.read().unwrap(); // TODO: Non-string Error might be useful let session = sessions.get(&id).ok_or("Session did not exist")?; @@ -52,13 +54,19 @@ pub async fn handle_play(mut socket: WebSocket, app_state: Arc<AppState>) { &response, )?))) .await?; - }, + } IncomingPlayMessage::Color(color) => { let hand: Vec<HandObject> = { - let sessions = app_state.sessions.lock().unwrap(); - let session = sessions.get(play_state.id.as_ref().ok_or("No session was joined")?).ok_or("Session did not exist")?; + let sessions = app_state.sessions.read().unwrap(); + let session = sessions + .get(play_state.id.as_ref().ok_or("No session was joined")?) + .ok_or("Session did not exist")?; - (*session.hands.get(&color).ok_or("No player seated by that color")?).clone() + (*session + .hands + .get(&color) + .ok_or("No player seated by that color")?) + .clone() }; let response = OutgoingPlayMessage::Hand(hand.iter().collect()); @@ -67,7 +75,7 @@ pub async fn handle_play(mut socket: WebSocket, app_state: Arc<AppState>) { &response, )?))) .await?; - }, + } } Ok(()) }; |
