Skip to content
This repository was archived by the owner on Feb 21, 2024. It is now read-only.

Commit 6168279

Browse files
adoerrbkchr
authored andcommitted
[clippy] Fix clippy issues for crate sp-core (paritytech#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>
1 parent 1603f0f commit 6168279

File tree

12 files changed

+62
-58
lines changed

12 files changed

+62
-58
lines changed

primitives/core/benches/bench.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ fn get_key(key_size: u32) -> Vec<u8> {
3232
let mut rnd = rnd.iter().cycle();
3333

3434
(0..key_size)
35-
.map(|_| rnd.next().unwrap().clone())
35+
.map(|_| *rnd.next().unwrap())
3636
.collect()
3737
}
3838

primitives/core/src/changes_trie.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ mod tests {
226226
#[test]
227227
fn is_digest_build_required_at_block_works() {
228228
fn test_with_zero(zero: u64) {
229-
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 0u64));
229+
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero));
230230
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 1u64));
231231
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 2u64));
232232
assert!(!config(8, 4).is_digest_build_required_at_block(zero, zero + 4u64));
@@ -249,7 +249,7 @@ mod tests {
249249
#[test]
250250
fn digest_level_at_block_works() {
251251
fn test_with_zero(zero: u64) {
252-
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 0u64), None);
252+
assert_eq!(config(8, 4).digest_level_at_block(zero, zero), None);
253253
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 7u64), None);
254254
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 63u64), None);
255255
assert_eq!(config(8, 4).digest_level_at_block(zero, zero + 8u64), Some((1, 8, 1)));

