Skip to content

Commit 43eb331

Browse files
committed
Merge #400: Clear some more clippy warnings
cc1444d Use is_empty instead of comparison to 0 (Tobin C. Harding) 0421dfd Use vec macro instead of mut and push (Tobin C. Harding) 5155193 Remove redundant clone (Tobin C. Harding) 035ff5b Use an iterator to iterate over casts (Tobin C. Harding) b6c432b Use take instead of replace with default (Tobin C. Harding) c025403 Use any instead of fold (Tobin C. Harding) 42033dd Use is_err instead of pattern matching (Tobin C. Harding) a024e75 Fix manual implementation of Option::map warnings (Tobin C. Harding) bb1e916 Use map instead of and_then (Tobin C. Harding) 7816a5f Improve docs on parse method (Tobin C. Harding) 6ced1c0 Remove unnecessary cast (Tobin C. Harding) 1a02514 Remove explicit lifetimes (Tobin C. Harding) 80f9f14 Add clippy allow for from_str method (Tobin C. Harding) ff32f95 Use iter instead of into_iter (Tobin C. Harding) b6be0be Fix doc example (Tobin C. Harding) 36ae791 Remove unnecessary *&mut (Tobin C. Harding) 5596d07 Use struct init shorthand (Tobin C. Harding) Pull request description: Clear all the remaining non-controversial clippy warnings. Should be just the curly ones left after this. ACKs for top commit: sanket1729: Thanks for doing this. ACK cc1444d Tree-SHA512: f0041faa8bcb9ba5b0db5c0be21d2b44c18cb188cebf2b583f72ad82e6947bd29c454fa6c723fde310a61e41f5116b93bbd29fb6f3ede2bf68e1b36fd118a6b3
2 parents c0076e6 + cc1444d commit 43eb331

File tree

8 files changed

+79
-89
lines changed

8 files changed

+79
-89
lines changed

