Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rand: Fix most clippy warnings #840

Merged
merged 28 commits into from Jul 25, 2019
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
dcfd356
Clippy: Whitelist a false positive about alignment
vks Jul 9, 2019
c2202a9
Remove useless annotation
vks Jul 9, 2019
3808dd2
Disable noisy clippy lints
vks Jul 9, 2019
74484bf
Clippy: Allow float comparisons
vks Jul 9, 2019
fef8f78
seq: Fix some minor clippy warnings
vks Jul 9, 2019
d74c603
Implement `IndexVec::is_empty`
vks Jul 9, 2019
4af5671
Fix a few minor clippy warnings
vks Jul 9, 2019
805d946
Replace some transmutes with safe code
vks Jul 9, 2019
ce583e0
Prefer `From` over `as`
vks Jul 9, 2019
047fc24
Uniform: Fix some clippy lints
vks Jul 9, 2019
8f8f836
Fix some minor clippy lints
vks Jul 9, 2019
553088f
Bernoulli: Fix some clippy lints
vks Jul 9, 2019
60107eb
Ignore clippy lints in deprecated code
vks Jul 9, 2019
6947154
rand_core: Fix clippy warnings
vks Jul 9, 2019
78c470e
rand_pcg: Fix clippy warnings
vks Jul 9, 2019
1c516eb
rand_pcg: Replace transmutes with safe code
vks Jul 9, 2019
183fadb
rand_core: Replace transmutes with safe code
vks Jul 9, 2019
80f3571
rand_xoshiro: Fix clippy warnings
vks Jul 9, 2019
b92db7c
rand_chacha: Replace transmute with safe code
vks Jul 9, 2019
1b40a2b
rand_xorshift: Fix clippy warnings
vks Jul 9, 2019
13fa09c
rand_distr: Prefer `Into` over `as`
vks Jul 9, 2019
bab3a37
rand_distr: Disable noisy clippy lints
vks Jul 9, 2019
a983df4
rand_distr: Disable some more noisy lints
vks Jul 9, 2019
4607c32
Dirichlet: Prefer iterators over index variables
vks Jul 9, 2019
6d79ebd
rand_distr: Fix remaining clippy warnings
vks Jul 9, 2019
1510b6c
Fix typo
vks Jul 22, 2019
cf1b67c
Don't reimplement `to_bits` and `from_bits` for floats
vks Jul 23, 2019
2d4a6ee
IndexVec: Inline most methods
vks Jul 25, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rand_chacha/src/chacha.rs
Expand Up @@ -79,7 +79,7 @@ macro_rules! chacha_impl {
fn generate(&mut self, r: &mut Self::Results) {
// Fill slice of words by writing to equivalent slice of bytes, then fixing endianness.
self.state.refill4($rounds, unsafe {
core::mem::transmute::<&mut Array64<u32>, &mut [u8; 256]>(&mut *r)
&mut *(&mut *r as *mut Array64<u32> as *mut [u8; 256])
});
for x in r.as_mut() {
*x = x.to_le();
Expand Down
7 changes: 5 additions & 2 deletions rand_core/src/block.rs
Expand Up @@ -188,6 +188,7 @@ where <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>
let read_u64 = |results: &[u32], index| {
if cfg!(any(target_endian = "little")) {
// requires little-endian CPU
#[allow(clippy::cast_ptr_alignment)] // false positive
let ptr: *const u64 = results[index..=index+1].as_ptr() as *const u64;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

results is aligned to 32bits, but then 64bits are read. I don't understand why this would be a false positive.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rust-lang/rust-clippy#2881

Guess what we do with the result: ptr::read_unaligned(ptr)

unsafe { ptr::read_unaligned(ptr) }
} else {
Expand Down Expand Up @@ -233,7 +234,8 @@ where <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>

#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is to appease a lint intended to catch accidental semicolons, so arguably a false positive.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I revert this? I think the new version is slightly more clear, but I don't have a strong preference.

}
}

Expand Down Expand Up @@ -408,7 +410,8 @@ where <R as BlockRngCore>::Results: AsRef<[u64]> + AsMut<[u64]>

#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
}
}

Expand Down
13 changes: 3 additions & 10 deletions rand_core/src/impls.rs
Expand Up @@ -17,7 +17,6 @@
//! to/from byte sequences, and since its purpose is reproducibility,
//! non-reproducible sources (e.g. `OsRng`) need not bother with it.

use core::intrinsics::transmute;
use core::ptr::copy_nonoverlapping;
use core::slice;
use core::cmp::min;
Expand All @@ -44,21 +43,15 @@ pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
while left.len() >= 8 {
let (l, r) = {left}.split_at_mut(8);
left = r;
let chunk: [u8; 8] = unsafe {
transmute(rng.next_u64().to_le())
};
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
l.copy_from_slice(&chunk);
}
let n = left.len();
if n > 4 {
let chunk: [u8; 8] = unsafe {
transmute(rng.next_u64().to_le())
};
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
} else if n > 0 {
let chunk: [u8; 4] = unsafe {
transmute(rng.next_u32().to_le())
};
let chunk: [u8; 4] = rng.next_u32().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
}
}
Expand Down
2 changes: 2 additions & 0 deletions rand_core/src/lib.rs
Expand Up @@ -35,6 +35,8 @@
#![deny(missing_debug_implementations)]
#![doc(test(attr(allow(unused_variables), deny(warnings))))]

