Run rustfmt
This commit is contained in:
parent
bf84433d5b
commit
4c0f571317
194
src/client.rs
194
src/client.rs
@ -1,98 +1,96 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use tokio::sync::Mutex;
|
use futures::{select, FutureExt};
|
||||||
use futures::{
|
use tokio::sync::Mutex;
|
||||||
select,
|
|
||||||
FutureExt,
|
use hexland_server::{
|
||||||
};
|
channel_pair,
|
||||||
|
message::{Message, MessageWebSocket},
|
||||||
|
msg, Channel, GameController, GlobalState,
|
||||||
use hexland_server::{
|
};
|
||||||
GlobalState,
|
|
||||||
Channel,
|
pub struct Client {
|
||||||
channel_pair,
|
global_state: Arc<GlobalState>,
|
||||||
GameController,
|
ws: MessageWebSocket,
|
||||||
message::{Message, MessageWebSocket},
|
channel: Option<Channel>,
|
||||||
msg,
|
}
|
||||||
};
|
|
||||||
|
impl Client {
|
||||||
|
pub fn new(ws: MessageWebSocket, global_state: Arc<GlobalState>) -> Self {
|
||||||
pub struct Client {
|
Client {
|
||||||
global_state: Arc<GlobalState>,
|
global_state,
|
||||||
ws: MessageWebSocket,
|
ws,
|
||||||
channel: Option<Channel>,
|
channel: None,
|
||||||
}
|
}
|
||||||
|
}
|
||||||
impl Client {
|
pub async fn run(&mut self) {
|
||||||
pub fn new(ws: MessageWebSocket, global_state: Arc<GlobalState>) -> Self {
|
loop {
|
||||||
Client {
|
match &mut self.channel {
|
||||||
global_state,
|
Some(channel) => {
|
||||||
ws,
|
select! {
|
||||||
channel: None
|
msg = channel.rx.recv().fuse() =>
|
||||||
}
|
self.handle_server_msg(msg.unwrap()).await,
|
||||||
}
|
msg = self.ws.next().fuse() =>
|
||||||
pub async fn run(&mut self) {
|
self.handle_client_msg(msg.unwrap()).await,
|
||||||
loop {
|
};
|
||||||
match &mut self.channel {
|
}
|
||||||
Some(channel) => {
|
None => {
|
||||||
select! {
|
let msg = self.ws.next().await;
|
||||||
msg = channel.rx.recv().fuse() =>
|
self.handle_client_msg(msg.unwrap()).await;
|
||||||
self.handle_server_msg(msg.unwrap()).await,
|
}
|
||||||
msg = self.ws.next().fuse() =>
|
}
|
||||||
self.handle_client_msg(msg.unwrap()).await,
|
}
|
||||||
};
|
}
|
||||||
}
|
async fn handle_client_msg(&mut self, msg: Message) {
|
||||||
None => {
|
match msg.command.as_str() {
|
||||||
let msg = self.ws.next().await;
|
"HOST" => {
|
||||||
self.handle_client_msg(msg.unwrap()).await;
|
let room_code = self.global_state.code_generator.lock().await.generate();
|
||||||
}
|
let mut game_controller = GameController::default();
|
||||||
}
|
|
||||||
}
|
let (client_channel, server_channel) = channel_pair();
|
||||||
}
|
self.channel = Some(client_channel);
|
||||||
async fn handle_client_msg(&mut self, msg: Message) {
|
game_controller.channels.push(server_channel);
|
||||||
match msg.command.as_str() {
|
|
||||||
"HOST" => {
|
let game_controller = Arc::new(Mutex::new(game_controller));
|
||||||
let room_code = self.global_state.code_generator.lock().await.generate();
|
self.global_state
|
||||||
let mut game_controller = GameController::default();
|
.rooms
|
||||||
|
.lock()
|
||||||
let (client_channel, server_channel) = channel_pair();
|
.await
|
||||||
self.channel = Some(client_channel);
|
.insert(room_code.clone(), Arc::clone(&game_controller));
|
||||||
game_controller.channels.push(server_channel);
|
tokio::spawn(async move { game_loop(game_controller) });
|
||||||
|
self.ws.send(msg!(ROOM_CODE, room_code)).await.unwrap();
|
||||||
let game_controller = Arc::new(Mutex::new(game_controller));
|
}
|
||||||
self.global_state.rooms.lock().await.insert(room_code.clone(), Arc::clone(&game_controller));
|
"JOIN" => {
|
||||||
tokio::spawn(async move {game_loop(game_controller)});
|
let room_code = &msg.args[0];
|
||||||
self.ws.send(msg!(ROOM_CODE, room_code)).await.unwrap();
|
let rooms = self.global_state.rooms.lock().await;
|
||||||
}
|
let room = rooms.get(room_code);
|
||||||
"JOIN" => {
|
|
||||||
let room_code = &msg.args[0];
|
match room {
|
||||||
let rooms = self.global_state.rooms.lock().await;
|
Some(room) => {
|
||||||
let room = rooms.get(room_code);
|
let mut room = room.lock().await;
|
||||||
|
let (client_channel, server_channel) = channel_pair();
|
||||||
match room {
|
self.channel = Some(client_channel);
|
||||||
Some(room) => {
|
room.channels.push(server_channel);
|
||||||
let mut room = room.lock().await;
|
self.ws.send(msg!(JOIN_OK)).await.unwrap();
|
||||||
let (client_channel, server_channel) = channel_pair();
|
}
|
||||||
self.channel = Some(client_channel);
|
None => {
|
||||||
room.channels.push(server_channel);
|
self.ws.send(msg!(JOIN_INVALID)).await.unwrap();
|
||||||
self.ws.send(msg!(JOIN_OK)).await.unwrap();
|
}
|
||||||
}
|
}
|
||||||
None => {
|
}
|
||||||
self.ws.send(msg!(JOIN_INVALID)).await.unwrap();
|
_ => {
|
||||||
}
|
if let Some(channel) = &self.channel {
|
||||||
}
|
// Forward message to the server
|
||||||
}
|
channel.tx.send(msg).await.unwrap();
|
||||||
_ => if let Some(channel) = &self.channel {
|
}
|
||||||
// Forward message to the server
|
}
|
||||||
channel.tx.send(msg).await.unwrap();
|
}
|
||||||
}
|
}
|
||||||
}
|
async fn handle_server_msg(&mut self, _msg: Message) {
|
||||||
}
|
todo!();
|
||||||
async fn handle_server_msg(&mut self, _msg: Message) {
|
}
|
||||||
todo!();
|
}
|
||||||
}
|
|
||||||
}
|
fn game_loop(_gc: Arc<Mutex<GameController>>) {
|
||||||
|
todo!();
|
||||||
fn game_loop(_gc: Arc<Mutex<GameController>>) {
|
}
|
||||||
todo!();
|
|
||||||
}
|
|
||||||
|
@ -1,42 +1,39 @@
|
|||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
use sha2::{Sha256, Digest};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
pub struct CodeGenerator {
|
pub struct CodeGenerator {
|
||||||
counter: u64,
|
counter: u64,
|
||||||
salt: [u8; 32],
|
salt: [u8; 32],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CodeGenerator {
|
impl CodeGenerator {
|
||||||
pub fn generate(&mut self) -> String {
|
pub fn generate(&mut self) -> String {
|
||||||
let count = self.counter;
|
let count = self.counter;
|
||||||
self.counter += 1;
|
self.counter += 1;
|
||||||
|
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
hasher.update(self.salt);
|
hasher.update(self.salt);
|
||||||
hasher.update(count.to_be_bytes());
|
hasher.update(count.to_be_bytes());
|
||||||
|
|
||||||
format!("{:x}", hasher.finalize())[..6].to_string()
|
format!("{:x}", hasher.finalize())[..6].to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for CodeGenerator {
|
impl Default for CodeGenerator {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
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,
|
}
|
||||||
}
|
|
||||||
}
|
#[cfg(test)]
|
||||||
}
|
mod test {
|
||||||
|
use super::*;
|
||||||
#[cfg(test)]
|
#[test]
|
||||||
mod test {
|
fn test_generate() {
|
||||||
use super::*;
|
let code = CodeGenerator::default().generate();
|
||||||
#[test]
|
assert_eq!(code.len(), 6);
|
||||||
fn test_generate() {
|
}
|
||||||
let code = CodeGenerator::default().generate();
|
}
|
||||||
assert_eq!(code.len(), 6);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
66
src/lib.rs
66
src/lib.rs
@ -1,36 +1,30 @@
|
|||||||
use std::{
|
use std::{collections::HashMap, sync::Arc};
|
||||||
collections::HashMap,
|
|
||||||
sync::Arc,
|
use tokio::sync::{mpsc, Mutex};
|
||||||
};
|
|
||||||
|
pub mod message;
|
||||||
use tokio::sync::{Mutex, mpsc};
|
use message::Message;
|
||||||
|
mod code_generator;
|
||||||
pub mod message;
|
use code_generator::CodeGenerator;
|
||||||
use message::{Message};
|
|
||||||
mod code_generator;
|
#[derive(Default)]
|
||||||
use code_generator::CodeGenerator;
|
pub struct GlobalState {
|
||||||
|
pub code_generator: Arc<Mutex<CodeGenerator>>,
|
||||||
#[derive(Default)]
|
pub rooms: Arc<Mutex<HashMap<String, Arc<Mutex<GameController>>>>>,
|
||||||
pub struct GlobalState {
|
}
|
||||||
pub code_generator: Arc<Mutex<CodeGenerator>>,
|
|
||||||
pub rooms: Arc<Mutex<HashMap<String, Arc<Mutex<GameController>>>>>,
|
pub struct Channel {
|
||||||
}
|
pub tx: mpsc::Sender<Message>,
|
||||||
|
pub rx: mpsc::Receiver<Message>,
|
||||||
pub struct Channel {
|
}
|
||||||
pub tx: mpsc::Sender<Message>,
|
|
||||||
pub rx: mpsc::Receiver<Message>,
|
pub fn channel_pair() -> (Channel, Channel) {
|
||||||
}
|
let (atx, brx) = mpsc::channel(32);
|
||||||
|
let (btx, arx) = mpsc::channel(32);
|
||||||
pub fn channel_pair() -> (Channel, Channel) {
|
(Channel { tx: atx, rx: arx }, Channel { tx: btx, rx: brx })
|
||||||
let (atx, brx) = mpsc::channel(32);
|
}
|
||||||
let (btx, arx) = mpsc::channel(32);
|
|
||||||
(
|
#[derive(Default)]
|
||||||
Channel { tx: atx, rx: arx },
|
pub struct GameController {
|
||||||
Channel { tx: btx, rx: brx },
|
pub channels: Vec<Channel>,
|
||||||
)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct GameController {
|
|
||||||
pub channels: Vec<Channel>,
|
|
||||||
}
|
|
||||||
|
19
src/main.rs
19
src/main.rs
@ -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;
|
||||||
});
|
});
|
||||||
|
261
src/message.rs
261
src/message.rs
@ -1,131 +1,130 @@
|
|||||||
use std::convert::{From, TryFrom};
|
use std::convert::{From, TryFrom};
|
||||||
|
|
||||||
use tokio::net::TcpStream;
|
use futures::{SinkExt, StreamExt};
|
||||||
use tokio_tungstenite::{
|
use lazy_static::lazy_static;
|
||||||
WebSocketStream,
|
use tokio::net::TcpStream;
|
||||||
tungstenite::Message as WsMessage,
|
use tokio_tungstenite::{tungstenite::Message as WsMessage, WebSocketStream};
|
||||||
};
|
|
||||||
use futures::{StreamExt, SinkExt};
|
#[derive(PartialEq, Debug)]
|
||||||
use lazy_static::lazy_static;
|
pub struct Message {
|
||||||
|
pub command: String,
|
||||||
#[derive(PartialEq, Debug)]
|
pub args: Vec<String>,
|
||||||
pub struct Message {
|
}
|
||||||
pub command: String,
|
|
||||||
pub args: Vec<String>,
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
}
|
|
||||||
|
#[repr(u8)]
|
||||||
pub type Result<T> = std::result::Result<T, Error>;
|
#[derive(PartialEq, Debug)]
|
||||||
|
pub enum Error {
|
||||||
#[repr(u8)]
|
BadParse,
|
||||||
#[derive(PartialEq, Debug)]
|
NonText,
|
||||||
pub enum Error {
|
Unknown,
|
||||||
BadParse,
|
}
|
||||||
NonText,
|
|
||||||
Unknown,
|
impl Message {
|
||||||
}
|
pub fn parse(text: String) -> Result<Message> {
|
||||||
|
lazy_static! {
|
||||||
impl Message {
|
static ref RE: regex::Regex = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap();
|
||||||
pub fn parse(text: String) -> Result<Message> {
|
}
|
||||||
lazy_static! {
|
match RE.captures(text.as_str()) {
|
||||||
static ref RE: regex::Regex = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap();
|
Some(captures) => {
|
||||||
}
|
if captures.len() < 3 {
|
||||||
match RE.captures(text.as_str()) {
|
Err(Error::BadParse)
|
||||||
Some(captures) => {
|
} else {
|
||||||
if captures.len() < 3 {
|
let command = captures.get(1).unwrap().as_str().to_string();
|
||||||
Err(Error::BadParse)
|
let args = captures
|
||||||
} else {
|
.get(2)
|
||||||
let command = captures.get(1).unwrap().as_str().to_string();
|
.unwrap()
|
||||||
let args = captures.get(2).unwrap().as_str()
|
.as_str()
|
||||||
.split(',')
|
.split(',')
|
||||||
.map(|s| s.trim().to_string())
|
.map(|s| s.trim().to_string())
|
||||||
.collect();
|
.collect();
|
||||||
Ok(Message { command, args })
|
Ok(Message { command, args })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => Err(Error::BadParse),
|
None => Err(Error::BadParse),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<WsMessage> for Message {
|
impl TryFrom<WsMessage> for Message {
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Message> for WsMessage {
|
impl From<Message> for WsMessage {
|
||||||
fn from(message: Message) -> Self {
|
fn from(message: Message) -> Self {
|
||||||
WsMessage::Text(message.to_string())
|
WsMessage::Text(message.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MessageWebSocket(pub WebSocketStream<TcpStream>);
|
pub struct MessageWebSocket(pub WebSocketStream<TcpStream>);
|
||||||
|
|
||||||
impl MessageWebSocket {
|
impl MessageWebSocket {
|
||||||
pub async fn next(&mut self) -> Result<Message> {
|
pub async fn next(&mut self) -> Result<Message> {
|
||||||
if let Some(Ok(msg)) = self.0.next().await {
|
if let Some(Ok(msg)) = self.0.next().await {
|
||||||
msg.try_into()
|
msg.try_into()
|
||||||
} else {
|
} else {
|
||||||
Err(Error::Unknown)
|
Err(Error::Unknown)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn send(&mut self, msg: Message) -> Result<()> {
|
pub async fn send(&mut self, msg: Message) -> Result<()> {
|
||||||
if self.0.send(msg.into()).await.is_err() {
|
if self.0.send(msg.into()).await.is_err() {
|
||||||
Err(Error::Unknown)
|
Err(Error::Unknown)
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! msg {
|
macro_rules! msg {
|
||||||
( $command:ident) => {
|
( $command:ident) => {
|
||||||
{
|
{
|
||||||
let command = stringify!($command).to_string();
|
let command = stringify!($command).to_string();
|
||||||
let args = vec![];
|
let args = vec![];
|
||||||
Message { command, args }
|
Message { command, args }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
( $command:ident, $( $arg:expr ),*) => {
|
( $command:ident, $( $arg:expr ),*) => {
|
||||||
{
|
{
|
||||||
let command = stringify!($command).to_string();
|
let command = stringify!($command).to_string();
|
||||||
let args = vec![$($arg.to_string()),*];
|
let args = vec![$($arg.to_string()),*];
|
||||||
Message { command, args }
|
Message { command, args }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(", "))
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
#[cfg(test)]
|
||||||
#[cfg(test)]
|
mod test {
|
||||||
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());
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user