src/descriptor/key.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ impl DescriptorXKey<bip32::ExtendedPrivKey> {
180180
Some((fingerprint, path)) => Some((
181181
*fingerprint,
182182
path.into_iter()
183-
.chain(hardened_path.into_iter())
183+
.chain(hardened_path.iter())
184184
.cloned()
185185
.collect(),
186186
)),
@@ -456,7 +456,7 @@ impl DescriptorPublicKey {
456456
DescriptorPublicKey::XPub(DescriptorXKey {
457457
origin: xpub.origin,
458458
xkey: xpub.xkey,
459-
derivation_path: derivation_path,
459+
derivation_path,
460460
wildcard: Wildcard::None,
461461
})
462462
}

src/expression.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ impl<'a> Tree<'a> {
173173
}
174174

175175
/// Parses a tree from a string
176+
#[allow(clippy::should_implement_trait)] // Cannot use std::str::FromStr because of lifetimes.
176177
pub fn from_str(s: &'a str) -> Result<Tree<'a>, Error> {
177178
// Filter out non-ASCII because we byte-index strings all over the
178179
// place and Rust gets very upset when you splinch a string.

src/interpreter/stack.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,9 @@ impl<'txin> Stack<'txin> {
228228
/// The reason we don't need to copy the Script semantics is that
229229
/// Miniscript never evaluates integers and it is safe to treat them as
230230
/// booleans
231-
pub(super) fn evaluate_after<'intp>(
231+
pub(super) fn evaluate_after(
232232
&mut self,
233-
n: &'intp u32,
233+
n: &u32,
234234
age: u32,
235235
) -> Option<Result<SatisfiedConstraint, Error>> {
236236
if age >= *n {
@@ -247,9 +247,9 @@ impl<'txin> Stack<'txin> {
247247
/// The reason we don't need to copy the Script semantics is that
248248
/// Miniscript never evaluates integers and it is safe to treat them as
249249
/// booleans
250-
pub(super) fn evaluate_older<'intp>(
250+
pub(super) fn evaluate_older(
251251
&mut self,
252-
n: &'intp u32,
252+
n: &u32,
253253
height: u32,
254254
) -> Option<Result<SatisfiedConstraint, Error>> {
255255
if height >= *n {
@@ -262,9 +262,9 @@ impl<'txin> Stack<'txin> {
262262

263263
/// Helper function to evaluate a Sha256 Node.
264264
/// `SIZE 32 EQUALVERIFY SHA256 h EQUAL`
265-
pub(super) fn evaluate_sha256<'intp>(
265+
pub(super) fn evaluate_sha256(
266266
&mut self,
267-
hash: &'intp sha256::Hash,
267+
hash: &sha256::Hash,
268268
) -> Option<Result<SatisfiedConstraint, Error>> {
269269
if let Some(Element::Push(preimage)) = self.pop() {
270270
if preimage.len() != 32 {
@@ -287,9 +287,9 @@ impl<'txin> Stack<'txin> {
287287

288288
/// Helper function to evaluate a Hash256 Node.
289289
/// `SIZE 32 EQUALVERIFY HASH256 h EQUAL`
290-
pub(super) fn evaluate_hash256<'intp>(
290+
pub(super) fn evaluate_hash256(
291291
&mut self,
292-
hash: &'intp sha256d::Hash,
292+
hash: &sha256d::Hash,
293293
) -> Option<Result<SatisfiedConstraint, Error>> {
294294
if let Some(Element::Push(preimage)) = self.pop() {
295295
if preimage.len() != 32 {
@@ -312,9 +312,9 @@ impl<'txin> Stack<'txin> {
312312

313313
/// Helper function to evaluate a Hash160 Node.
314314
/// `SIZE 32 EQUALVERIFY HASH160 h EQUAL`
315-
pub(super) fn evaluate_hash160<'intp>(
315+
pub(super) fn evaluate_hash160(
316316
&mut self,
317-
hash: &'intp hash160::Hash,
317+
hash: &hash160::Hash,
318318
) -> Option<Result<SatisfiedConstraint, Error>> {
319319
if let Some(Element::Push(preimage)) = self.pop() {
320320
if preimage.len() != 32 {
@@ -337,9 +337,9 @@ impl<'txin> Stack<'txin> {
337337

338338
/// Helper function to evaluate a RipeMd160 Node.
339339
/// `SIZE 32 EQUALVERIFY RIPEMD160 h EQUAL`
340-
pub(super) fn evaluate_ripemd160<'intp>(
340+
pub(super) fn evaluate_ripemd160(
341341
&mut self,
342-
hash: &'intp ripemd160::Hash,
342+
hash: &ripemd160::Hash,
343343
) -> Option<Result<SatisfiedConstraint, Error>> {
344344
if let Some(Element::Push(preimage)) = self.pop() {
345345
if preimage.len() != 32 {

src/lib.rs

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -54,36 +54,31 @@
5454
//!
5555
//! ```rust
5656
//! use std::str::FromStr;
57-
//! use miniscript::{DescriptorTrait};
57+
//! use miniscript::DescriptorTrait;
5858
//!
59-
//! fn main() {
60-
//! let desc = miniscript::Descriptor::<
61-
//! bitcoin::PublicKey,
62-
//! >::from_str("\
63-
//! sh(wsh(or_d(\
64-
//! c:pk_k(020e0338c96a8870479f2396c373cc7696ba124e8635d41b0ea581112b67817261),\
65-
//! c:pk_k(0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352)\
66-
//! )))\
59+
//! let desc = miniscript::Descriptor::<bitcoin::PublicKey>::from_str("\
60+
//! sh(wsh(or_d(\
61+
//! c:pk_k(020e0338c96a8870479f2396c373cc7696ba124e8635d41b0ea581112b67817261),\
62+
//! c:pk_k(0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352)\
63+
//! )))\
6764
//! ").unwrap();
6865
//!
69-
//! // Derive the P2SH address
70-
//! assert_eq!(
71-
//! desc.address(bitcoin::Network::Bitcoin).unwrap().to_string(),
72-
//! "3CJxbQBfWAe1ZkKiGQNEYrioV73ZwvBWns"
73-
//! );
66+
//! // Derive the P2SH address
67+
//! assert_eq!(
68+
//! desc.address(bitcoin::Network::Bitcoin).unwrap().to_string(),
69+
//! "3CJxbQBfWAe1ZkKiGQNEYrioV73ZwvBWns"
70+
//! );
7471
//!
75-
//! // Check whether the descriptor is safe
76-
//! // This checks whether all spend paths are accessible in bitcoin network.
77-
//! // It maybe possible that some of the spend require more than 100 elements in Wsh scripts
78-
//! // Or they contain a combination of timelock and heightlock.
79-
//! assert!(desc.sanity_check().is_ok());
72+
//! // Check whether the descriptor is safe. This checks whether all spend paths are accessible in
73+
//! // the Bitcoin network. It may be possible that some of the spend paths require more than 100
74+
//! // elements in Wsh scripts or they contain a combination of timelock and heightlock.
75+
//! assert!(desc.sanity_check().is_ok());
8076
//!
81-
//! // Estimate the satisfaction cost
82-
//! assert_eq!(desc.max_satisfaction_weight().unwrap(), 293);
83-
//! }
77+
//! // Estimate the satisfaction cost
78+
//! assert_eq!(desc.max_satisfaction_weight().unwrap(), 293);
8479
//! ```
8580
//!
86-
//!
81+
8782
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
8883
// Coding conventions
8984
#![deny(unsafe_code)]

src/miniscript/astelem.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ impl<Pk: MiniscriptKey, Ctx: ScriptContext> Terminal<Pk, Ctx> {
194194
Arc::new(right.real_translate_pk(fpk, fpkh)?),
195195
),
196196
Terminal::OrI(ref left, ref right) => Terminal::OrI(
197-
Arc::new(left.real_translate_pk(&mut *&mut *fpk, &mut *&mut *fpkh)?),
197+
Arc::new(left.real_translate_pk(&mut *fpk, &mut *fpkh)?),
198198
Arc::new(right.real_translate_pk(fpk, fpkh)?),
199199
),
200200
Terminal::Thresh(k, ref subs) => {

src/miniscript/mod.rs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -166,37 +166,37 @@ impl<Ctx: ScriptContext> Miniscript<Ctx::Key, Ctx> {
166166
}
167167

168168
/// Attempt to parse a Script into Miniscript representation.
169-
/// This function will fail parsing for scripts that do not clear
170-
/// the [Miniscript::sanity_check] checks. Use [Miniscript::parse_insane] to
169+
///
170+
/// This function will fail parsing for scripts that do not clear the
171+
/// [`Miniscript::sanity_check`] checks. Use [`Miniscript::parse_insane`] to
171172
/// parse such scripts.
172173
///
173174
/// ## Decode/Parse a miniscript from script hex
174175
///
175176
/// ```rust
176-
/// use miniscript::Miniscript;
177-
/// use miniscript::{Segwitv0, Tap};
177+
/// use miniscript::{Miniscript, Segwitv0, Tap};
178178
/// use miniscript::bitcoin::secp256k1::XOnlyPublicKey;
179+
/// use miniscript::bitcoin::hashes::hex::FromHex;
180+
///
179181
/// type Segwitv0Script = Miniscript<bitcoin::PublicKey, Segwitv0>;
180182
/// type TapScript = Miniscript<XOnlyPublicKey, Tap>;
181-
/// use bitcoin::hashes::hex::FromHex;
182-
/// fn main() {
183-
/// // parse x-only miniscript in Taproot context
184-
/// let tapscript_ms = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
185-
/// "202788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
186-
/// ).expect("Even length hex")))
183+
///
184+
/// // parse x-only miniscript in Taproot context
185+
/// let tapscript_ms = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
186+
/// "202788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
187+
/// ).expect("Even length hex")))
187188
/// .expect("Xonly keys are valid only in taproot context");
188-
/// // tapscript fails decoding when we use them with compressed keys
189-
/// let err = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
190-
/// "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
191-
/// ).expect("Even length hex")))
189+
/// // tapscript fails decoding when we use them with compressed keys
190+
/// let err = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
191+
/// "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
192+
/// ).expect("Even length hex")))
192193
/// .expect_err("Compressed keys cannot be used in Taproot context");
193-
/// // Segwitv0 succeeds decoding with full keys.
194-
/// Segwitv0Script::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
195-
/// "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
196-
/// ).expect("Even length hex")))
194+
/// // Segwitv0 succeeds decoding with full keys.
195+
/// Segwitv0Script::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
196+
/// "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
197+
/// ).expect("Even length hex")))
197198
/// .expect("Compressed keys are allowed in Segwit context");
198199
///
199-
/// }
200200
/// ```
201201
pub fn parse(script: &script::Script) -> Result<Miniscript<Ctx::Key, Ctx>, Error> {
202202
let ms = Self::parse_insane(script)?;

src/miniscript/types/extra_props.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -761,9 +761,9 @@ impl Property for ExtData {
761761
S: FnMut(usize) -> Result<Self, ErrorKind>,
762762
{
763763
let mut pk_cost = 1 + script_num_size(k); //Equal and k
764-
let mut ops_count = 0 as usize;
764+
let mut ops_count = 0;
765765
let mut ops_count_sat_vec = Vec::with_capacity(n);
766-
let mut ops_count_nsat_sum = 0 as usize;
766+
let mut ops_count_nsat_sum = 0;
767767
let mut op_count_sat = Some(0);
768768
let mut timelocks = Vec::with_capacity(n);
769769
let mut stack_elem_count_sat_vec = Vec::with_capacity(n);

src/policy/compiler.rs

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ impl CompilationKey {
129129
CompilationKey {
130130
ty,
131131
expensive_verify,
132-
dissat_prob: dissat_prob.and_then(|x| Some(OrdF64(x))),
132+
dissat_prob: dissat_prob.map(OrdF64),
133133
}
134134
}
135135
}
@@ -353,6 +353,7 @@ impl Property for CompilerExtData {
353353
})
354354
}
355355

356+
#[allow(clippy::manual_map)] // Complex if/let is better as is.
356357
fn or_i(l: Self, r: Self) -> Result<Self, types::ErrorKind> {
357358
let lprob = l
358359
.branch_prob
@@ -394,11 +395,7 @@ impl Property for CompilerExtData {
394395
Ok(CompilerExtData {
395396
branch_prob: None,
396397
sat_cost: aprob * (a.sat_cost + b.sat_cost) + cprob * (adis + c.sat_cost),
397-
dissat_cost: if let Some(cdis) = c.dissat_cost {
398-
Some(adis + cdis)
399-
} else {
400-
None
401-
},
398+
dissat_cost: c.dissat_cost.map(|cdis| adis + cdis),
402399
})
403400
}
404401

@@ -508,8 +505,8 @@ impl<Pk: MiniscriptKey, Ctx: ScriptContext> AstElemExt<Pk, Ctx> {
508505
let comp_ext_data = CompilerExtData::type_check(&ast, lookup_ext)?;
509506
Ok(AstElemExt {
510507
ms: Arc::new(Miniscript {
511-
ty: ty,
512-
ext: ext,
508+
ty,
509+
ext,
513510
node: ast,
514511
phantom: PhantomData,
515512
}),
@@ -647,7 +644,7 @@ fn insert_elem<Pk: MiniscriptKey, Ctx: ScriptContext>(
647644
return false;
648645
}
649646

650-
if let Err(_) = Ctx::check_local_validity(&elem.ms) {
647+
if Ctx::check_local_validity(&elem.ms).is_err() {
651648
return false;
652649
}
653650

@@ -664,11 +661,11 @@ fn insert_elem<Pk: MiniscriptKey, Ctx: ScriptContext>(
664661
let existing_elem_cost = existing_elem.cost_1d(sat_prob, dissat_prob);
665662
existing_key.is_subtype(elem_key) && existing_elem_cost <= elem_cost
666663
})
667-
.fold(false, |acc, x| acc || x);
664+
.any(|x| x);
668665
if !is_worse {
669666
// If the element is not worse any element in the map, remove elements
670667
// whose subtype is the current element and have worse cost.
671-
*map = mem::replace(map, BTreeMap::new())
668+
*map = mem::take(map)
672669
.into_iter()
673670
.filter(|&(ref existing_key, ref existing_elem)| {
674671
let existing_elem_cost = existing_elem.cost_1d(sat_prob, dissat_prob);
@@ -703,8 +700,8 @@ fn insert_elem_closure<Pk: MiniscriptKey, Ctx: ScriptContext>(
703700
while !cast_stack.is_empty() {
704701
let current = cast_stack.pop_front().unwrap();
705702

706-
for i in 0..casts.len() {
707-
if let Ok(new_ext) = casts[i].cast(&current) {
703+
for c in &casts {
704+
if let Ok(new_ext) = c.cast(&current) {
708705
if insert_elem(map, new_ext.clone(), sat_prob, dissat_prob) {
709706
cast_stack.push_back(new_ext);
710707
}
@@ -735,9 +732,9 @@ fn insert_best_wrapped<Pk: MiniscriptKey, Ctx: ScriptContext>(
735732
if dissat_prob.is_some() {
736733
let casts: [Cast<Pk, Ctx>; 10] = all_casts::<Pk, Ctx>();
737734

738-
for i in 0..casts.len() {
735+
for c in &casts {
739736
for x in best_compilations(policy_cache, policy, sat_prob, None)?.values() {
740-
if let Ok(new_ext) = casts[i].cast(x) {
737+
if let Ok(new_ext) = c.cast(x) {
741738
insert_elem_closure(map, new_ext, sat_prob, dissat_prob);
742739
}
743740
}
@@ -760,7 +757,7 @@ where
760757
{
761758
//Check the cache for hits
762759
let ord_sat_prob = OrdF64(sat_prob);
763-
let ord_dissat_prob = dissat_prob.and_then(|x| Some(OrdF64(x)));
760+
let ord_dissat_prob = dissat_prob.map(OrdF64);
764761
if let Some(ret) = policy_cache.get(&(policy.clone(), ord_sat_prob, ord_dissat_prob)) {
765762
return Ok(ret.clone());
766763
}
@@ -812,9 +809,7 @@ where
812809
insert_wrap!(AstElemExt::terminal(Terminal::True));
813810
}
814811
Concrete::Key(ref pk) => {
815-
insert_wrap!(AstElemExt::terminal(Terminal::PkH(
816-
pk.to_pubkeyhash().clone()
817-
)));
812+
insert_wrap!(AstElemExt::terminal(Terminal::PkH(pk.to_pubkeyhash())));
818813
insert_wrap!(AstElemExt::terminal(Terminal::PkK(pk.clone())));
819814
}
820815
Concrete::After(n) => insert_wrap!(AstElemExt::terminal(Terminal::After(n))),
@@ -900,12 +895,12 @@ where
900895
};
901896

902897
let dissat_probs = |w: f64| -> Vec<Option<f64>> {
903-
let mut dissat_set = Vec::new();
904-
dissat_set.push(Some(dissat_prob.unwrap_or(0 as f64) + w * sat_prob));
905-
dissat_set.push(Some(w * sat_prob));
906-
dissat_set.push(dissat_prob);
907-
dissat_set.push(None);
908-
dissat_set
898+
vec![
899+
Some(dissat_prob.unwrap_or(0 as f64) + w * sat_prob),
900+
Some(w * sat_prob),
901+
dissat_prob,
902+
None,
903+
]
909904
};
910905

911906
let mut l_comp = vec![];
@@ -945,7 +940,7 @@ where
945940
let mut best_es = Vec::with_capacity(n);
946941
let mut best_ws = Vec::with_capacity(n);
947942

948-
let mut min_value = (0 as usize, f64::INFINITY as f64);
943+
let mut min_value = (0, f64::INFINITY as f64);
949944
for (i, ast) in subs.iter().enumerate() {
950945
let sp = sat_prob * k_over_n;
951946
//Expressions must be dissatisfiable
@@ -1013,7 +1008,7 @@ where
10131008
for k in ret.keys() {
10141009
debug_assert_eq!(k.dissat_prob, ord_dissat_prob);
10151010
}
1016-
if ret.len() == 0 {
1011+
if ret.is_empty() {
10171012
// The only reason we are discarding elements out of compiler is because
10181013
// compilations exceeded consensus and standardness limits or are non-malleable.
10191014
// If there no possible compilations for any policies regardless of dissat
@@ -1123,8 +1118,7 @@ where
11231118
best_compilations(policy_cache, policy, sat_prob, dissat_prob)?
11241119
.into_iter()
11251120
.filter(|&(key, _)| {
1126-
key.ty.corr.base == types::Base::B
1127-
&& key.dissat_prob == dissat_prob.and_then(|x| Some(OrdF64(x)))
1121+
key.ty.corr.base == types::Base::B && key.dissat_prob == dissat_prob.map(OrdF64)
11281122
})
11291123
.map(|(_, val)| val)
11301124
.min_by_key(|ext| OrdF64(ext.cost_1d(sat_prob, dissat_prob)))
@@ -1149,7 +1143,7 @@ where
11491143
key.ty.corr.base == basic_type
11501144
&& key.ty.corr.unit
11511145
&& val.ms.ty.mall.dissat == types::Dissat::Unique
1152-
&& key.dissat_prob == dissat_prob.and_then(|x| Some(OrdF64(x)))
1146+
&& key.dissat_prob == dissat_prob.map(OrdF64)
11531147
})
11541148
.map(|(_, val)| val)
11551149
.min_by_key(|ext| OrdF64(ext.cost_1d(sat_prob, dissat_prob)))

0 commit comments

Comments
 (0)