#![allow(clippy::unreadable_literal)]

#![cfg_attr(not(feature="std"), no_std)]
#![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))]

Expand Down
1 change: 1 addition & 0 deletions rand_distr/src/binomial.rs
Expand Up @@ -65,6 +65,7 @@ fn f64_to_i64(x: f64) -> i64 {
}

impl Distribution<u64> for Binomial {
#[allow(clippy::many_single_char_names)] // Same names as in the reference.
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 {
// Handle these values directly.
if self.p == 0.0 {
Expand Down
3 changes: 1 addition & 2 deletions rand_distr/src/cauchy.rs
Expand Up @@ -66,8 +66,7 @@ where Standard: Distribution<N>
// note that π/2 is not exactly representable, even if x=0.5 the result is finite
let comp_dev = (N::pi() * x).tan();
// shift and scale according to parameters
let result = self.median + self.scale * comp_dev;
result
self.median + self.scale * comp_dev
}
}

Expand Down
16 changes: 8 additions & 8 deletions rand_distr/src/dirichlet.rs
Expand Up @@ -58,8 +58,8 @@ where StandardNormal: Distribution<N>, Exp1: Distribution<N>, Open01: Distributi
if a.len() < 2 {
return Err(Error::AlphaTooShort);
}
for i in 0..a.len() {
if !(a[i] > N::from(0.0)) {
for &ai in &a {
if !(ai > N::from(0.0)) {
dhardy marked this conversation as resolved.
Show resolved Hide resolved
return Err(Error::AlphaTooSmall);
}
}
Expand Down Expand Up @@ -92,14 +92,14 @@ where StandardNormal: Distribution<N>, Exp1: Distribution<N>, Open01: Distributi
let mut samples = vec![N::from(0.0); n];
let mut sum = N::from(0.0);

for i in 0..n {
let g = Gamma::new(self.alpha[i], N::from(1.0)).unwrap();
samples[i] = g.sample(rng);
sum += samples[i];
for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) {
let g = Gamma::new(a, N::from(1.0)).unwrap();
*s = g.sample(rng);
sum += *s;
}
let invacc = N::from(1.0) / sum;
for i in 0..n {
samples[i] *= invacc;
for s in samples.iter_mut() {
*s *= invacc;
}
samples
}
Expand Down
3 changes: 3 additions & 0 deletions rand_distr/src/lib.rs
Expand Up @@ -13,6 +13,9 @@
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]

#![allow(clippy::excessive_precision, clippy::float_cmp, clippy::unreadable_literal)]
#![allow(clippy::neg_cmp_op_on_partial_ord)] // suggested fix too verbose

//! Generating random samples from probability distributions.
//!
//! ## Re-exports
Expand Down
6 changes: 3 additions & 3 deletions rand_distr/src/utils.rs
Expand Up @@ -88,9 +88,9 @@ impl Float for f32 {
fn tan(self) -> Self { self.tan() }
#[inline]
fn log_gamma(self) -> Self {
let result = log_gamma(self as f64);
assert!(result <= ::core::f32::MAX as f64);
assert!(result >= ::core::f32::MIN as f64);
let result = log_gamma(self.into());
assert!(result <= ::core::f32::MAX.into());
assert!(result >= ::core::f32::MIN.into());
result as f32
}
}
Expand Down
2 changes: 2 additions & 0 deletions rand_pcg/src/lib.rs
Expand Up @@ -35,6 +35,8 @@
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]

#![allow(clippy::unreadable_literal)]

#![no_std]

mod pcg64;
Expand Down
23 changes: 10 additions & 13 deletions rand_pcg/src/pcg128.rs
Expand Up @@ -14,7 +14,6 @@
const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645;

use core::fmt;
use core::mem::transmute;
use rand_core::{RngCore, SeedableRng, Error, le};
#[cfg(feature="serde1")] use serde::{Serialize, Deserialize};

Expand Down Expand Up @@ -86,8 +85,8 @@ impl SeedableRng for Lcg128Xsl64 {
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u64 = [0u64; 4];
le::read_u64_into(&seed, &mut seed_u64);
let state = (seed_u64[0] as u128) | ((seed_u64[1] as u128) << 64);
let incr = (seed_u64[2] as u128) | ((seed_u64[3] as u128) << 64);
let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64);
let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64);