primitives/core/src/crypto.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,8 @@ impl DeriveJunction {
174174
impl<T: AsRef<str>> From<T> for DeriveJunction {
175175
fn from(j: T) -> DeriveJunction {
176176
let j = j.as_ref();
177-
let (code, hard) = if j.starts_with('/') {
178-
(&j[1..], true)
177+
let (code, hard) = if let Some(stripped) = j.strip_prefix('/') {
178+
(stripped, true)
179179
} else {
180180
(j, false)
181181
};
@@ -262,7 +262,7 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default {
262262
let upper = data[1] & 0b00111111;
263263
(2, (lower as u16) | ((upper as u16) << 8))
264264
}
265-
_ => Err(PublicError::UnknownVersion)?,
265+
_ => return Err(PublicError::UnknownVersion),
266266
};
267267
if data.len() != prefix_len + body_len + CHECKSUM_LEN { return Err(PublicError::BadLength) }
268268
let format = ident.try_into().map_err(|_: ()| PublicError::UnknownVersion)?;
@@ -294,15 +294,15 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default {
294294
#[cfg(feature = "std")]
295295
fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String {
296296
// We mask out the upper two bits of the ident - SS58 Prefix currently only supports 14-bits
297-
let ident: u16 = u16::from(version) & 0b00111111_11111111;
297+
let ident: u16 = u16::from(version) & 0b0011_1111_1111_1111;
298298
let mut v = match ident {
299299
0..=63 => vec![ident as u8],
300300
64..=16_383 => {
301301
// upper six bits of the lower byte(!)
302-
let first = ((ident & 0b00000000_11111100) as u8) >> 2;
302+
let first = ((ident & 0b0000_0000_1111_1100) as u8) >> 2;
303303
// lower two bits of the lower byte in the high pos,
304304
// lower bits of the upper byte in the low pos
305-
let second = ((ident >> 8) as u8) | ((ident & 0b00000000_00000011) as u8) << 6;
305+
let second = ((ident >> 8) as u8) | ((ident & 0b0000_0000_0000_0011) as u8) << 6;
306306
vec![first | 0b01000000, second]
307307
}
308308
_ => unreachable!("masked out the upper two bits; qed"),
@@ -612,14 +612,14 @@ impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Default + Derive> Ss58Codec for T {
612612
let s = cap.name("ss58")
613613
.map(|r| r.as_str())
614614
.unwrap_or(DEV_ADDRESS);
615-
let addr = if s.starts_with("0x") {
616-
let d = hex::decode(&s[2..]).map_err(|_| PublicError::InvalidFormat)?;
615+
let addr = if let Some(stripped) = s.strip_prefix("0x") {
616+
let d = hex::decode(stripped).map_err(|_| PublicError::InvalidFormat)?;
617617
let mut r = Self::default();
618618
if d.len() == r.as_ref().len() {
619619
r.as_mut().copy_from_slice(&d);
620620
r
621621
} else {
622-
Err(PublicError::BadLength)?
622+
return Err(PublicError::BadLength)
623623
}
624624
} else {
625625
Self::from_ss58check(s)?
@@ -1009,8 +1009,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static {
10091009
let phrase = cap.name("phrase").map(|r| r.as_str()).unwrap_or(DEV_PHRASE);
10101010
let password = password_override.or_else(|| cap.name("password").map(|m| m.as_str()));
10111011

1012-
let (root, seed) = if phrase.starts_with("0x") {
1013-
hex::decode(&phrase[2..]).ok()
1012+
let (root, seed) = if let Some(stripped) = phrase.strip_prefix("0x") {
1013+
hex::decode(stripped).ok()
10141014
.and_then(|seed_vec| {
10151015
let mut seed = Self::Seed::default();
10161016
if seed.as_ref().len() == seed_vec.len() {

primitives/core/src/ecdsa.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,8 @@ impl<'de> Deserialize<'de> for Signature {
256256
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
257257
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
258258
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
259-
Ok(Signature::try_from(signature_hex.as_ref())
260-
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
259+
Signature::try_from(signature_hex.as_ref())
260+
.map_err(|e| de::Error::custom(format!("{:?}", e)))
261261
}
262262
}
263263

@@ -453,7 +453,7 @@ impl TraitPair for Pair {
453453
let secret = SecretKey::parse_slice(seed_slice)
454454
.map_err(|_| SecretStringError::InvalidSeedLength)?;
455455
let public = PublicKey::from_secret_key(&secret);
456-
Ok(Pair{ secret, public })
456+
Ok(Pair{ public, secret })
457457
}
458458

459459
/// Derive a child key from a series of given junctions.
@@ -592,7 +592,7 @@ mod test {
592592
let message = b"";
593593
let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
594594
let signature = Signature::from_raw(signature);
595-
assert!(&pair.sign(&message[..]) == &signature);
595+
assert!(pair.sign(&message[..]) == signature);
596596
assert!(Pair::verify(&signature, &message[..], &public));
597597
}
598598

@@ -612,7 +612,7 @@ mod test {
612612
let message = b"";
613613
let signature = hex!("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
614614
let signature = Signature::from_raw(signature);
615-
assert!(&pair.sign(&message[..]) == &signature);
615+
assert!(pair.sign(&message[..]) == signature);
616616
assert!(Pair::verify(&signature, &message[..], &public));
617617
}
618618

@@ -754,7 +754,7 @@ mod test {
754754
#[test]
755755
fn signature_serialization_doesnt_panic() {
756756
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
757-
Ok(serde_json::from_str(text)?)
757+
serde_json::from_str(text)
758758
}
759759
assert!(deserialize_signature("Not valid json.").is_err());
760760
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());

primitives/core/src/ed25519.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ pub struct Pair(ed25519_dalek::Keypair);
6565
impl Clone for Pair {
6666
fn clone(&self) -> Self {
6767
Pair(ed25519_dalek::Keypair {
68-
public: self.0.public.clone(),
68+
public: self.0.public,
6969
secret: ed25519_dalek::SecretKey::from_bytes(self.0.secret.as_bytes())
7070
.expect("key is always the correct size; qed")
7171
})
@@ -217,8 +217,8 @@ impl<'de> Deserialize<'de> for Signature {
217217
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
218218
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
219219
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
220-
Ok(Signature::try_from(signature_hex.as_ref())
221-
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
220+
Signature::try_from(signature_hex.as_ref())
221+
.map_err(|e| de::Error::custom(format!("{:?}", e)))
222222
}
223223
}
224224

@@ -522,10 +522,7 @@ impl TraitPair for Pair {
522522
Err(_) => return false
523523
};
524524

525-
match public_key.verify(message.as_ref(), &sig) {
526-
Ok(_) => true,
527-
_ => false,
528-
}
525+
public_key.verify(message.as_ref(), &sig).is_ok()
529526
}
530527

531528
/// Return a vec filled with raw data.
@@ -546,7 +543,7 @@ impl Pair {
546543
#[cfg(feature = "std")]
547544
pub fn from_legacy_string(s: &str, password_override: Option<&str>) -> Pair {
548545
Self::from_string(s, password_override).unwrap_or_else(|_| {
549-
let mut padded_seed: Seed = [' ' as u8; 32];
546+
let mut padded_seed: Seed = [b' '; 32];
550547
let len = s.len().min(32);
551548
padded_seed[..len].copy_from_slice(&s.as_bytes()[..len]);
552549
Self::from_seed(&padded_seed)
@@ -609,7 +606,7 @@ mod test {
609606
let message = b"";
610607
let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
611608
let signature = Signature::from_raw(signature);
612-
assert!(&pair.sign(&message[..]) == &signature);
609+
assert!(pair.sign(&message[..]) == signature);
613610
assert!(Pair::verify(&signature, &message[..], &public));
614611
}
615612

@@ -626,7 +623,7 @@ mod test {
626623
let message = b"";
627624
let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
628625
let signature = Signature::from_raw(signature);
629-
assert!(&pair.sign(&message[..]) == &signature);
626+
assert!(pair.sign(&message[..]) == signature);
630627
assert!(Pair::verify(&signature, &message[..], &public));
631628
}
632629

@@ -703,7 +700,7 @@ mod test {
703700
#[test]
704701
fn signature_serialization_doesnt_panic() {
705702
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
706-
Ok(serde_json::from_str(text)?)
703+
serde_json::from_str(text)
707704
}
708705
assert!(deserialize_signature("Not valid json.").is_err());
709706
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());

primitives/core/src/lib.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -285,15 +285,15 @@ pub trait TypeId {
285285
#[derive(Encode, Decode, PassByEnum, Copy, Clone)]
286286
pub enum LogLevel {
287287
/// `Error` log level.
288-
Error = 1,
288+
Error = 1_isize,
289289
/// `Warn` log level.
290-
Warn = 2,
290+
Warn = 2_isize,
291291
/// `Info` log level.
292-
Info = 3,
292+
Info = 3_isize,
293293
/// `Debug` log level.
294-
Debug = 4,
294+
Debug = 4_isize,
295295
/// `Trace` log level.
296-
Trace = 5,
296+
Trace = 5_isize,
297297
}
298298

299299
impl From<u32> for LogLevel {
@@ -340,17 +340,17 @@ impl From<LogLevel> for log::Level {
340340
#[derive(Encode, Decode, PassByEnum, Copy, Clone)]
341341
pub enum LogLevelFilter {
342342
/// `Off` log level filter.
343-
Off = 0,
343+
Off = 0_isize,
344344
/// `Error` log level filter.
345-
Error = 1,
345+
Error = 1_isize,
346346
/// `Warn` log level filter.
347-
Warn = 2,
347+
Warn = 2_isize,
348348
/// `Info` log level filter.
349-
Info = 3,
349+
Info = 3_isize,
350350
/// `Debug` log level filter.
351-
Debug = 4,
351+
Debug = 4_isize,
352352
/// `Trace` log level filter.
353-
Trace = 5,
353+
Trace = 5_isize,
354354
}
355355

356356
impl From<LogLevelFilter> for log::LevelFilter {

primitives/core/src/offchain/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,12 @@ pub enum StorageKind {
6666
/// that is re-run at block `N(hash2)`.
6767
/// This storage can be used by offchain workers to handle forks
6868
/// and coordinate offchain workers running on different forks.
69-
PERSISTENT = 1,
69+
PERSISTENT = 1_isize,
7070
/// Local storage is revertible and fork-aware. It means that any value
7171
/// set by the offchain worker triggered at block `N(hash1)` is reverted
7272
/// if that block is reverted as non-canonical and is NOT available for the worker
7373
/// that is re-run at block `N(hash2)`.
74-
LOCAL = 2,
74+
LOCAL = 2_isize,
7575
}
7676

7777
impl TryFrom<u32> for StorageKind {
@@ -108,11 +108,11 @@ impl From<HttpRequestId> for u32 {
108108
#[repr(C)]
109109
pub enum HttpError {
110110
/// The requested action couldn't been completed within a deadline.
111-
DeadlineReached = 1,
111+
DeadlineReached = 1_isize,
112112
/// There was an IO Error while processing the request.
113-
IoError = 2,
113+
IoError = 2_isize,
114114
/// The ID of the request is invalid in this context.
115-
Invalid = 3,
115+
Invalid = 3_isize,
116116
}
117117

118118
impl TryFrom<u32> for HttpError {

primitives/core/src/offchain/storage.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ impl InMemOffchainStorage {
3434
}
3535

3636
/// Iterate over all key value pairs by reference.
37-
pub fn iter<'a>(&'a self) -> impl Iterator<Item=(&'a Vec<u8>,&'a Vec<u8>)> {
37+
pub fn iter(&self) -> impl Iterator<Item=(&Vec<u8>,&Vec<u8>)> {
3838
self.storage.iter()
3939
}
4040

primitives/core/src/offchain/testing.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ impl offchain::Externalities for TestOffchainExt {
247247
fn http_request_start(&mut self, method: &str, uri: &str, meta: &[u8]) -> Result<RequestId, ()> {
248248
let mut state = self.0.write();
249249
let id = RequestId(state.requests.len() as u16);
250-
state.requests.insert(id.clone(), PendingRequest {
250+
state.requests.insert(id, PendingRequest {
251251
method: method.into(),
252252
uri: uri.into(),
253253
meta: meta.into(),

primitives/core/src/sr25519.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,8 @@ impl<'de> Deserialize<'de> for Signature {
218218
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
219219
let signature_hex = hex::decode(&String::deserialize(deserializer)?)
220220
.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
221-
Ok(Signature::try_from(signature_hex.as_ref())
222-
.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
221+
Signature::try_from(signature_hex.as_ref())
222+
.map_err(|e| de::Error::custom(format!("{:?}", e)))
223223
}
224224
}
225225

@@ -448,7 +448,7 @@ impl AsRef<schnorrkel::Keypair> for Pair {
448448
/// Derive a single hard junction.
449449
#[cfg(feature = "full_crypto")]
450450
fn derive_hard_junction(secret: &SecretKey, cc: &[u8; CHAIN_CODE_LENGTH]) -> MiniSecretKey {
451-
secret.hard_derive_mini_secret_key(Some(ChainCode(cc.clone())), b"").0
451+
secret.hard_derive_mini_secret_key(Some(ChainCode(*cc)), b"").0
452452
}
453453

454454
/// The raw secret seed, which can be used to recreate the `Pair`.
@@ -762,7 +762,7 @@ mod test {
762762
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
763763
));
764764
let path = Some(DeriveJunction::soft(1));
765-
let pair_1 = pair.derive(path.clone().into_iter(), None).unwrap().0;
765+
let pair_1 = pair.derive(path.into_iter(), None).unwrap().0;
766766
let public_1 = pair.public().derive(path.into_iter()).unwrap();
767767
assert_eq!(pair_1.public(), public_1);
768768
}
@@ -879,7 +879,7 @@ mod test {
879879
#[test]
880880
fn signature_serialization_doesnt_panic() {
881881
fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
882-
Ok(serde_json::from_str(text)?)
882+
serde_json::from_str(text)
883883
}
884884
assert!(deserialize_signature("Not valid json.").is_err());
885885
assert!(deserialize_signature("\"Not an actual signature.\"").is_err());

primitives/core/src/testing.rs

+7
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,13 @@ impl TaskExecutor {
143143
}
144144
}
145145

146+
#[cfg(feature = "std")]
147+
impl Default for TaskExecutor {
148+
fn default() -> Self {
149+
Self::new()
150+
}
151+
}
152+
146153
#[cfg(feature = "std")]
147154
impl crate::traits::SpawnNamed for TaskExecutor {
148155
fn spawn_blocking(&self, _: &'static str, future: futures::future::BoxFuture<'static, ()>) {

primitives/core/src/traits.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,14 @@ pub trait FetchRuntimeCode {
5151
/// Fetch the runtime `:code`.
5252
///
5353
/// If the `:code` could not be found/not available, `None` should be returned.
54-
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>>;
54+
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>>;
5555
}
5656

5757
/// Wrapper to use a `u8` slice or `Vec` as [`FetchRuntimeCode`].
5858
pub struct WrappedRuntimeCode<'a>(pub std::borrow::Cow<'a, [u8]>);
5959

6060
impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
61-
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
61+
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
6262
Some(self.0.as_ref().into())
6363
}
6464
}
@@ -67,7 +67,7 @@ impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
6767
pub struct NoneFetchRuntimeCode;
6868

6969
impl FetchRuntimeCode for NoneFetchRuntimeCode {
70-
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>> {
70+
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
7171
None
7272
}
7373
}
@@ -108,7 +108,7 @@ impl<'a> RuntimeCode<'a> {
108108
}
109109

110110
impl<'a> FetchRuntimeCode for RuntimeCode<'a> {
111-
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
111+
fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
112112
self.code_fetcher.fetch_runtime_code()
113113
}
114114
}

0 commit comments

Comments
 (0)