Run rustfmt

This commit is contained in:
Dane Johnson 2022-10-12 12:48:23 -05:00
parent bf84433d5b
commit 4c0f571317
5 changed files with 303 additions and 318 deletions

View File

@ -1,22 +1,14 @@
use std::sync::Arc; use std::sync::Arc;
use futures::{select, FutureExt};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use futures::{
select,
FutureExt,
};
use hexland_server::{ use hexland_server::{
GlobalState,
Channel,
channel_pair, channel_pair,
GameController,
message::{Message, MessageWebSocket}, message::{Message, MessageWebSocket},
msg, msg, Channel, GameController, GlobalState,
}; };
pub struct Client { pub struct Client {
global_state: Arc<GlobalState>, global_state: Arc<GlobalState>,
ws: MessageWebSocket, ws: MessageWebSocket,
@ -28,7 +20,7 @@ impl Client {
Client { Client {
global_state, global_state,
ws, ws,
channel: None channel: None,
} }
} }
pub async fn run(&mut self) { pub async fn run(&mut self) {
@ -60,8 +52,12 @@ impl Client {
game_controller.channels.push(server_channel); game_controller.channels.push(server_channel);
let game_controller = Arc::new(Mutex::new(game_controller)); let game_controller = Arc::new(Mutex::new(game_controller));
self.global_state.rooms.lock().await.insert(room_code.clone(), Arc::clone(&game_controller)); self.global_state
tokio::spawn(async move {game_loop(game_controller)}); .rooms
.lock()
.await
.insert(room_code.clone(), Arc::clone(&game_controller));
tokio::spawn(async move { game_loop(game_controller) });
self.ws.send(msg!(ROOM_CODE, room_code)).await.unwrap(); self.ws.send(msg!(ROOM_CODE, room_code)).await.unwrap();
} }
"JOIN" => { "JOIN" => {
@ -82,9 +78,11 @@ impl Client {
} }
} }
} }
_ => if let Some(channel) = &self.channel { _ => {
// Forward message to the server if let Some(channel) = &self.channel {
channel.tx.send(msg).await.unwrap(); // Forward message to the server
channel.tx.send(msg).await.unwrap();
}
} }
} }
} }

View File

@ -1,5 +1,5 @@
use rand::RngCore; use rand::RngCore;
use sha2::{Sha256, Digest}; use sha2::{Digest, Sha256};
pub struct CodeGenerator { pub struct CodeGenerator {
counter: u64, counter: u64,
@ -24,10 +24,7 @@ impl Default for CodeGenerator {
let mut salt = [0; 32]; let mut salt = [0; 32];
rand::thread_rng().fill_bytes(&mut salt); rand::thread_rng().fill_bytes(&mut salt);
CodeGenerator { CodeGenerator { counter: 0, salt }
counter: 0,
salt,
}
} }
} }

View File

