Add various fixes to clippy lints

Thou shalt appease clippy
This commit is contained in:
Paul Hauner 2019-06-10 11:01:25 -04:00
parent a9284bec18
commit e550c0218f
No known key found for this signature in database
GPG Key ID: 303E4494BB28068C
37 changed files with 72 additions and 82 deletions

View File

@ -216,9 +216,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
.iter()
.map(|root| match self.get_block(root)? {
Some(block) => Ok(block.body),
None => Err(Error::DBInconsistent(
format!("Missing block: {}", root).into(),
)),
None => Err(Error::DBInconsistent(format!("Missing block: {}", root))),
})
.collect();

View File

@ -57,7 +57,7 @@ impl<T: EthSpec, U: Store> Iterator for BlockRootsIterator<T, U> {
return None;
}
self.slot = self.slot - 1;
self.slot -= 1;
match self.beacon_state.get_block_root(self.slot) {
Ok(root) => Some(*root),
@ -73,7 +73,7 @@ impl<T: EthSpec, U: Store> Iterator for BlockRootsIterator<T, U> {
self.beacon_state.get_block_root(self.slot).ok().cloned()
}
_ => return None,
_ => None,
}
}
}

View File

@ -57,12 +57,12 @@ impl Config {
pub fn apply_cli_args(&mut self, args: &ArgMatches) -> Result<(), &'static str> {
if let Some(listen_address_str) = args.value_of("listen-address") {
let listen_addresses = listen_address_str.split(",").map(Into::into).collect();
let listen_addresses = listen_address_str.split(',').map(Into::into).collect();
self.listen_addresses = listen_addresses;
}
if let Some(boot_addresses_str) = args.value_of("boot-nodes") {
let boot_addresses = boot_addresses_str.split(",").map(Into::into).collect();
let boot_addresses = boot_addresses_str.split(',').map(Into::into).collect();
self.boot_nodes = boot_addresses;
}

View File

@ -42,7 +42,7 @@ impl RequestId {
}
/// Return the previous id.
pub fn previous(&self) -> Self {
pub fn previous(self) -> Self {
Self(self.0 - 1)
}
}
@ -220,7 +220,7 @@ impl Encode for RPCEvent {
} => SszContainer {
is_request: true,
id: (*id).into(),
other: (*method_id).into(),
other: *method_id,
bytes: match body {
RPCRequest::Hello(body) => body.as_ssz_bytes(),
RPCRequest::Goodbye(body) => body.as_ssz_bytes(),
@ -237,7 +237,7 @@ impl Encode for RPCEvent {
} => SszContainer {
is_request: false,
id: (*id).into(),
other: (*method_id).into(),
other: *method_id,
bytes: match result {
RPCResponse::Hello(response) => response.as_ssz_bytes(),
RPCResponse::BeaconBlockRoots(response) => response.as_ssz_bytes(),

View File

@ -155,7 +155,7 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
if self
.network_context
.outstanding_outgoing_request_ids
.remove(&(peer_id.clone(), id.clone()))
.remove(&(peer_id.clone(), id))
.is_none()
{
warn!(
@ -250,7 +250,7 @@ impl NetworkContext {
let id = self.generate_request_id(&peer_id);
self.outstanding_outgoing_request_ids
.insert((peer_id.clone(), id.clone()), Instant::now());
.insert((peer_id.clone(), id), Instant::now());
self.send_rpc_event(
peer_id,

View File

@ -57,7 +57,7 @@ fn get_chain_of_blocks<T: EthSpec, U: Store>(
) -> Vec<(Hash256, BeaconBlock)> {
let spec = T::default_spec();
let mut blocks_and_roots: Vec<(Hash256, BeaconBlock)> = vec![];
let mut unique_hashes = (0..).into_iter().map(|i| Hash256::from(i));
let mut unique_hashes = (0..).map(Hash256::from);
let mut random_block = BeaconBlock::random_for_test(&mut XorShiftRng::from_seed([42; 16]));
random_block.previous_block_root = Hash256::zero();
let beacon_state = get_state::<T>(validator_count);

View File

@ -49,7 +49,7 @@ fn verify_indexed_attestation_parametric<T: EthSpec>(
);
// Check that nobody signed with custody bit 1 (to be removed in phase 1)
if custody_bit_1_indices.len() > 0 {
if !custody_bit_1_indices.is_empty() {
invalid!(Invalid::CustodyBitfieldHasSetBits);
}
@ -96,7 +96,7 @@ where
state
.validator_registry
.get(validator_idx as usize)
.ok_or(Error::Invalid(Invalid::UnknownValidator(validator_idx)))
.ok_or_else(|| Error::Invalid(Invalid::UnknownValidator(validator_idx)))
.map(|validator| {
aggregate_pubkey.add(&validator.pubkey);
aggregate_pubkey

View File

@ -156,7 +156,7 @@ pub fn process_crosslinks<T: EthSpec>(
state.previous_crosslinks = state.current_crosslinks.clone();
for relative_epoch in vec![RelativeEpoch::Previous, RelativeEpoch::Current] {
for &relative_epoch in &[RelativeEpoch::Previous, RelativeEpoch::Current] {
let epoch = relative_epoch.into_epoch(state.current_epoch());
for offset in 0..state.get_epoch_committee_count(relative_epoch)? {
let shard =

View File

@ -422,7 +422,7 @@ impl<T: EthSpec> BeaconState<T> {
};
let effective_balance = self.validator_registry[candidate_index].effective_balance;
if (effective_balance * MAX_RANDOM_BYTE)
>= (spec.max_effective_balance * random_byte as u64)
>= (spec.max_effective_balance * u64::from(random_byte))
{
break candidate_index;
}

View File

@ -162,7 +162,6 @@ impl CommitteeCache {
let i = self.shuffled_position(validator_index)?;
(0..self.committee_count)
.into_iter()
.map(|nth_committee| (nth_committee, self.compute_committee_range(nth_committee)))
.find(|(_, range)| {
if let Some(range) = range {

View File

@ -174,7 +174,7 @@ impl ChainSpec {
/*
* Time parameters
*/
genesis_time: u32::max_value() as u64,
genesis_time: u64::from(u32::max_value()),
seconds_per_slot: 6,
min_attestation_inclusion_delay: 4,
min_seed_lookahead: Epoch::new(1),

View File

@ -77,7 +77,7 @@ impl Epoch {
/// Position of some slot inside an epoch, if any.
///
/// E.g., the first `slot` in `epoch` is at position `0`.
pub fn position(&self, slot: Slot, slots_per_epoch: u64) -> Option<usize> {
pub fn position(self, slot: Slot, slots_per_epoch: u64) -> Option<usize> {
let start = self.start_slot(slots_per_epoch);
let end = self.end_slot(slots_per_epoch);

View File

@ -271,7 +271,7 @@ fn build_proposer_slashing<T: EthSpec>(
Signature::new(message, domain, secret_key)
};
TestingProposerSlashingBuilder::double_vote::<T, _>(validator_index, signer, spec)
TestingProposerSlashingBuilder::double_vote::<T, _>(validator_index, signer)
}
/// Builds an `AttesterSlashing` for some `validator_indices`.

View File

@ -17,7 +17,7 @@ impl TestingProposerSlashingBuilder {
/// - `domain: Domain`
///
/// Where domain is a domain "constant" (e.g., `spec.domain_attestation`).
pub fn double_vote<T, F>(proposer_index: u64, signer: F, spec: &ChainSpec) -> ProposerSlashing
pub fn double_vote<T, F>(proposer_index: u64, signer: F) -> ProposerSlashing
where
T: EthSpec,
F: Fn(u64, &[u8], Epoch, Domain) -> Signature,

View File

@ -13,6 +13,7 @@ where
u8::from_str_radix(&s.as_str()[2..], 16).map_err(D::Error::custom)
}
#[allow(clippy::trivially_copy_pass_by_ref)] // Serde requires the `byte` to be a ref.
pub fn u8_to_hex_str<S>(byte: &u8, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,

View File

@ -80,7 +80,7 @@ where
)
})?;
file.write_all(toml_encoded.as_bytes())
.expect(&format!("Unable to write to {:?}", path));
.unwrap_or_else(|_| panic!("Unable to write to {:?}", path));
}
Ok(())

View File

@ -28,13 +28,10 @@ pub fn compare_beacon_state_results_without_caches<T: EthSpec, E: Debug>(
result: &mut Result<BeaconState<T>, E>,
expected: &mut Option<BeaconState<T>>,
) -> Result<(), Error> {
match (result.as_mut(), expected.as_mut()) {
(Ok(ref mut result), Some(ref mut expected)) => {
result.drop_all_caches();
expected.drop_all_caches();
}
_ => (),
};
if let (Ok(ref mut result), Some(ref mut expected)) = (result.as_mut(), expected.as_mut()) {
result.drop_all_caches();
expected.drop_all_caches();
}
compare_result_detailed(&result, &expected)
}

View File

@ -70,7 +70,7 @@ where
impl<T: YamlDecode> YamlDecode for Cases<T> {
/// Decodes a YAML list of test cases
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
let mut p = 0;
let mut elems: Vec<&str> = yaml
.match_indices("\n- ")

View File

@ -10,8 +10,8 @@ pub struct BlsAggregatePubkeys {
}
impl YamlDecode for BlsAggregatePubkeys {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -10,8 +10,8 @@ pub struct BlsAggregateSigs {
}
impl YamlDecode for BlsAggregateSigs {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -16,8 +16,8 @@ pub struct BlsG2Compressed {
}
impl YamlDecode for BlsG2Compressed {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}
@ -46,13 +46,13 @@ impl Case for BlsG2Compressed {
}
// Converts a vector to u64 (from big endian)
fn bytes_to_u64(array: &Vec<u8>) -> u64 {
fn bytes_to_u64(array: &[u8]) -> u64 {
let mut result: u64 = 0;
for (i, value) in array.iter().rev().enumerate() {
if i == 8 {
break;
}
result += u64::pow(2, i as u32 * 8) * (*value as u64);
result += u64::pow(2, i as u32 * 8) * u64::from(*value);
}
result
}

View File

@ -16,8 +16,8 @@ pub struct BlsG2Uncompressed {
}
impl YamlDecode for BlsG2Uncompressed {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}
@ -56,13 +56,13 @@ impl Case for BlsG2Uncompressed {
}
// Converts a vector to u64 (from big endian)
fn bytes_to_u64(array: &Vec<u8>) -> u64 {
fn bytes_to_u64(array: &[u8]) -> u64 {
let mut result: u64 = 0;
for (i, value) in array.iter().rev().enumerate() {
if i == 8 {
break;
}
result += u64::pow(2, i as u32 * 8) * (*value as u64);
result += u64::pow(2, i as u32 * 8) * u64::from(*value);
}
result
}

View File

@ -10,8 +10,8 @@ pub struct BlsPrivToPub {
}
impl YamlDecode for BlsPrivToPub {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -17,8 +17,8 @@ pub struct BlsSign {
}
impl YamlDecode for BlsSign {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}
@ -46,13 +46,13 @@ impl Case for BlsSign {
}
// Converts a vector to u64 (from big endian)
fn bytes_to_u64(array: &Vec<u8>) -> u64 {
fn bytes_to_u64(array: &[u8]) -> u64 {
let mut result: u64 = 0;
for (i, value) in array.iter().rev().enumerate() {
if i == 8 {
break;
}
result += u64::pow(2, i as u32 * 8) * (*value as u64);
result += u64::pow(2, i as u32 * 8) * u64::from(*value);
}
result
}

View File

@ -14,8 +14,8 @@ pub struct EpochProcessingCrosslinks<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for EpochProcessingCrosslinks<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -14,8 +14,8 @@ pub struct EpochProcessingRegistryUpdates<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for EpochProcessingRegistryUpdates<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -15,8 +15,8 @@ pub struct OperationsAttesterSlashing<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for OperationsAttesterSlashing<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -16,8 +16,8 @@ pub struct OperationsDeposit<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for OperationsDeposit<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -15,8 +15,8 @@ pub struct OperationsExit<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for OperationsExit<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -15,8 +15,8 @@ pub struct OperationsProposerSlashing<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for OperationsProposerSlashing<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -15,8 +15,8 @@ pub struct OperationsTransfer<E: EthSpec> {
}
impl<E: EthSpec> YamlDecode for OperationsTransfer<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}

View File

@ -14,8 +14,8 @@ pub struct Shuffling<T> {
}
impl<T> YamlDecode for Shuffling<T> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}
@ -30,7 +30,6 @@ impl<T: EthSpec> Case for Shuffling<T> {
// Test get_permuted_index
let shuffling = (0..self.count)
.into_iter()
.map(|i| {
get_permutated_index(i, self.count, &seed, spec.shuffle_round_count).unwrap()
})

View File

@ -15,8 +15,8 @@ pub struct SszGeneric {
}
impl YamlDecode for SszGeneric {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
Ok(serde_yaml::from_str(&yaml.as_str()).unwrap())
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
Ok(serde_yaml::from_str(yaml).unwrap())
}
}
@ -45,11 +45,7 @@ impl Case for SszGeneric {
}
/// Execute a `ssz_generic` test case.
fn ssz_generic_test<T>(
should_be_ok: bool,
ssz: &String,
value: &Option<String>,
) -> Result<(), Error>
fn ssz_generic_test<T>(should_be_ok: bool, ssz: &str, value: &Option<String>) -> Result<(), Error>
where
T: Decode + YamlDecode + Debug + PartialEq<T>,
{

View File

@ -55,7 +55,7 @@ where
}
impl<E: EthSpec + serde::de::DeserializeOwned> YamlDecode for SszStatic<E> {
fn yaml_decode(yaml: &String) -> Result<Self, Error> {
fn yaml_decode(yaml: &str) -> Result<Self, Error> {
serde_yaml::from_str(yaml).map_err(|e| Error::FailedToParseTest(format!("{:?}", e)))
}
}

View File

@ -136,14 +136,14 @@ pub fn print_failures(doc: &Doc, results: &[CaseResult]) {
println!("Test Failure");
println!("Title: {}", header.title);
println!("File: {:?}", doc.path);
println!("");
println!();
println!(
"{} tests, {} failures, {} passes.",
results.len(),
failures.len(),
results.len() - failures.len()
);
println!("");
println!();
for failure in failures {
let error = failure.result.clone().unwrap_err();
@ -157,5 +157,5 @@ pub fn print_failures(doc: &Doc, results: &[CaseResult]) {
);
println!("{}", error.message());
}
println!("");
println!();
}

View File

@ -8,14 +8,14 @@ pub use utils::*;
pub trait YamlDecode: Sized {
/// Decode an object from the test specification YAML.
fn yaml_decode(string: &String) -> Result<Self, Error>;
fn yaml_decode(string: &str) -> Result<Self, Error>;
}
/// Basic types can general be decoded with the `parse` fn if they implement `str::FromStr`.
macro_rules! impl_via_parse {
($ty: ty) => {
impl YamlDecode for $ty {
fn yaml_decode(string: &String) -> Result<Self, Error> {
fn yaml_decode(string: &str) -> Result<Self, Error> {
string
.parse::<Self>()
.map_err(|e| Error::FailedToParseTest(format!("{:?}", e)))
@ -34,7 +34,7 @@ impl_via_parse!(u64);
macro_rules! impl_via_from_dec_str {
($ty: ty) => {
impl YamlDecode for $ty {
fn yaml_decode(string: &String) -> Result<Self, Error> {
fn yaml_decode(string: &str) -> Result<Self, Error> {
Self::from_dec_str(string).map_err(|e| Error::FailedToParseTest(format!("{:?}", e)))
}
}
@ -48,7 +48,7 @@ impl_via_from_dec_str!(U256);
macro_rules! impl_via_serde_yaml {
($ty: ty) => {
impl YamlDecode for $ty {
fn yaml_decode(string: &String) -> Result<Self, Error> {
fn yaml_decode(string: &str) -> Result<Self, Error> {
serde_yaml::from_str(string)
.map_err(|e| Error::FailedToParseTest(format!("{:?}", e)))
}

View File

@ -3,7 +3,7 @@ pub fn yaml_split_header_and_cases(mut yaml: String) -> (String, String) {
// + 1 to skip the \n we used for matching.
let mut test_cases = yaml.split_off(test_cases_start + 1);
let end_of_first_line = test_cases.find("\n").unwrap();
let end_of_first_line = test_cases.find('\n').unwrap();
let test_cases = test_cases.split_off(end_of_first_line + 1);
(yaml, test_cases)