Initial clippy fixes as discussed in #587

This commit is contained in:
Ben Wallis 2020-06-08 19:37:41 +01:00
parent 8b2b9e45ec
commit de37de7f45
23 changed files with 70 additions and 84 deletions

View File

@ -281,7 +281,7 @@ lazy_static! {
// VELOREN_ASSETS environment variable // VELOREN_ASSETS environment variable
if let Ok(var) = std::env::var("VELOREN_ASSETS") { if let Ok(var) = std::env::var("VELOREN_ASSETS") {
paths.push(var.to_owned().into()); paths.push(var.into());
} }
// Executable path // Executable path

View File

@ -56,7 +56,7 @@ pub enum ChatCommand {
} }
// Thank you for keeping this sorted alphabetically :-) // Thank you for keeping this sorted alphabetically :-)
pub static CHAT_COMMANDS: &'static [ChatCommand] = &[ pub static CHAT_COMMANDS: &[ChatCommand] = &[
ChatCommand::Adminify, ChatCommand::Adminify,
ChatCommand::Alias, ChatCommand::Alias,
ChatCommand::Build, ChatCommand::Build,
@ -118,11 +118,9 @@ lazy_static! {
let path = entry?.path(); let path = entry?.path();
if path.is_dir(){ if path.is_dir(){
list_items(&path, &base, &mut items)?; list_items(&path, &base, &mut items)?;
} else { } else if let Ok(path) = path.strip_prefix(base) {
if let Ok(path) = path.strip_prefix(base) { let path = path.to_string_lossy().trim_end_matches(".ron").replace('/', ".");
let path = path.to_string_lossy().trim_end_matches(".ron").replace('/', "."); items.push(path);
items.push(path);
}
} }
} }
Ok(()) Ok(())
@ -348,7 +346,7 @@ impl FromStr for ChatCommand {
type Err = (); type Err = ();
fn from_str(keyword: &str) -> Result<ChatCommand, ()> { fn from_str(keyword: &str) -> Result<ChatCommand, ()> {
let kwd = if keyword.chars().next() == Some('/') { let kwd = if keyword.starts_with('/') {
&keyword[1..] &keyword[1..]
} else { } else {
&keyword[..] &keyword[..]
@ -358,7 +356,7 @@ impl FromStr for ChatCommand {
return Ok(*c); return Ok(*c);
} }
} }
return Err(()); Err(())
} }
} }

View File

@ -203,9 +203,10 @@ impl From<&CharacterAbility> for CharacterState {
stage_exhausted: false, stage_exhausted: false,
stage_time_active: Duration::default(), stage_time_active: Duration::default(),
initialized: false, initialized: false,
transition_style: match *needs_timing { transition_style: if *needs_timing {
true => TransitionStyle::Timed(TimingState::NotPressed), TransitionStyle::Timed(TimingState::NotPressed)
false => TransitionStyle::Hold(HoldingState::Holding), } else {
TransitionStyle::Hold(HoldingState::Holding)
}, },
}), }),
} }

View File

@ -150,7 +150,7 @@ impl SpeechBubble {
{ {
match &self.message { match &self.message {
SpeechBubbleMessage::Plain(m) => m.to_string(), SpeechBubbleMessage::Plain(m) => m.to_string(),
SpeechBubbleMessage::Localized(k, i) => i18n_variation(k.to_string(), *i).to_string(), SpeechBubbleMessage::Localized(k, i) => i18n_variation(k.to_string(), *i),
} }
} }
} }

View File

