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=build.rs");
let mut files = Vec::new();
for f in read_dir("../protobuf").unwrap() {
if let Ok(f) = f {
for f in read_dir("../protobuf").unwrap().flatten() {
if f.path().is_file() && f.path().extension().map(|x| x == "proto").unwrap_or(false) {
files.push(f.path());
}
}
}
if let Err(e) = prost_build::Config::new()
.out_dir("src/server/protos")
.compile_protos(

4
server/src/allocator.rs

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

8
server/src/command.rs

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

6
server/src/db.rs

@ -42,12 +42,11 @@ impl Db {
}
pub fn add_user(&mut self, name: String) -> Result<Uuid> {
loop {
let uuid = Uuid::new_v4();
// println!("{:?}", uuid.as_bytes().to_vec());
let res = self.conn.execute(
"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
if let Err(e) = res {
@ -69,8 +68,7 @@ impl Db {
}
}
return Ok(uuid);
}
Ok(uuid)
}
// FIXME: return Results intead of crashing
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();
tokio::task::spawn_blocking(|| cache_image(p, folder));
}
for (
_,
for
Card {
image,
back_image,
other: _,
},
) in &self.available_cards
} in self.available_cards.values()
{
{
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());
let mut face_buf = Vec::new();
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)
.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) {
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(
&card
.back_image
.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");
back.set_extension("png");
@ -97,18 +97,14 @@ impl std::fmt::Debug for Game {
pub fn load_games() -> Vec<Game> {
config::setup();
let mut games = Vec::new();
for file in read_dir("games").unwrap() {
if let Ok(folder) = file {
for folder in read_dir("games").unwrap().flatten() {
if folder.path().is_dir() {
for file in read_dir(folder.path()).unwrap() {
if let Ok(file) = file {
for file in read_dir(folder.path()).unwrap().flatten() {
if file.file_name().to_str().unwrap() == "game.json" {
games.push(Game::load(folder.path()))
}
}
}
}
}
}
games
}

6
server/src/games/run.rs

@ -80,13 +80,13 @@ impl RunningGame {
.unwrap();
let mut players = HashMap::new();
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);
Self {
name,
piles: piles,
player_piles: player_piles,
piles,
player_piles,
functions,
current_player: Player::new(0, current_players.len() as u32),
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),
};
card_maybe
.map(|x| to_dynamic(x))
.unwrap_or(Ok(Dynamic::default()))
.map(to_dynamic)
.unwrap_or_else(|| Ok(Dynamic::default()))
}
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
.cards
.pop()
.map(|x| to_dynamic(x))
.unwrap_or(Ok(Dynamic::default())),
.map(to_dynamic)
.unwrap_or_else(|| Ok(Dynamic::default())),
super::CardIdx::Indexed(i) => to_dynamic(&pile.cards.remove(i)),
};
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 engine = setup_engine(conf);
Self {
engine,
ast,
engine,
has_turn_start,
}
}

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

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

8
server/src/logger.rs

@ -99,10 +99,7 @@ fn colored_formatter(d: fern::Dispatch) -> fern::Dispatch {
.debug(Color::BrightBlack)
// depending on the terminals color scheme, this is the same as the background color
.trace(Color::BrightBlack);
let colors_level = colors_line
.clone()
.info(Color::Green)
.debug(Color::BrightBlack);
let colors_level = colors_line.info(Color::Green).debug(Color::BrightBlack);
d.format(
move |out: fern::FormatCallback, message: _, record: &log::Record| {
out.finish(format_args!(
@ -144,6 +141,7 @@ where
T: Send + 'static,
F: Fn(String) -> T + Send + 'static,
{
#[allow(clippy::new_ret_no_self)]
fn new(
handler: F,
use_colors: bool,
@ -367,7 +365,7 @@ impl<T> LimitedVec<T> {
.and_then(|x| x.checked_sub(self.pos))
.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() {
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 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 {
let mut s = String::new();
let mut highlight = false;
@ -26,22 +26,20 @@ pub fn print_line(message: &String, use_colors: bool, stdout: &mut std::io::Stdo
current
);
queue!(stdout, Print(styled)).unwrap();
s = String::new();
} else {
queue!(stdout, Print(s)).unwrap();
s = String::new();
}
s = String::new();
highlight = !highlight;
continue;
} else {
if !highlight {
if let Some(m) = ANSI_REGEX.find_at(message.as_str(), i) {
} else if !highlight {
if let Some(m) = ANSI_REGEX.find_at(message, i) {
if i == m.start() {
current = m.as_str().to_string();
}
}
}
}
i += 1;
s.push(c);
}

48
server/src/server.rs

@ -103,15 +103,7 @@ pub async fn start(
// }
// }
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: Arc<
type RunningGames = Arc<
RwLock<
HashMap<
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());
loop {
let (stream, addr) = listener.accept().await?;
@ -205,9 +207,9 @@ pub async fn serve(
&mut service_data,
writer
.take()
.ok_or(anyhow::anyhow!(
"Connect shouldn't be called more than once"
))
.ok_or_else(|| {
anyhow::anyhow!("Connect shouldn't be called more than once")
})
.unwrap(),
&socket_manager,
name,
@ -280,18 +282,7 @@ struct ServiceData {
properties: Arc<ServerProperties>,
games: Arc<Vec<crate::games::Game>>,
voting: VotingSystem,
running_games: Arc<
RwLock<
HashMap<
u32,
RwLock<(
u32,
RunningGame,
votes::Modifiable<Option<protos::game::GameStatus>>,
)>,
>,
>,
>,
running_games: RunningGames,
addr: SocketAddr,
db: db::DbClient,
}
@ -313,12 +304,13 @@ impl UserId {
}
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> {
self.0
.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 mut names = vec![];
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));
let names = names

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

@ -1,6 +1,9 @@
#[derive(Clone, PartialEq, ::prost::Message)]
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>,
}
/// Nested message and enum types in `ClientServerPacket`.
@ -42,7 +45,10 @@ pub mod client_server_packet {
}
#[derive(Clone, PartialEq, ::prost::Message)]
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>,
}
/// Nested message and enum types in `ServerClientPacket`.

2
server/src/server/socket_manager.rs

@ -74,7 +74,7 @@ impl SocketManager {
{
let mut lock = lock
.get(uuid)
.ok_or(anyhow!("Can't get socket with uuid {}", uuid))?
.ok_or_else(|| anyhow!("Can't get socket with uuid {}", uuid))?
.write()
.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);
type LastStatus = Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>;
#[derive(Clone)]
pub struct VotingSystem {
conn: Arc<RwLock<db::DbClient>>,
// games: Arc<Vec<crate::games::Game>>,
// broadcast: broadcast::Sender<Message>,
last_status: Arc<RwLock<HashMap<u32, Arc<RwLock<Modifiable<(Message, Option<SystemTime>)>>>>>>,
last_status: LastStatus,
}
impl VotingSystem {
@ -80,6 +81,7 @@ impl VotingSystem {
timeout: Option<SystemTime>,
) {
let mut lock = self.last_status.write().await;
#[allow(clippy::map_entry)]
if lock.contains_key(&lobby) {
lock.get(&lobby)
.unwrap()

2
server/src/server_properties.rs

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

Loading…
Cancel
Save