// The increment must be odd, hence we discard one bit:
Lcg128Xsl64::from_state_incr(state, incr | 1)
Expand All @@ -113,7 +112,8 @@ impl RngCore for Lcg128Xsl64 {

#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
}
}

Expand Down Expand Up @@ -166,8 +166,8 @@ impl SeedableRng for Mcg128Xsl64 {
// Read as if a little-endian u128 value:
let mut seed_u64 = [0u64; 2];
le::read_u64_into(&seed, &mut seed_u64);
let state = (seed_u64[0] as u128) |
(seed_u64[1] as u128) << 64;
let state = u128::from(seed_u64[0]) |
u128::from(seed_u64[1]) << 64;
Mcg128Xsl64::new(state)
}
}
Expand All @@ -191,7 +191,8 @@ impl RngCore for Mcg128Xsl64 {

#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
}
}

Expand All @@ -213,16 +214,12 @@ fn fill_bytes_impl<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
while left.len() >= 8 {
let (l, r) = {left}.split_at_mut(8);
left = r;
let chunk: [u8; 8] = unsafe {
transmute(rng.next_u64().to_le())
};
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
l.copy_from_slice(&chunk);
}
let n = left.len();
if n > 0 {
let chunk: [u8; 8] = unsafe {
transmute(rng.next_u64().to_le())
};
let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
left.copy_from_slice(&chunk[..n]);
}
}
3 changes: 2 additions & 1 deletion rand_pcg/src/pcg64.rs
Expand Up @@ -121,6 +121,7 @@ impl RngCore for Lcg64Xsh32 {

#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
}
}
3 changes: 2 additions & 1 deletion rand_xorshift/src/lib.rs
Expand Up @@ -71,7 +71,8 @@ impl RngCore for XorShiftRng {
}

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
self.fill_bytes(dest);
Ok(())
}
}

Expand Down
2 changes: 1 addition & 1 deletion rand_xoshiro/src/lib.rs
Expand Up @@ -62,7 +62,7 @@

#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))]
#![allow(clippy::unreadable_literal)]
#![no_std]