@ -164,7 +164,7 @@ impl Inventory {
} }
} }
self.recount_items(); self.recount_items();
if leftovers.len() > 0 { if !leftovers.is_empty() {
Err(Error::Full(leftovers)) Err(Error::Full(leftovers))
} else { } else {
Ok(()) Ok(())
@ -187,7 +187,7 @@ impl Inventory {
self.push(item).map(|overflow| leftovers.push(overflow)); self.push(item).map(|overflow| leftovers.push(overflow));
} // else drop item if it was already in } // else drop item if it was already in
} }
if leftovers.len() > 0 { if !leftovers.is_empty() {
Err(Error::Full(leftovers)) Err(Error::Full(leftovers))
} else { } else {
Ok(()) Ok(())

View File

@ -31,7 +31,7 @@ fn push_all_full() {
amount: 0, amount: 0,
}; };
let Error::Full(leftovers) = inv let Error::Full(leftovers) = inv
.push_all(TEST_ITEMS.iter().map(|a| a.clone())) .push_all(TEST_ITEMS.iter().cloned())
.expect_err("Pushing into a full inventory somehow worked!"); .expect_err("Pushing into a full inventory somehow worked!");
assert_eq!(leftovers, TEST_ITEMS.clone()) assert_eq!(leftovers, TEST_ITEMS.clone())
} }
@ -44,7 +44,7 @@ fn push_unique_all_full() {
slots: TEST_ITEMS.iter().map(|a| Some(a.clone())).collect(), slots: TEST_ITEMS.iter().map(|a| Some(a.clone())).collect(),
amount: 0, amount: 0,
}; };
inv.push_all_unique(TEST_ITEMS.iter().map(|a| a.clone())) inv.push_all_unique(TEST_ITEMS.iter().cloned())
.expect("Pushing unique items into an inventory that already contains them didn't work!"); .expect("Pushing unique items into an inventory that already contains them didn't work!");
} }
@ -56,7 +56,7 @@ fn push_all_empty() {
slots: vec![None, None], slots: vec![None, None],
amount: 0, amount: 0,
}; };
inv.push_all(TEST_ITEMS.iter().map(|a| a.clone())) inv.push_all(TEST_ITEMS.iter().cloned())
.expect("Pushing items into an empty inventory didn't work!"); .expect("Pushing items into an empty inventory didn't work!");
} }
@ -68,8 +68,7 @@ fn push_all_unique_empty() {
slots: vec![None, None], slots: vec![None, None],
amount: 0, amount: 0,
}; };
inv.push_all_unique(TEST_ITEMS.iter().map(|a| a.clone())) inv.push_all_unique(TEST_ITEMS.iter().cloned()).expect(
.expect( "Pushing unique items into an empty inventory that didn't contain them didn't work!",
"Pushing unique items into an empty inventory that didn't contain them didn't work!", );
);
} }

View File

@ -36,7 +36,7 @@ impl From<&DotVoxData> for Segment {
if let Some(&color) = palette.get(voxel.i as usize) { if let Some(&color) = palette.get(voxel.i as usize) {
segment segment
.set( .set(
Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| i32::from(e)), Vec3::new(voxel.x, voxel.y, voxel.z).map(i32::from),
Cell::new(color), Cell::new(color),
) )
.unwrap(); .unwrap();
@ -195,7 +195,7 @@ impl MatSegment {
voxel.y, voxel.y,
voxel.z, voxel.z,
) )
.map(|e| i32::from(e)), .map(i32::from),
block, block,
) )
.unwrap(); .unwrap();

View File

