Merge branch 'xvar/clippy-fixes' into 'master'

Initial clippy fixes as discussed in #587

See merge request veloren/veloren!1054
This commit is contained in:
Marcel 2020-06-08 21:10:12 +00:00
commit 11462776db
23 changed files with 70 additions and 84 deletions

View File

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

View File

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

View File

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

View File

@ -150,7 +150,7 @@ impl SpeechBubble {
{
match &self.message {
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();
if leftovers.len() > 0 {
if !leftovers.is_empty() {
Err(Error::Full(leftovers))
} else {
Ok(())
@ -187,7 +187,7 @@ impl Inventory {
self.push(item).map(|overflow| leftovers.push(overflow));
} // else drop item if it was already in
}
if leftovers.len() > 0 {
if !leftovers.is_empty() {
Err(Error::Full(leftovers))
} else {
Ok(())

View File

@ -31,7 +31,7 @@ fn push_all_full() {
amount: 0,
};
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!");
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(),
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!");
}
@ -56,7 +56,7 @@ fn push_all_empty() {
slots: vec![None, None],
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!");
}
@ -68,8 +68,7 @@ fn push_all_unique_empty() {
slots: vec![None, None],
amount: 0,
};
inv.push_all_unique(TEST_ITEMS.iter().map(|a| a.clone()))
.expect(
"Pushing unique items into an empty inventory that didn't contain them didn't work!",
);
inv.push_all_unique(TEST_ITEMS.iter().cloned()).expect(
"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) {
segment
.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),
)
.unwrap();
@ -195,7 +195,7 @@ impl MatSegment {
voxel.y,
voxel.z,
)
.map(|e| i32::from(e)),
.map(i32::from),
block,
)
.unwrap();

View File

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

View File

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

View File

@ -306,10 +306,8 @@ impl State {
// Apply terrain changes
pub fn apply_terrain_changes(&self) {
let mut terrain = self.ecs.write_resource::<TerrainGrid>();
let mut modified_blocks = std::mem::replace(
&mut self.ecs.write_resource::<BlockChange>().blocks,
Default::default(),
);
let mut modified_blocks =
std::mem::take(&mut self.ecs.write_resource::<BlockChange>().blocks);
// Apply block modifications
// Only include in `TerrainChanges` if successful
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::Hold => 1,
};
if let Err(_) = update
if update
.energy
.try_change_by(-energy_use, EnergySource::Climb)
.is_err()
{
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 let Some(_) = data.physics.on_wall {
if data.physics.on_wall.is_some() {
update.character = CharacterState::Climb;
return update;
}

View File

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

View File

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

View File

@ -124,14 +124,14 @@ impl<'a> System<'a> for Sys {
}
if rand::random() {
healthchange = healthchange * 1.2;
healthchange *= 1.2;
}
// Block
if character_b.is_block()
&& 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 {

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
use vek::{Mat3, Rgb, Rgba, Vec3};
#[inline(always)]
#[allow(clippy::excessive_precision)]
pub fn srgb_to_linear(col: Rgb<f32>) -> Rgb<f32> {
col.map(|c| {
if c <= 0.104 {
@ -12,6 +13,7 @@ pub fn srgb_to_linear(col: Rgb<f32>) -> Rgb<f32> {
}
#[inline(always)]
#[allow(clippy::excessive_precision)]
pub fn linear_to_srgb(col: Rgb<f32>) -> Rgb<f32> {
col.map(|c| {
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].
#[inline(always)]
#[allow(clippy::many_single_char_names)]
pub fn rgb_to_hsv(rgb: Rgb<f32>) -> Vec3<f32> {
let (r, g, b) = rgb.into_tuple();
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]
#[inline(always)]
#[allow(clippy::many_single_char_names)]
pub fn hsv_to_rgb(hsv: Vec3<f32>) -> Rgb<f32> {
let (h, s, v) = hsv.into_tuple();
let c = s * v;

View File

@ -88,7 +88,7 @@ impl std::ops::Deref 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
/// 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
#[cfg(debug_assertions)]
{
if {
let unnormalized = {
let len_sq = from.magnitude_squared();
len_sq < 0.999 || len_sq > 1.001
} {
};
if unnormalized {
panic!("Called slerp_normalized with unnormalized from: {:?}", from);
}
}
// Ensure to is normalized
#[cfg(debug_assertions)]
{
if {
let unnormalized = {
let len_sq = from.magnitude_squared();
len_sq < 0.999 || len_sq > 1.001
} {
};
if unnormalized {
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"));
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_DATE: &'static str = GIT_VERSION.split("/").nth(1).expect("failed to retrieve git_date!");
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 use color::*;

View File

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