@ -1,12 +1,9 @@
use std::{ use std::{collections::HashMap, sync::Arc};
collections::HashMap,
sync::Arc,
};
use tokio::sync::{Mutex, mpsc}; use tokio::sync::{mpsc, Mutex};
pub mod message; pub mod message;
use message::{Message}; use message::Message;
mod code_generator; mod code_generator;
use code_generator::CodeGenerator; use code_generator::CodeGenerator;
@ -24,10 +21,7 @@ pub struct Channel {
pub fn channel_pair() -> (Channel, Channel) { pub fn channel_pair() -> (Channel, Channel) {
let (atx, brx) = mpsc::channel(32); let (atx, brx) = mpsc::channel(32);
let (btx, arx) = mpsc::channel(32); let (btx, arx) = mpsc::channel(32);
( (Channel { tx: atx, rx: arx }, Channel { tx: btx, rx: brx })
Channel { tx: atx, rx: arx },
Channel { tx: btx, rx: brx },
)
} }
#[derive(Default)] #[derive(Default)]

View File

@ -1,14 +1,9 @@
use std::{ use std::{io::Error as IoError, sync::Arc};
sync::Arc,
io::Error as IoError,
};
use tokio::{ use tokio::net::TcpListener;
net::{TcpListener},
};
use hexland_server::GlobalState;
use hexland_server::message::MessageWebSocket; use hexland_server::message::MessageWebSocket;
use hexland_server::GlobalState;
mod client; mod client;
use client::Client; use client::Client;
@ -27,9 +22,11 @@ async fn main() -> Result<(), IoError> {
let global_state = Arc::clone(&global_state); let global_state = Arc::clone(&global_state);
tokio::spawn(async move { tokio::spawn(async move {
// Upgrade to a WS connection // Upgrade to a WS connection
let ws = MessageWebSocket(tokio_tungstenite::accept_async(stream) let ws = MessageWebSocket(
.await tokio_tungstenite::accept_async(stream)
.expect("Could not establish connection")); .await
.expect("Could not establish connection"),
);
println!("Connected to {}", addr); println!("Connected to {}", addr);
Client::new(ws, global_state).run().await; Client::new(ws, global_state).run().await;
}); });

View File

@ -1,12 +1,9 @@
use std::convert::{From, TryFrom}; use std::convert::{From, TryFrom};
use tokio::net::TcpStream; use futures::{SinkExt, StreamExt};
use tokio_tungstenite::{
WebSocketStream,
tungstenite::Message as WsMessage,
};
use futures::{StreamExt, SinkExt};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use tokio::net::TcpStream;
use tokio_tungstenite::{tungstenite::Message as WsMessage, WebSocketStream};
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub struct Message { pub struct Message {
@ -29,20 +26,23 @@ impl Message {
lazy_static! { lazy_static! {
static ref RE: regex::Regex = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap(); static ref RE: regex::Regex = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap();
} }
match RE.captures(text.as_str()) { match RE.captures(text.as_str()) {
Some(captures) => { Some(captures) => {
if captures.len() < 3 { if captures.len() < 3 {
Err(Error::BadParse) Err(Error::BadParse)
} else { } else {
let command = captures.get(1).unwrap().as_str().to_string(); let command = captures.get(1).unwrap().as_str().to_string();
let args = captures.get(2).unwrap().as_str() let args = captures
.split(',') .get(2)
.map(|s| s.trim().to_string()) .unwrap()
.collect(); .as_str()
.split(',')
.map(|s| s.trim().to_string())
.collect();
Ok(Message { command, args }) Ok(Message { command, args })
} }
} }
None => Err(Error::BadParse), None => Err(Error::BadParse),
} }
} }
} }
@ -53,7 +53,7 @@ impl TryFrom<WsMessage> for Message {
fn try_from(ws_message: WsMessage) -> Result<Self> { fn try_from(ws_message: WsMessage) -> Result<Self> {
let text = match ws_message { let text = match ws_message {
WsMessage::Text(text) => text, WsMessage::Text(text) => text,
_ => return Err(Error::NonText) _ => return Err(Error::NonText),
}; };
Message::parse(text) Message::parse(text)
} }
@ -102,13 +102,12 @@ macro_rules! msg {
}; };
} }
impl std::fmt::Display for Message { impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
if self.args.is_empty() { if self.args.is_empty() {
write!(f, "{}:", self.command) write!(f, "{}:", self.command)
} else { } else {
write!(f, "{}: {}", self.command, self.args.as_slice().join(", ")) write!(f, "{}: {}", self.command, self.args.as_slice().join(", "))
} }
} }
} }
@ -118,14 +117,14 @@ mod test {
use super::*; use super::*;
#[test] #[test]
fn test_parse() -> Result<()> { fn test_parse() -> Result<()> {
let text = "COMMAND: arg1, arg2"; let text = "COMMAND: arg1, arg2";
let msg = Message::parse(text.to_string())?; let msg = Message::parse(text.to_string())?;
assert_eq!(msg!(COMMAND, "arg1", "arg2"), msg); assert_eq!(msg!(COMMAND, "arg1", "arg2"), msg);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_to_string() { fn test_to_string() {
let msg = msg!(COMMAND, "arg1", "arg2"); let msg = msg!(COMMAND, "arg1", "arg2");
assert_eq!(msg.to_string(), "COMMAND: arg1, arg2".to_string()); assert_eq!(msg.to_string(), "COMMAND: arg1, arg2".to_string());
} }
} }