[clippy] Fix clippy issues for crate sp-core (#8809)

* Fix clippy issues for crate sp-core

* Update primitives/core/benches/bench.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update primitives/core/src/ed25519.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Remove clippy attributes

* Missed a clippy attribute

* remove clippy attributes for bechmarks as well

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Andreas Doerr
2021-05-18 09:38:56 +02:00
committed by GitHub
parent 72a2ad4f4f
commit a68ed7c3d8
12 changed files with 62 additions and 58 deletions
@@ -226,7 +226,7 @@ mod tests {
#[test]
fn is_digest_build_required_at_block_works() {
fn test_with_zero(zero: u64) {
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 0u64));
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero));
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 1u64));
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 2u64));
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 4u64));
@@ -249,7 +249,7 @@ mod tests {
#[test]
fn digest_level_at_block_works() {
fn test_with_zero(zero: u64) {
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 0u64), None);
assert_eq!(config(8, 4).digest_level_at_block(zero, zero), None);
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 7u64), None);
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 63u64), None);
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 8u64), Some((1, 8, 1)));
+11 -11
View File
@@ -174,8 +174,8 @@ impl DeriveJunction {
impl<T: AsRef<str>> From<T> for DeriveJunction {
fn from(j: T) -> DeriveJunction {
let j = j.as_ref();
let (code, hard) = if j.starts_with('/') {
(&j[1..], true)
let (code, hard) = if let Some(stripped) = j.strip_prefix('/') {
(stripped, true)
} else {
(j, false)
};
@@ -262,7 +262,7 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default {
let upper = data[1] & 0b00111111;
(2, (lower as u16) | ((upper as u16) << 8))
}
_ => Err(PublicError::UnknownVersion)?,
_ => return Err(PublicError::UnknownVersion),
};
if data.len() != prefix_len + body_len + CHECKSUM_LEN { return Err(PublicError::BadLength) }
let format = ident.try_into().map_err(|_: ()| PublicError::UnknownVersion)?;
@@ -294,15 +294,15 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default {
#[cfg(feature = "std")]
fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String {
// We mask out the upper two bits of the ident - SS58 Prefix currently only supports 14-bits
let ident: u16 = u16::from(version) & 0b00111111_11111111;
let ident: u16 = u16::from(version) & 0b0011_1111_1111_1111;
let mut v = match ident {
0..=63 => vec![ident as u8],
64..=16_383 => {
// upper six bits of the lower byte(!)
let first = ((ident & 0b00000000_11111100) as u8) >> 2;
let first = ((ident & 0b0000_0000_1111_1100) as u8) >> 2;
// lower two bits of the lower byte in the high pos,
// lower bits of the upper byte in the low pos
let second = ((ident >> 8) as u8) | ((ident & 0b00000000_00000011) as u8) << 6;
let second = ((ident >> 8) as u8) | ((ident & 0b0000_0000_0000_0011) as u8) << 6;
vec![first | 0b01000000, second]
}
_ => unreachable!("masked out the upper two bits; qed"),
@@ -612,14 +612,14 @@ impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Default + Derive> Ss58Codec for T {
let s = cap.name("ss58")
.map(|r| r.as_str())
.unwrap_or(DEV_ADDRESS);
let addr = if s.starts_with("0x") {
let d = hex::decode(&s[2..]).map_err(|_| PublicError::InvalidFormat)?;
let addr = if let Some(stripped) = s.strip_prefix("0x") {
let d = hex::decode(stripped).map_err(|_| PublicError::InvalidFormat)?;
let mut r = Self::default();
if d.len() == r.as_ref().len() {
r.as_mut().copy_from_slice(&d);
r
} else {
Err(PublicError::BadLength)?
return Err(PublicError::BadLength)
}
} else {
Self::from_ss58check(s)?
@@ -1009,8 +1009,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static {
let phrase = cap.name("phrase").map(|r| r.as_str()).unwrap_or(DEV_PHRASE);
let password = password_override.or_else(|| cap.name("password").map(|m| m.as_str()));
let (root, seed) = if phrase.starts_with("0x") {
hex::decode(&phrase[2..]).ok()
let (root, seed) = if let Some(stripped) = phrase.strip_prefix("0x") {
hex::decode(stripped).ok()
.and_then(|seed_vec| {
let mut seed = Self::Seed::default();
if seed.as_ref().len() == seed_vec.len() {
+6 -6
View File
@@ -256,8 +256,8 @@ impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
Ok(Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))
}
}
@@ -453,7 +453,7 @@ impl TraitPair for Pair {
let secret = SecretKey::parse_slice(seed_slice)
.map_err(|_| SecretStringError::InvalidSeedLength)?;
let public = PublicKey::from_secret_key(&secret);
Ok(Pair{ secret, public })
Ok(Pair{ public, secret })
}
/// Derive a child key from a series of given junctions.
@@ -592,7 +592,7 @@ mod test {
let message = b"";
let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
let signature = Signature::from_raw(signature);
assert!(&pair.sign(&message[..]) == &signature);
assert!(pair.sign(&message[..]) == signature);
assert!(Pair::verify(&signature, &message[..], &public));
}
@@ -612,7 +612,7 @@ mod test {
let message = b"";
let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
let signature = Signature::from_raw(signature);
assert!(&pair.sign(&message[..]) == &signature);
assert!(pair.sign(&message[..]) == signature);
assert!(Pair::verify(&signature, &message[..], &public));
}
@@ -754,7 +754,7 @@ mod test {
#[test]
fn signature_serialization_doesnt_panic() {
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
Ok(serde_json::from_str(text)?)
serde_json::from_str(text)
}
assert!(deserialize_signature("Not valid json.").is_err());
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
+8 -11
View File
@@ -65,7 +65,7 @@ pub struct Pair(ed25519_dalek::Keypair);
impl Clone for Pair {
fn clone(&self) -> Self {
Pair(ed25519_dalek::Keypair {
public: self.0.public.clone(),
public: self.0.public,
secret: ed25519_dalek::SecretKey::from_bytes(self.0.secret.as_bytes())
.expect("key is always the correct size; qed")
})
@@ -217,8 +217,8 @@ impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
Ok(Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))
}
}
@@ -522,10 +522,7 @@ impl TraitPair for Pair {
Err(_) => return false
};
match public_key.verify(message.as_ref(), &sig) {
Ok(_) => true,
_ => false,
}
public_key.verify(message.as_ref(), &sig).is_ok()
}
/// Return a vec filled with raw data.
@@ -546,7 +543,7 @@ impl Pair {
#[cfg(feature = "std")]
pub fn from_legacy_string(s: &str, password_override: Option<&str>) -> Pair {
Self::from_string(s, password_override).unwrap_or_else(|_| {
let mut padded_seed: Seed = [' ' as u8; 32];
let mut padded_seed: Seed = [b' '; 32];
let len = s.len().min(32);
padded_seed[..len].copy_from_slice(&s.as_bytes()[..len]);
Self::from_seed(&padded_seed)
@@ -609,7 +606,7 @@ mod test {
let message = b"";
let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
let signature = Signature::from_raw(signature);
assert!(&pair.sign(&message[..]) == &signature);
assert!(pair.sign(&message[..]) == signature);
assert!(Pair::verify(&signature, &message[..], &public));
}
@@ -626,7 +623,7 @@ mod test {
let message = b"";
let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
let signature = Signature::from_raw(signature);
assert!(&pair.sign(&message[..]) == &signature);
assert!(pair.sign(&message[..]) == signature);
assert!(Pair::verify(&signature, &message[..], &public));
}
@@ -703,7 +700,7 @@ mod test {
#[test]
fn signature_serialization_doesnt_panic() {
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
Ok(serde_json::from_str(text)?)
serde_json::from_str(text)
}
assert!(deserialize_signature("Not valid json.").is_err());
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
+11 -11
View File
@@ -285,15 +285,15 @@ pub trait TypeId {
#[derive(Encode, Decode, PassByEnum, Copy, Clone)]
pub enum LogLevel {
/// `Error` log level.
Error = 1,
Error = 1_isize,
/// `Warn` log level.
Warn = 2,
Warn = 2_isize,
/// `Info` log level.
Info = 3,
Info = 3_isize,
/// `Debug` log level.
Debug = 4,
Debug = 4_isize,
/// `Trace` log level.
Trace = 5,
Trace = 5_isize,
}
impl From<u32> for LogLevel {
@@ -340,17 +340,17 @@ impl From<LogLevel> for log::Level {
#[derive(Encode, Decode, PassByEnum, Copy, Clone)]
pub enum LogLevelFilter {
/// `Off` log level filter.
Off = 0,
Off = 0_isize,
/// `Error` log level filter.
Error = 1,
Error = 1_isize,
/// `Warn` log level filter.
Warn = 2,
Warn = 2_isize,
/// `Info` log level filter.
Info = 3,
Info = 3_isize,
/// `Debug` log level filter.
Debug = 4,
Debug = 4_isize,
/// `Trace` log level filter.
Trace = 5,
Trace = 5_isize,
}
impl From<LogLevelFilter> for log::LevelFilter {
@@ -66,12 +66,12 @@ pub enum StorageKind {
/// that is re-run at block `N(hash2)`.
/// This storage can be used by offchain workers to handle forks
/// and coordinate offchain workers running on different forks.
PERSISTENT = 1,
PERSISTENT = 1_isize,
/// Local storage is revertible and fork-aware. It means that any value
/// set by the offchain worker triggered at block `N(hash1)` is reverted
/// if that block is reverted as non-canonical and is NOT available for the worker
/// that is re-run at block `N(hash2)`.
LOCAL = 2,
LOCAL = 2_isize,
}
impl TryFrom<u32> for StorageKind {
@@ -108,11 +108,11 @@ impl From<HttpRequestId> for u32 {
#[repr(C)]
pub enum HttpError {
/// The requested action couldn't been completed within a deadline.
DeadlineReached = 1,
DeadlineReached = 1_isize,
/// There was an IO Error while processing the request.
IoError = 2,
IoError = 2_isize,
/// The ID of the request is invalid in this context.
Invalid = 3,
Invalid = 3_isize,
}
impl TryFrom<u32> for HttpError {
@@ -34,7 +34,7 @@ impl InMemOffchainStorage {
}
/// Iterate over all key value pairs by reference.
pub fn iter<'a>(&'a self) -> impl Iterator<Item=(&'a Vec<u8>,&'a Vec<u8>)> {
pub fn iter(&self) -> impl Iterator<Item=(&Vec<u8>,&Vec<u8>)> {
self.storage.iter()
}
@@ -247,7 +247,7 @@ impl offchain::Externalities for TestOffchainExt {
fn http_request_start(&mut self, method: &str, uri: &str, meta: &[u8]) -> Result<RequestId, ()> {
let mut state = self.0.write();
let id = RequestId(state.requests.len() as u16);
state.requests.insert(id.clone(), PendingRequest {
state.requests.insert(id, PendingRequest {
method: method.into(),
uri: uri.into(),
meta: meta.into(),
+5 -5
View File
@@ -218,8 +218,8 @@ impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
Ok(Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
Signature::try_from(signature_hex.as_ref())
.map_err(|e| de::Error::custom(format!("{:?}", e)))
}
}
@@ -448,7 +448,7 @@ impl AsRef<schnorrkel::Keypair> for Pair {
/// Derive a single hard junction.
#[cfg(feature = "full_crypto")]
fn derive_hard_junction(secret: &SecretKey, cc: &[u8; CHAIN_CODE_LENGTH]) -> MiniSecretKey {
secret.hard_derive_mini_secret_key(Some(ChainCode(cc.clone())), b"").0
secret.hard_derive_mini_secret_key(Some(ChainCode(*cc)), b"").0
}
/// The raw secret seed, which can be used to recreate the `Pair`.
@@ -762,7 +762,7 @@ mod test {
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
));
let path = Some(DeriveJunction::soft(1));
let pair_1 = pair.derive(path.clone().into_iter(), None).unwrap().0;
let pair_1 = pair.derive(path.into_iter(), None).unwrap().0;
let public_1 = pair.public().derive(path.into_iter()).unwrap();
assert_eq!(pair_1.public(), public_1);
}
@@ -879,7 +879,7 @@ mod test {
#[test]
fn signature_serialization_doesnt_panic() {
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
Ok(serde_json::from_str(text)?)
serde_json::from_str(text)
}
assert!(deserialize_signature("Not valid json.").is_err());
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
+7
View File
@@ -143,6 +143,13 @@ impl TaskExecutor {
}
}
#[cfg(feature = "std")]
impl Default for TaskExecutor {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "std")]
impl crate::traits::SpawnNamed for TaskExecutor {
fn spawn_blocking(&self, _: &'static str, future: futures::future::BoxFuture<'static, ()>) {
+4 -4
View File
@@ -51,14 +51,14 @@ pub trait FetchRuntimeCode {
/// Fetch the runtime `:code`.
///
/// If the `:code` could not be found/not available, `None` should be returned.
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>>;
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>>;
}
/// Wrapper to use a `u8` slice or `Vec` as [`FetchRuntimeCode`].
pub struct WrappedRuntimeCode<'a>(pub std::borrow::Cow<'a, [u8]>);
impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
Some(self.0.as_ref().into())
}
}
@@ -67,7 +67,7 @@ impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
pub struct NoneFetchRuntimeCode;
impl FetchRuntimeCode for NoneFetchRuntimeCode {
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>> {
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
None
}
}
@@ -108,7 +108,7 @@ impl<'a> RuntimeCode<'a> {
}
impl<'a> FetchRuntimeCode for RuntimeCode<'a> {
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
self.code_fetcher.fetch_runtime_code()
}
}