#[macro_use]
Expand Down
4 changes: 2 additions & 2 deletions src/distributions/bernoulli.rs
Expand Up @@ -96,13 +96,13 @@ impl Bernoulli {
/// return `true`. If `numerator == 0` it will always return `false`.
#[inline]
pub fn from_ratio(numerator: u32, denominator: u32) -> Result<Bernoulli, BernoulliError> {
if !(numerator <= denominator) {
if numerator > denominator {
return Err(BernoulliError::InvalidProbability);
}
if numerator == denominator {
return Ok(Bernoulli { p_int: ALWAYS_TRUE })
}
let p_int = ((numerator as f64 / denominator as f64) * SCALE) as u64;
let p_int = ((f64::from(numerator) / f64::from(denominator)) * SCALE) as u64;
Ok(Bernoulli { p_int })
}
}
Expand Down
1 change: 1 addition & 0 deletions src/distributions/binomial.rs
Expand Up @@ -9,6 +9,7 @@

//! The binomial distribution.
#![allow(deprecated)]
#![allow(clippy::all)]

use crate::Rng;
use crate::distributions::{Distribution, Uniform};
Expand Down
1 change: 1 addition & 0 deletions src/distributions/cauchy.rs
Expand Up @@ -9,6 +9,7 @@

//! The Cauchy distribution.
#![allow(deprecated)]
#![allow(clippy::all)]

use crate::Rng;
use crate::distributions::Distribution;
Expand Down
1 change: 1 addition & 0 deletions src/distributions/dirichlet.rs
Expand Up @@ -9,6 +9,7 @@

//! The dirichlet distribution.
#![allow(deprecated)]
#![allow(clippy::all)]

use crate::Rng;
use crate::distributions::Distribution;
Expand Down
4 changes: 1 addition & 3 deletions src/distributions/float.rs
Expand Up @@ -95,9 +95,7 @@ macro_rules! float_impls {
// The exponent is encoded using an offset-binary representation
let exponent_bits: $u_scalar =
(($exponent_bias + exponent) as $u_scalar) << $fraction_bits;
// TODO: use from_bits when min compiler > 1.25 (see #545)
// $ty::from_bits(self | exponent_bits)
unsafe{ mem::transmute(self | exponent_bits) }
$ty::from_bits(self | exponent_bits)
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/distributions/integer.rs
Expand Up @@ -52,8 +52,8 @@ impl Distribution<u128> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u128 {
// Use LE; we explicitly generate one value before the next.
let x = rng.next_u64() as u128;
let y = rng.next_u64() as u128;
let x = u128::from(rng.next_u64());
let y = u128::from(rng.next_u64());
(y << 64) | x
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/distributions/mod.rs
Expand Up @@ -213,7 +213,7 @@ pub trait Distribution<T> {
{
DistIter {
distr: self,
rng: rng,
rng,
phantom: ::core::marker::PhantomData,
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/distributions/other.rs
Expand Up @@ -11,7 +11,7 @@
use core::char;
use core::num::Wrapping;

use crate::{Rng};
use crate::Rng;
use crate::distributions::{Distribution, Standard, Uniform};

// ----- Sampling distributions -----
Expand Down Expand Up @@ -116,6 +116,7 @@ macro_rules! tuple_impl {
}

impl Distribution<()> for Standard {
#[allow(clippy::unused_unit)]
#[inline]
fn sample<R: Rng + ?Sized>(&self, _: &mut R) -> () { () }
}
Expand Down
10 changes: 5 additions & 5 deletions src/distributions/uniform.rs
Expand Up @@ -380,7 +380,7 @@ macro_rules! uniform_int_impl {
let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned;
let ints_to_reject =
if range > 0 {
let range = range as $u_large;
let range = $u_large::from(range);
(unsigned_max - range + 1) % range
} else {
0
Expand Down Expand Up @@ -865,8 +865,8 @@ impl UniformSampler for UniformDuration {
let mut high_n = high.subsec_nanos();

if high_n < low_n {
high_s = high_s - 1;
high_n = high_n + 1_000_000_000;
high_s -= 1;
high_n += 1_000_000_000;
}

let mode = if low_s == high_s {
Expand All @@ -877,10 +877,10 @@ impl UniformSampler for UniformDuration {
} else {
let max = high_s
.checked_mul(1_000_000_000)
.and_then(|n| n.checked_add(high_n as u64));
.and_then(|n| n.checked_add(u64::from(high_n)));

if let Some(higher_bound) = max {
let lower_bound = low_s * 1_000_000_000 + low_n as u64;
let lower_bound = low_s * 1_000_000_000 + u64::from(low_n);
UniformDurationMode::Medium {
nanos: Uniform::new_inclusive(lower_bound, higher_bound),
}
Expand Down
1 change: 1 addition & 0 deletions src/distributions/unit_circle.rs
Expand Up @@ -7,6 +7,7 @@
// except according to those terms.

#![allow(deprecated)]
#![allow(clippy::all)]

use crate::Rng;
use crate::distributions::{Distribution, Uniform};
Expand Down
1 change: 1 addition & 0 deletions src/distributions/unit_sphere.rs
Expand Up @@ -7,6 +7,7 @@
// except according to those terms.

#![allow(deprecated)]
#![allow(clippy::all)]

use crate::Rng;
use crate::distributions::{Distribution, Uniform};
Expand Down