Run cargo fmt on codebase

This commit is contained in:
Sebastian Lohff 2021-12-31 02:18:38 +01:00
parent dfede05b88
commit 9357886b76
5 changed files with 53 additions and 34 deletions

View File

@ -11,7 +11,7 @@ impl From<std::io::Error> for ChatError {
}
}
impl <'a, T> From<std::sync::PoisonError<std::sync::MutexGuard<'a, T>>> for ChatError {
impl<'a, T> From<std::sync::PoisonError<std::sync::MutexGuard<'a, T>>> for ChatError {
fn from(_error: std::sync::PoisonError<std::sync::MutexGuard<'a, T>>) -> Self {
ChatError::MutexPoisonError()
}

View File

@ -1,13 +1,10 @@
use std::collections::BTreeMap;
use crate::chat_user::ChatUser;
use chrono::{DateTime, Utc};
use crate::config::ConfigArgs;
use std::net::TcpStream;
use std::io::Write;
use crate::chat_error::ChatError;
use crate::chat_user::ChatUser;
use crate::config::ConfigArgs;
use chrono::{DateTime, Utc};
use std::collections::BTreeMap;
use std::io::Write;
use std::net::TcpStream;
pub struct ChatServer {
pub config: ConfigArgs,
@ -17,7 +14,11 @@ pub struct ChatServer {
impl ChatServer {
pub fn new(config: ConfigArgs) -> Self {
Self{config, user_map: BTreeMap::new(), user_id_counter: 1}
Self {
config,
user_map: BTreeMap::new(),
user_id_counter: 1,
}
}
pub fn get_user_count(&self) -> usize {
@ -62,7 +63,6 @@ impl ChatServer {
}
pub fn is_nick_in_use(&self, name: &str) -> bool {
self.user_map.values().any(|client| { client.name == name })
self.user_map.values().any(|client| client.name == name)
}
}

View File

@ -14,6 +14,6 @@ pub struct ChatUser {
impl ChatUser {
pub fn new(id: u64, name: String, socket: TcpStream) -> Self {
Self{id, name, socket}
Self { id, name, socket }
}
}

View File

@ -1,4 +1,4 @@
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct ConfigArgs {
@ -6,4 +6,3 @@ pub struct ConfigArgs {
pub port: u16,
pub greeting_msg: String,
}

View File

@ -1,10 +1,10 @@
use std::sync::{Arc, Mutex};
use std::net::{TcpListener, TcpStream};
use std::thread;
use clap::Parser;
use std::fs::File;
use std::io::Write;
use std::io::{self, BufRead};
use std::fs::File;
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
mod chat_error;
use chat_error::ChatError;
@ -17,8 +17,11 @@ use chat_server::ChatServer;
mod config;
use config::ConfigArgs;
fn handle_client(mut stream: TcpStream, server: Arc<Mutex<ChatServer>>, client_id: &mut Option<u64>) -> Result<(), ChatError> {
fn handle_client(
mut stream: TcpStream,
server: Arc<Mutex<ChatServer>>,
client_id: &mut Option<u64>,
) -> Result<(), ChatError> {
let mut writer = stream.try_clone()?;
let reader = io::BufReader::new(&mut stream);
let mut lines = reader.lines();
@ -27,20 +30,33 @@ fn handle_client(mut stream: TcpStream, server: Arc<Mutex<ChatServer>>, client_i
write!(writer, "Hello and welcome to RustChat!\nNick: ")?;
let mut nick;
loop {
nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??;
nick = lines
.next()
.ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??;
// check for nick name uniqueness
let mut srv = server.lock()?;
if ! srv.is_nick_in_use(&nick) {
if !srv.is_nick_in_use(&nick) {
// print joined msg and register at server
srv.send_to_all(&format!("* {} has joined the chat", nick))?;
let curr_users = srv.get_user_count();
let users_in_room_msg = if curr_users == 1 { String::from("is 1 user") } else { format!("are {} users", curr_users) };
write!(writer, " *** {}\n *** You are known as {}. There {} in the room.\n", srv.config.greeting_msg, nick, users_in_room_msg)?;
let users_in_room_msg = if curr_users == 1 {
String::from("is 1 user")
} else {
format!("are {} users", curr_users)
};
write!(
writer,
" *** {}\n *** You are known as {}. There {} in the room.\n",
srv.config.greeting_msg, nick, users_in_room_msg
)?;
*client_id = Some(srv.register(nick.clone(), writer));
break;
}
write!(writer, "This nickname is already in use, please choose another.\nNick: ")?;
write!(
writer,
"This nickname is already in use, please choose another.\nNick: "
)?;
}
// read lines
@ -55,7 +71,6 @@ fn handle_client(mut stream: TcpStream, server: Arc<Mutex<ChatServer>>, client_i
Ok(())
}
fn run_thread(stream: TcpStream, server: Arc<Mutex<ChatServer>>) {
let mut client_id = None;
let quit_reason = match handle_client(stream, Arc::clone(&server), &mut client_id) {
@ -65,7 +80,10 @@ fn run_thread(stream: TcpStream, server: Arc<Mutex<ChatServer>>) {
if let Some(client_id) = client_id {
let mut srv = server.lock().unwrap();
let name = srv.deregister(client_id).map(|client| client.name).unwrap_or("<unknown user>".into());
let name = srv
.deregister(client_id)
.map(|client| client.name)
.unwrap_or("<unknown user>".into());
let quit_msg = format!("* {} has left the chat ({})", name, quit_reason);
println!("{}", quit_msg);
srv.send_to_all(&quit_msg).unwrap();
@ -74,7 +92,6 @@ fn run_thread(stream: TcpStream, server: Arc<Mutex<ChatServer>>) {
}
}
/// Chatserver in RUST!
#[derive(Parser, Debug)]
#[clap(about, version, author)]
@ -98,7 +115,8 @@ fn main() -> std::io::Result<()> {
// read config file
let config_reader = File::open(args.config).expect("Could not open config file");
let mut config: ConfigArgs = serde_yaml::from_reader(&config_reader).expect("Could not parse config file");
let mut config: ConfigArgs =
serde_yaml::from_reader(&config_reader).expect("Could not parse config file");
if let Some(host) = args.host {
config.host = host;
@ -116,7 +134,9 @@ fn main() -> std::io::Result<()> {
for stream in listener.incoming() {
if let Ok(stream) = stream {
let server_clone = Arc::clone(&server);
thread::spawn(move || { run_thread(stream, server_clone); });
thread::spawn(move || {
run_thread(stream, server_clone);
});
}
}
Ok(())