@ -374,7 +374,7 @@ mod tests {
let mut server = postoffice.new_postboxes().next().unwrap(); let mut server = postoffice.new_postboxes().next().unwrap();
for msg in &test_msgs { for msg in &test_msgs {
client.send_message(msg.clone()); client.send_message(*msg);
} }
let mut recv_msgs = Vec::new(); let mut recv_msgs = Vec::new();

View File

@ -268,12 +268,7 @@ where
let satisfied = |pos: &Vec3<i32>| pos == &end; let satisfied = |pos: &Vec3<i32>| pos == &end;
let mut new_astar = match astar.take() { let mut new_astar = match astar.take() {
None => Astar::new( None => Astar::new(20_000, start, heuristic, DefaultHashBuilder::default()),
20_000,
start,
heuristic.clone(),
DefaultHashBuilder::default(),
),
Some(astar) => astar, Some(astar) => astar,
}; };

View File

@ -306,10 +306,8 @@ impl State {
// Apply terrain changes // Apply terrain changes
pub fn apply_terrain_changes(&self) { pub fn apply_terrain_changes(&self) {
let mut terrain = self.ecs.write_resource::<TerrainGrid>(); let mut terrain = self.ecs.write_resource::<TerrainGrid>();
let mut modified_blocks = std::mem::replace( let mut modified_blocks =
&mut self.ecs.write_resource::<BlockChange>().blocks, std::mem::take(&mut self.ecs.write_resource::<BlockChange>().blocks);
Default::default(),
);
// Apply block modifications // Apply block modifications
// Only include in `TerrainChanges` if successful // Only include in `TerrainChanges` if successful
modified_blocks.retain(|pos, block| terrain.set(*pos, *block).is_ok()); modified_blocks.retain(|pos, block| terrain.set(*pos, *block).is_ok());

View File

@ -54,9 +54,11 @@ impl CharacterBehavior for Data {
Climb::Up | Climb::Down => 8, Climb::Up | Climb::Down => 8,
Climb::Hold => 1, Climb::Hold => 1,
}; };
if let Err(_) = update
if update
.energy .energy
.try_change_by(-energy_use, EnergySource::Climb) .try_change_by(-energy_use, EnergySource::Climb)
.is_err()
{ {
update.character = CharacterState::Idle {}; update.character = CharacterState::Idle {};
} }

View File

@ -24,7 +24,7 @@ impl CharacterBehavior for Data {
} }
// If there is a wall in front of character go to climb // If there is a wall in front of character go to climb
if let Some(_) = data.physics.on_wall { if data.physics.on_wall.is_some() {
update.character = CharacterState::Climb; update.character = CharacterState::Climb;
return update; return update;
} }

View File

@ -128,13 +128,12 @@ impl CharacterBehavior for Data {
// Move player forward while in first third of each stage // Move player forward while in first third of each stage
if update.vel.0.magnitude_squared() < BASE_SPEED.powf(2.0) { if update.vel.0.magnitude_squared() < BASE_SPEED.powf(2.0) {
update.vel.0 = update.vel.0 update.vel.0 += data.dt.0
+ data.dt.0 * (if data.physics.on_ground {
* (if data.physics.on_ground { Vec3::new(0.0, 0.0, 500.0) // Jump upwards if on ground
Vec3::new(0.0, 0.0, 500.0) // Jump upwards if on ground } else {
} else { Vec3::one()
Vec3::one() } + adjusted_accel * Vec3::from(data.ori.0.xy()));
} + adjusted_accel * Vec3::from(data.ori.0.xy()));
let mag2 = update.vel.0.magnitude_squared(); let mag2 = update.vel.0.magnitude_squared();
if mag2 > BASE_SPEED.powf(2.0) { if mag2 > BASE_SPEED.powf(2.0) {
update.vel.0 = update.vel.0.normalized() * BASE_SPEED; update.vel.0 = update.vel.0.normalized() * BASE_SPEED;

View File

@ -88,13 +88,7 @@ impl<'a> System<'a> for Sys {
{ {
// Skip mounted entities // Skip mounted entities
if mount_state if mount_state
.map(|ms| { .map(|ms| *ms != MountState::Unmounted)
if let MountState::Unmounted = ms {
false
} else {
true
}
})
.unwrap_or(false) .unwrap_or(false)
{ {
continue; continue;

View File

@ -124,14 +124,14 @@ impl<'a> System<'a> for Sys {
} }
if rand::random() { if rand::random() {
healthchange = healthchange * 1.2; healthchange *= 1.2;
} }
// Block // Block
if character_b.is_block() if character_b.is_block()
&& ori_b.0.angle_between(pos.0 - pos_b.0) < BLOCK_ANGLE.to_radians() / 2.0 && ori_b.0.angle_between(pos.0 - pos_b.0) < BLOCK_ANGLE.to_radians() / 2.0
{ {
healthchange = healthchange * (1.0 - BLOCK_EFFICIENCY) healthchange *= 1.0 - BLOCK_EFFICIENCY
} }
server_emitter.emit(ServerEvent::Damage { server_emitter.emit(ServerEvent::Damage {

View File

@ -119,20 +119,18 @@ impl<'a> System<'a> for Sys {
projectile::Effect::Possess => { projectile::Effect::Possess => {
if other != projectile.owner.unwrap() { if other != projectile.owner.unwrap() {
if let Some(owner) = projectile.owner { if let Some(owner) = projectile.owner {
server_emitter.emit(ServerEvent::Possess(owner.into(), other)); server_emitter.emit(ServerEvent::Possess(owner, other));
} }
} }
}, },
_ => {}, _ => {},
} }
} }
} else { } else if let Some(dir) = velocities
if let Some(dir) = velocities .get(entity)
.get(entity) .and_then(|vel| vel.0.try_normalized())
.and_then(|vel| vel.0.try_normalized()) {
{ ori.0 = dir.into();
ori.0 = dir.into();
}
} }
if projectile.time_left == Duration::default() { if projectile.time_left == Duration::default() {

View File

@ -77,10 +77,12 @@ impl<'a> System<'a> for Sys {
// Accelerate recharging energy if not wielding. // Accelerate recharging energy if not wielding.
match character_state { match character_state {
CharacterState::Idle { .. } | CharacterState::Sit { .. } => { CharacterState::Idle { .. } | CharacterState::Sit { .. } => {
if { let res = {
let energy = energy.get_unchecked(); let energy = energy.get_unchecked();
energy.current() < energy.maximum() energy.current() < energy.maximum()
} { };
if res {
let mut energy = energy.get_mut_unchecked(); let mut energy = energy.get_mut_unchecked();
// Have to account for Calc I differential equations due to acceleration // Have to account for Calc I differential equations due to acceleration
energy.change_by( energy.change_by(

View File

@ -41,12 +41,7 @@ impl TerrainChunkMeta {
} }
} }
pub fn name(&self) -> &str { pub fn name(&self) -> &str { self.name.as_deref().unwrap_or("Wilderness") }
self.name
.as_ref()
.map(|s| s.as_str())
.unwrap_or("Wilderness")
}
pub fn biome(&self) -> BiomeKind { self.biome } pub fn biome(&self) -> BiomeKind { self.biome }
} }

View File

@ -53,8 +53,7 @@ pub struct Structure {
impl Structure { impl Structure {
pub fn load_group(specifier: &str) -> Vec<Arc<Structure>> { pub fn load_group(specifier: &str) -> Vec<Arc<Structure>> {
let spec = assets::load::<StructuresSpec>(&["world.manifests.", specifier].concat()); let spec = assets::load::<StructuresSpec>(&["world.manifests.", specifier].concat());
return spec spec.unwrap()
.unwrap()
.0 .0
.iter() .iter()
.map(|sp| { .map(|sp| {
@ -63,7 +62,7 @@ impl Structure {
}) })
.unwrap() .unwrap()
}) })
.collect(); .collect()
} }
pub fn with_center(mut self, center: Vec3<i32>) -> Self { pub fn with_center(mut self, center: Vec3<i32>) -> Self {
@ -145,10 +144,7 @@ impl Asset for Structure {
}, },
}; };
let _ = vol.set( let _ = vol.set(Vec3::new(voxel.x, voxel.y, voxel.z).map(i32::from), block);
Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| i32::from(e)),
block,
);
} }
Ok(Structure { Ok(Structure {

View File

@ -1,6 +1,7 @@
use vek::{Mat3, Rgb, Rgba, Vec3}; use vek::{Mat3, Rgb, Rgba, Vec3};
#[inline(always)] #[inline(always)]
#[allow(clippy::excessive_precision)]
pub fn srgb_to_linear(col: Rgb<f32>) -> Rgb<f32> { pub fn srgb_to_linear(col: Rgb<f32>) -> Rgb<f32> {
col.map(|c| { col.map(|c| {
if c <= 0.104 { if c <= 0.104 {
@ -12,6 +13,7 @@ pub fn srgb_to_linear(col: Rgb<f32>) -> Rgb<f32> {
} }
#[inline(always)] #[inline(always)]
#[allow(clippy::excessive_precision)]
pub fn linear_to_srgb(col: Rgb<f32>) -> Rgb<f32> { pub fn linear_to_srgb(col: Rgb<f32>) -> Rgb<f32> {
col.map(|c| { col.map(|c| {
if c <= 0.0060 { if c <= 0.0060 {
@ -37,6 +39,7 @@ pub fn linear_to_srgba(col: Rgba<f32>) -> Rgba<f32> {
/// Convert rgb to hsv. Expects rgb to be [0, 1]. /// Convert rgb to hsv. Expects rgb to be [0, 1].
#[inline(always)] #[inline(always)]
#[allow(clippy::many_single_char_names)]
pub fn rgb_to_hsv(rgb: Rgb<f32>) -> Vec3<f32> { pub fn rgb_to_hsv(rgb: Rgb<f32>) -> Vec3<f32> {
let (r, g, b) = rgb.into_tuple(); let (r, g, b) = rgb.into_tuple();
let (max, min, diff, add) = { let (max, min, diff, add) = {
@ -69,6 +72,7 @@ pub fn rgb_to_hsv(rgb: Rgb<f32>) -> Vec3<f32> {
/// Convert hsv to rgb. Expects h [0, 360], s [0, 1], v [0, 1] /// Convert hsv to rgb. Expects h [0, 360], s [0, 1], v [0, 1]
#[inline(always)] #[inline(always)]
#[allow(clippy::many_single_char_names)]
pub fn hsv_to_rgb(hsv: Vec3<f32>) -> Rgb<f32> { pub fn hsv_to_rgb(hsv: Vec3<f32>) -> Rgb<f32> {
let (h, s, v) = hsv.into_tuple(); let (h, s, v) = hsv.into_tuple();
let c = s * v; let c = s * v;

View File

@ -88,7 +88,7 @@ impl std::ops::Deref for Dir {
} }
impl From<Vec3<f32>> for Dir { impl From<Vec3<f32>> for Dir {
fn from(dir: Vec3<f32>) -> Self { Dir::new(dir.into()) } fn from(dir: Vec3<f32>) -> Self { Dir::new(dir) }
} }
/// Begone ye NaN's /// Begone ye NaN's
/// Slerp two `Vec3`s skipping the slerp if their directions are very close /// Slerp two `Vec3`s skipping the slerp if their directions are very close
@ -102,20 +102,25 @@ fn slerp_normalized(from: vek::Vec3<f32>, to: vek::Vec3<f32>, factor: f32) -> ve
// Ensure from is normalized // Ensure from is normalized
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
if { let unnormalized = {
let len_sq = from.magnitude_squared(); let len_sq = from.magnitude_squared();
len_sq < 0.999 || len_sq > 1.001 len_sq < 0.999 || len_sq > 1.001
} { };
if unnormalized {
panic!("Called slerp_normalized with unnormalized from: {:?}", from); panic!("Called slerp_normalized with unnormalized from: {:?}", from);
} }
} }
// Ensure to is normalized // Ensure to is normalized
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
if { let unnormalized = {
let len_sq = from.magnitude_squared(); let len_sq = from.magnitude_squared();
len_sq < 0.999 || len_sq > 1.001 len_sq < 0.999 || len_sq > 1.001
} { };
if unnormalized {
panic!("Called slerp_normalized with unnormalized to: {:?}", to); panic!("Called slerp_normalized with unnormalized to: {:?}", to);
} }
} }

View File

@ -4,8 +4,8 @@ mod dir;
pub const GIT_VERSION: &str = include_str!(concat!(env!("OUT_DIR"), "/githash")); pub const GIT_VERSION: &str = include_str!(concat!(env!("OUT_DIR"), "/githash"));
lazy_static::lazy_static! { lazy_static::lazy_static! {
pub static ref GIT_HASH: &'static str = GIT_VERSION.split("/").nth(0).expect("failed to retrieve git_hash!"); pub static ref GIT_HASH: &'static str = GIT_VERSION.split('/').nth(0).expect("failed to retrieve git_hash!");
pub static ref GIT_DATE: &'static str = GIT_VERSION.split("/").nth(1).expect("failed to retrieve git_date!"); pub static ref GIT_DATE: &'static str = GIT_VERSION.split('/').nth(1).expect("failed to retrieve git_date!");
} }
pub use color::*; pub use color::*;

View File

@ -269,6 +269,6 @@ impl<'a, T: ReadVol> Iterator for DefaultVolIterator<'a, T> {
return Some((pos, vox)); return Some((pos, vox));
} }
} }
return None; None
} }
} }