Run cargo fmt on codebase

main
Sebastian Lohff 2 years ago
parent dfede05b88
commit 9357886b76

@ -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()
}

@ -1,13 +1,10 @@
use std::collections::BTreeMap;
use crate::chat_error::ChatError;
use crate::chat_user::ChatUser;
use chrono::{DateTime, Utc};
use crate::config::ConfigArgs;
use std::net::TcpStream;
use chrono::{DateTime, Utc};
use std::collections::BTreeMap;
use std::io::Write;
use crate::chat_error::ChatError;
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)
}
}

@ -4,16 +4,16 @@ use std::net::TcpStream;
pub struct ChatUser {
/// user id
pub id: u64,
/// Name of the chat user
pub name: String,
/// TCPStream socket object thingy
pub socket: TcpStream,
}
impl ChatUser {
pub fn new(id: u64, name: String, socket: TcpStream) -> Self {
Self{id, name, socket}
Self { id, name, socket }
}
}

@ -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,
}

@ -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(())

Loading…
Cancel
Save