Browse Source

Fix all clippy lints

main
ThePerkinrex 5 years ago
parent
commit
1126683f79
No known key found for this signature in database GPG Key ID: FD81DE6D75E20917
  1. 4
      server/build.rs
  2. 4
      server/src/allocator.rs
  3. 8
      server/src/command.rs
  4. 6
      server/src/db.rs
  5. 8
      server/src/games/config.rs
  6. 12
      server/src/games/mod.rs
  7. 6
      server/src/games/run.rs
  8. 8
      server/src/games/run/engine.rs
  9. 2
      server/src/games/run/functions.rs
  10. 8
      server/src/games/run/types.rs
  11. 8
      server/src/logger.rs
  12. 12
      server/src/logger/color_message.rs
  13. 48
      server/src/server.rs
  14. 2
      server/src/server/game.rs
  15. 10
      server/src/server/protos/protocol.rs
  16. 2
      server/src/server/socket_manager.rs
  17. 4
      server/src/server/votes.rs
  18. 2
      server/src/server_properties.rs

4
server/build.rs

@ -4,13 +4,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=../protobuf/"); println!("cargo:rerun-if-changed=../protobuf/");
println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=build.rs");
let mut files = Vec::new(); let mut files = Vec::new();
for f in read_dir("../protobuf").unwrap() { for f in read_dir("../protobuf").unwrap().flatten() {
if let Ok(f) = f {
if f.path().is_file() && f.path().extension().map(|x| x == "proto").unwrap_or(false) { if f.path().is_file() && f.path().extension().map(|x| x == "proto").unwrap_or(false) {
files.push(f.path()); files.push(f.path());
} }
} }
}
if let Err(e) = prost_build::Config::new() if let Err(e) = prost_build::Config::new()
.out_dir("src/server/protos") .out_dir("src/server/protos")
.compile_protos( .compile_protos(

4
server/src/allocator.rs

@ -14,7 +14,7 @@ unsafe impl GlobalAlloc for Allocator {
if !ret.is_null() { if !ret.is_null() {
ALLOCATED.fetch_add(layout.size(), SeqCst); ALLOCATED.fetch_add(layout.size(), SeqCst);
} }
return ret; ret
} }
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
@ -32,7 +32,7 @@ impl Allocator {
#[global_allocator] #[global_allocator]
static ALLOCATOR: Allocator = Allocator; static ALLOCATOR: Allocator = Allocator;
static UNITS: (&'static str, &'static [(&'static str, usize)]) = ( static UNITS: (&str, &[(&str, usize)]) = (
"b", "b",
&[ &[
("B", 8), ("B", 8),

8
server/src/command.rs

@ -2,11 +2,9 @@ use std::fs::read_dir;
pub fn command_handler(command: String) -> String { pub fn command_handler(command: String) -> String {
if command == "reload_cache" { if command == "reload_cache" {
for file in read_dir("games").unwrap() { for folder in read_dir("games").unwrap().flatten() {
if let Ok(folder) = file {
if folder.path().is_dir() { if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() { for file in read_dir(folder.path()).unwrap().flatten() {
if let Ok(file) = file {
if file.file_name().to_str().unwrap() == "game.json" { if file.file_name().to_str().unwrap() == "game.json" {
let conf = crate::games::Config::load(file.path()); let conf = crate::games::Config::load(file.path());
log::info!("Reloading caches for {}", conf.name); log::info!("Reloading caches for {}", conf.name);
@ -16,7 +14,5 @@ pub fn command_handler(command: String) -> String {
} }
} }
} }
}
}
command command
} }

6
server/src/db.rs

@ -42,12 +42,11 @@ impl Db {
} }
pub fn add_user(&mut self, name: String) -> Result<Uuid> { pub fn add_user(&mut self, name: String) -> Result<Uuid> {
loop {
let uuid = Uuid::new_v4(); let uuid = Uuid::new_v4();
// println!("{:?}", uuid.as_bytes().to_vec()); // println!("{:?}", uuid.as_bytes().to_vec());
let res = self.conn.execute( let res = self.conn.execute(
"INSERT INTO Users(uuid, name) VALUES(?, ?)", "INSERT INTO Users(uuid, name) VALUES(?, ?)",
params![uuid.as_bytes().to_vec(), name.to_string()], params![uuid.as_bytes().to_vec(), name],
); // Server crashes if uuids collide ); // Server crashes if uuids collide
if let Err(e) = res { if let Err(e) = res {
@ -69,8 +68,7 @@ impl Db {
} }
} }
return Ok(uuid); Ok(uuid)
}
} }
// FIXME: return Results intead of crashing // FIXME: return Results intead of crashing
pub fn get_users_in_lobby_where_user_is(&mut self, uuid: Uuid) -> Vec<String> { pub fn get_users_in_lobby_where_user_is(&mut self, uuid: Uuid) -> Vec<String> {

8
server/src/games/config.rs

@ -77,14 +77,12 @@ impl Config {
let folder = folder.clone(); let folder = folder.clone();
tokio::task::spawn_blocking(|| cache_image(p, folder)); tokio::task::spawn_blocking(|| cache_image(p, folder));
} }
for ( for
_,
Card { Card {
image, image,
back_image, back_image,
other: _, other: _,
}, } in self.available_cards.values()
) in &self.available_cards
{ {
{ {
let folder = folder.clone(); let folder = folder.clone();
@ -128,7 +126,7 @@ fn cache_image<P1: AsRef<Path>, P2: AsRef<Path>>(p: P1, folder: P2) {
// log::info!("Updating cache for: {}", original.display()); // log::info!("Updating cache for: {}", original.display());
let mut face_buf = Vec::new(); let mut face_buf = Vec::new();
image::open(&original) image::open(&original)
.expect(&format!("Error loading the image in {:?}", original)) .unwrap_or_else(|e| panic!("Error loading the image in {:?} ({})", original, e))
.write_to(&mut face_buf, image::ImageOutputFormat::Png) .write_to(&mut face_buf, image::ImageOutputFormat::Png)
.unwrap(); .unwrap();
match std::fs::create_dir_all(cached.parent().unwrap()) { match std::fs::create_dir_all(cached.parent().unwrap()) {

12
server/src/games/mod.rs

@ -59,12 +59,12 @@ impl Game {
pub fn get_card_paths(&self, image: &str) -> (std::path::PathBuf, std::path::PathBuf) { pub fn get_card_paths(&self, image: &str) -> (std::path::PathBuf, std::path::PathBuf) {
let card = &self.conf.available_cards[image]; let card = &self.conf.available_cards[image];
let mut front = self.folder.join(".cache").join(&card.image).to_path_buf(); let mut front = self.folder.join(".cache").join(&card.image);
let mut back = self.folder.join(".cache").join( let mut back = self.folder.join(".cache").join(
&card &card
.back_image .back_image
.as_ref() .as_ref()
.unwrap_or(self.conf.default_back.as_ref().unwrap()), .unwrap_or_else(|| self.conf.default_back.as_ref().unwrap()),
); );
front.set_extension("png"); front.set_extension("png");
back.set_extension("png"); back.set_extension("png");
@ -97,18 +97,14 @@ impl std::fmt::Debug for Game {
pub fn load_games() -> Vec<Game> { pub fn load_games() -> Vec<Game> {
config::setup(); config::setup();
let mut games = Vec::new(); let mut games = Vec::new();
for file in read_dir("games").unwrap() { for folder in read_dir("games").unwrap().flatten() {
if let Ok(folder) = file {
if folder.path().is_dir() { if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() { for file in read_dir(folder.path()).unwrap().flatten() {
if let Ok(file) = file {
if file.file_name().to_str().unwrap() == "game.json" { if file.file_name().to_str().unwrap() == "game.json" {
games.push(Game::load(folder.path())) games.push(Game::load(folder.path()))
} }
} }
} }
} }
}
}
games games
} }

6
server/src/games/run.rs

@ -80,13 +80,13 @@ impl RunningGame {
.unwrap(); .unwrap();
let mut players = HashMap::new(); let mut players = HashMap::new();
for (i, player) in current_players.iter().enumerate() { for (i, player) in current_players.iter().enumerate() {
players.insert(player.clone(), i as u32); players.insert(*player, i as u32);
} }
log::info!("Players in game {}: {:?}", name, players); log::info!("Players in game {}: {:?}", name, players);
Self { Self {
name, name,
piles: piles, piles,
player_piles: player_piles, player_piles,
functions, functions,
current_player: Player::new(0, current_players.len() as u32), current_player: Player::new(0, current_players.len() as u32),
data: other, data: other,

8
server/src/games/run/engine.rs

@ -97,8 +97,8 @@ fn get_card_from_id(data: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::E
super::CardIdx::Indexed(i) => pile.cards.get(i), super::CardIdx::Indexed(i) => pile.cards.get(i),
}; };
card_maybe card_maybe
.map(|x| to_dynamic(x)) .map(to_dynamic)
.unwrap_or(Ok(Dynamic::default())) .unwrap_or_else(|| Ok(Dynamic::default()))
} }
fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::EvalAltResult>> { fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rhai::EvalAltResult>> {
@ -116,8 +116,8 @@ fn pop_card_from_id(data_dyn: &mut Map, card: CardId) -> Result<Dynamic, Box<rha
super::CardIdx::Bottom => pile super::CardIdx::Bottom => pile
.cards .cards
.pop() .pop()
.map(|x| to_dynamic(x)) .map(to_dynamic)
.unwrap_or(Ok(Dynamic::default())), .unwrap_or_else(|| Ok(Dynamic::default())),
super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)), super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)),
}; };
dynamic = to_dynamic(&data)?; dynamic = to_dynamic(&data)?;

2
server/src/games/run/functions.rs

@ -34,8 +34,8 @@ impl Functions {
let has_turn_start = fns.contains(&"turn_start".to_string()); let has_turn_start = fns.contains(&"turn_start".to_string());
let engine = setup_engine(conf); let engine = setup_engine(conf);
Self { Self {
engine,
ast, ast,
engine,
has_turn_start, has_turn_start,
} }
} }

8
server/src/games/run/types.rs

@ -236,12 +236,6 @@ impl RunningPile {
other.insert(k, v); other.insert(k, v);
} }
Ok(Self { Ok(Self { name, cards, face_down, visible, other })
cards,
other,
face_down,
visible,
name,
})
} }
} }

8
server/src/logger.rs

@ -99,10 +99,7 @@ fn colored_formatter(d: fern::Dispatch) -> fern::Dispatch {
.debug(Color::BrightBlack) .debug(Color::BrightBlack)
// depending on the terminals color scheme, this is the same as the background color // depending on the terminals color scheme, this is the same as the background color
.trace(Color::BrightBlack); .trace(Color::BrightBlack);
let colors_level = colors_line let colors_level = colors_line.info(Color::Green).debug(Color::BrightBlack);
.clone()
.info(Color::Green)
.debug(Color::BrightBlack);
d.format( d.format(
move |out: fern::FormatCallback, message: _, record: &log::Record| { move |out: fern::FormatCallback, message: _, record: &log::Record| {
out.finish(format_args!( out.finish(format_args!(
@ -144,6 +141,7 @@ where
T: Send + 'static, T: Send + 'static,
F: Fn(String) -> T + Send + 'static, F: Fn(String) -> T + Send + 'static,
{ {
#[allow(clippy::new_ret_no_self)]
fn new( fn new(
handler: F, handler: F,
use_colors: bool, use_colors: bool,
@ -367,7 +365,7 @@ impl<T> LimitedVec<T> {
.and_then(|x| x.checked_sub(self.pos)) .and_then(|x| x.checked_sub(self.pos))
.unwrap_or(0) .unwrap_or(0)
}; };
let mut end = self.inner.len().checked_sub(self.pos).unwrap_or(0); let mut end = self.inner.len().saturating_sub(self.pos);
if end < self.inner.len() { if end < self.inner.len() {
end = self.inner.len() end = self.inner.len()
} }

12
server/src/logger/color_message.rs

@ -9,7 +9,7 @@ lazy_static! {
pub static ref ANSI_REGEX: Regex = Regex::new(ANSI_RE).unwrap(); pub static ref ANSI_REGEX: Regex = Regex::new(ANSI_RE).unwrap();
} }
pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdout) { pub fn print_line(message: &str, use_colors: bool, stdout: &mut std::io::Stdout) {
if use_colors { if use_colors {
let mut s = String::new(); let mut s = String::new();
let mut highlight = false; let mut highlight = false;
@ -26,22 +26,20 @@ pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdo
current current
); );
queue!(stdout, Print(styled)).unwrap(); queue!(stdout, Print(styled)).unwrap();
s = String::new();
} else { } else {
queue!(stdout, Print(s)).unwrap(); queue!(stdout, Print(s)).unwrap();
s = String::new();
} }
s = String::new();
highlight = !highlight; highlight = !highlight;
continue; continue;
} else { } else if !highlight {
if !highlight { if let Some(m) = ANSI_REGEX.find_at(message, i) {
if let Some(m) = ANSI_REGEX.find_at(message.as_str(), i) {
if i == m.start() { if i == m.start() {
current = m.as_str().to_string(); current = m.as_str().to_string();
} }
} }
} }
}
i += 1; i += 1;
s.push(c); s.push(c);
} }

48
server/src/server.rs

@ -103,15 +103,7 @@ pub async fn start(
// } // }
// } // }
pub async fn serve( type RunningGames = Arc<
mut pool: db::DbClient,
games: Vec<crate::games::Game>,
properties: crate::server_properties::ServerProperties,
) -> Result<(), std::io::Error> {
let properties = Arc::new(properties);
let games = Arc::new(games);
let voting = votes::VotingSystem::new(pool.clone().await);
let running_games: Arc<
RwLock< RwLock<
HashMap< HashMap<
u32, u32,
@ -122,8 +114,18 @@ pub async fn serve(
)>, )>,
>, >,
>, >,
> = Default::default(); >;
let listener = TcpListener::bind(properties.addr.clone()).await?;
pub async fn serve(
mut pool: db::DbClient,
games: Vec<crate::games::Game>,
properties: crate::server_properties::ServerProperties,
) -> Result<(), std::io::Error> {
let properties = Arc::new(properties);
let games = Arc::new(games);
let voting = votes::VotingSystem::new(pool.clone().await);
let running_games: RunningGames = Default::default();
let listener = TcpListener::bind(properties.addr).await?;
let socket_manager = Arc::new(SocketManager::new()); let socket_manager = Arc::new(SocketManager::new());
loop { loop {
let (stream, addr) = listener.accept().await?; let (stream, addr) = listener.accept().await?;
@ -205,9 +207,9 @@ pub async fn serve(
&mut service_data, &mut service_data,
writer writer
.take() .take()
.ok_or(anyhow::anyhow!( .ok_or_else(|| {
"Connect shouldn't be called more than once" anyhow::anyhow!("Connect shouldn't be called more than once")
)) })
.unwrap(), .unwrap(),
&socket_manager, &socket_manager,
name, name,
@ -280,18 +282,7 @@ struct ServiceData {
properties: Arc<ServerProperties>, properties: Arc<ServerProperties>,
games: Arc<Vec<crate::games::Game>>, games: Arc<Vec<crate::games::Game>>,
voting: VotingSystem, voting: VotingSystem,
running_games: Arc< running_games: RunningGames,
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
>,
addr: SocketAddr, addr: SocketAddr,
db: db::DbClient, db: db::DbClient,
} }
@ -313,12 +304,13 @@ impl UserId {
} }
pub fn get(self) -> Result<Uuid> { pub fn get(self) -> Result<Uuid> {
self.0.ok_or(anyhow::anyhow!("User should have connected")) self.0
.ok_or_else(|| anyhow::anyhow!("User should have connected"))
} }
pub fn get_ref(&self) -> Result<&Uuid> { pub fn get_ref(&self) -> Result<&Uuid> {
self.0 self.0
.as_ref() .as_ref()
.ok_or(anyhow::anyhow!("User should have connected")) .ok_or_else(|| anyhow::anyhow!("User should have connected"))
} }
} }

2
server/src/server/game.rs

@ -26,7 +26,7 @@ pub(super) async fn get_status(data: &mut ServiceData) -> Result<GameStatus> {
let game = &game_lock.1; let game = &game_lock.1;
let mut names = vec![]; let mut names = vec![];
for (uuid, id) in &game.players { for (uuid, id) in &game.players {
names.push((data.db.get_name_for_uuid(uuid.clone()).await, *id)) names.push((data.db.get_name_for_uuid(*uuid).await, *id))
} }
names.sort_by(|(_, a), (_, b)| a.cmp(b)); names.sort_by(|(_, a), (_, b)| a.cmp(b));
let names = names let names = names

10
server/src/server/protos/protocol.rs

@ -1,6 +1,9 @@
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientServerPacket { pub struct ClientServerPacket {
#[prost(oneof="client_server_packet::Data", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14")] #[prost(
oneof = "client_server_packet::Data",
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14"
)]
pub data: ::core::option::Option<client_server_packet::Data>, pub data: ::core::option::Option<client_server_packet::Data>,
} }
/// Nested message and enum types in `ClientServerPacket`. /// Nested message and enum types in `ClientServerPacket`.
@ -42,7 +45,10 @@ pub mod client_server_packet {
} }
#[derive(Clone, PartialEq, ::prost::Message)] #[derive(Clone, PartialEq, ::prost::Message)]
pub struct ServerClientPacket { pub struct ServerClientPacket {
#[prost(oneof="server_client_packet::Data", tags="1, 2, 3, 4, 5, 6, 7, 8, 9")] #[prost(
oneof = "server_client_packet::Data",
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9"
)]
pub data: ::core::option::Option<server_client_packet::Data>, pub data: ::core::option::Option<server_client_packet::Data>,
} }
/// Nested message and enum types in `ServerClientPacket`. /// Nested message and enum types in `ServerClientPacket`.

2
server/src/server/socket_manager.rs

@ -74,7 +74,7 @@ impl SocketManager {
{ {
let mut lock = lock let mut lock = lock
.get(uuid) .get(uuid)
.ok_or(anyhow!("Can't get socket with uuid {}", uuid))? .ok_or_else(|| anyhow!("Can't get socket with uuid {}", uuid))?
.write() .write()
.await; .await;
lock.write(message).await?; lock.write(message).await?;

4
server/src/server/votes.rs

@ -44,13 +44,14 @@ impl<T> Modifiable<T> {
} }
const STATUS_TIMEOUT: Duration = Duration::from_secs(120); const STATUS_TIMEOUT: Duration = Duration::from_secs(120);
type LastStatus = Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>;
#[derive(Clone)] #[derive(Clone)]
pub struct VotingSystem { pub struct VotingSystem {
conn: Arc<RwLock<db::DbClient>>, conn: Arc<RwLock<db::DbClient>>,
// games: Arc<Vec<crate::games::Game>>, // games: Arc<Vec<crate::games::Game>>,
// broadcast: broadcast::Sender<Message>, // broadcast: broadcast::Sender<Message>,
last_status: Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>, last_status: LastStatus,
} }
impl VotingSystem { impl VotingSystem {
@ -80,6 +81,7 @@ impl VotingSystem {
timeout: Option<SystemTime>, timeout: Option<SystemTime>,
) { ) {
let mut lock = self.last_status.write().await; let mut lock = self.last_status.write().await;
#[allow(clippy::map_entry)]
if lock.contains_key(&lobby) { if lock.contains_key(&lobby) {
lock.get(&lobby) lock.get(&lobby)
.unwrap() .unwrap()

2
server/src/server_properties.rs

@ -12,7 +12,7 @@ pub struct ServerProperties {
#[serde(default = "default_colors")] #[serde(default = "default_colors")]
pub use_colors: bool, pub use_colors: bool,
#[serde(alias = "$schema", default = "default_schema")] #[serde(alias = "$schema", default = "default_schema")]
schema: String schema: String,
} }
impl ServerProperties { impl ServerProperties {

Loading…
Cancel
Save