Made some idiomatic changes

This commit is contained in:
Elichai Turkel 2019-08-05 15:41:07 -04:00
parent 3f2d428706
commit a473d01b17
No known key found for this signature in database
GPG Key ID: 9383CDE9E8E66A7F
13 changed files with 87 additions and 103 deletions

View File

@ -78,7 +78,7 @@ impl Block {
if self.txdata.iter().all(|t| t.input.iter().all(|i| i.witness.is_empty())) {
return true;
}
if self.txdata.len() > 0 {
if !self.txdata.is_empty() {
let coinbase = &self.txdata[0];
if coinbase.is_coin_base() {
// commitment is in the last output that starts with below magic

View File

@ -162,7 +162,7 @@ pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
/// Deserialize an object from a vector, will error if said deserialization
/// doesn't consume the entire vector.
pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> {
pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T, Error> {
let (rv, consumed) = deserialize_partial(data)?;
// Fail if data are not consumed entirely.
@ -175,8 +175,8 @@ pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result<T, Error> {
/// Deserialize an object from a vector, but will not report an error if said deserialization
/// doesn't consume the entire vector.
pub fn deserialize_partial<'a, T: Decodable>(
data: &'a [u8],
pub fn deserialize_partial<T: Decodable>(
data: &[u8],
) -> Result<(T, usize), Error> {
let mut decoder = Cursor::new(data);
let rv = Decodable::consensus_decode(&mut decoder)?;

View File

@ -41,9 +41,9 @@ const ONION : [u16; 3] = [0xFD87, 0xD87E, 0xEB43];
impl Address {
/// Create an address message for a socket
pub fn new (socket :&SocketAddr, services: ServiceFlags) -> Address {
let (address, port) = match socket {
&SocketAddr::V4(ref addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
&SocketAddr::V6(ref addr) => (addr.ip().segments(), addr.port())
let (address, port) = match *socket {
SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
SocketAddr::V6(addr) => (addr.ip().segments(), addr.port())
};
Address { address: address, port: port, services: services }
}

View File

@ -72,9 +72,7 @@ impl Encodable for CommandString {
if strbytes.len() > 12 {
return Err(encode::Error::UnrecognizedNetworkCommand(self.0.clone().into_owned()));
}
for x in 0..strbytes.len() {
rawbytes[x] = strbytes[x];
}
rawbytes[..strbytes.len()].clone_from_slice(&strbytes[..]);
rawbytes.consensus_encode(s)
}
}

View File

@ -18,16 +18,13 @@
//! # Example: creating a new address from a randomly-generated key pair
//!
//! ```rust
//! extern crate secp256k1;
//! extern crate bitcoin;
//!
//! use bitcoin::network::constants::Network;
//! use bitcoin::util::address::Address;
//! use bitcoin::util::key;
//! use secp256k1::Secp256k1;
//! use secp256k1::rand::thread_rng;
//! use bitcoin::secp256k1::Secp256k1;
//! use bitcoin::secp256k1::rand::thread_rng;
//!
//! fn main() {
//! // Generate random key pair
//! let s = Secp256k1::new();
//! let public_key = key::PublicKey {
@ -37,7 +34,6 @@
//!
//! // Generate pay-to-pubkey-hash address
//! let address = Address::p2pkh(&public_key, Network::Bitcoin);
//! }
//! ```
use std::fmt::{self, Display, Formatter};
@ -219,7 +215,7 @@ impl Payload {
assert!(ver.to_u8() <= 16);
let mut verop = ver.to_u8();
if verop > 0 {
verop = 0x50 + verop;
verop += 0x50;
}
script::Builder::new().push_opcode(verop.into()).push_slice(&prog)
}
@ -406,7 +402,7 @@ impl Display for Address {
/// Returns the same slice when no prefix is found.
fn find_bech32_prefix(bech32: &str) -> &str {
// Split at the last occurrence of the separator character '1'.
match bech32.rfind("1") {
match bech32.rfind('1') {
None => bech32,
Some(sep) => bech32.split_at(sep).0,
}
@ -427,7 +423,7 @@ impl FromStr for Address {
if let Some(network) = bech32_network {
// decode as bech32
let (_, payload) = bech32::decode(s)?;
if payload.len() == 0 {
if payload.is_empty() {
return Err(Error::EmptyBech32Payload);
}

View File

@ -19,6 +19,7 @@ use std::error;
use std::fmt::{self, Write};
use std::ops;
use std::str::FromStr;
use std::cmp::Ordering;
/// A set of denominations in which amounts can be expressed.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
@ -131,7 +132,7 @@ impl error::Error for ParseAmountError {
fn is_too_precise(s: &str, precision: usize) -> bool {
s.contains(".") || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0')
s.contains('.') || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0')
}
/// Parse decimal string in the given denomination into a satoshi value and a
@ -140,14 +141,14 @@ fn parse_signed_to_satoshi(
mut s: &str,
denom: Denomination,
) -> Result<(bool, u64), ParseAmountError> {
if s.len() == 0 {
if s.is_empty() {
return Err(ParseAmountError::InvalidFormat);
}
if s.len() > 50 {
return Err(ParseAmountError::InputTooLarge);
}
let is_negative = s.chars().next().unwrap() == '-';
let is_negative = s.starts_with('-');
if is_negative {
if s.len() == 1 {
return Err(ParseAmountError::InvalidFormat);
@ -229,13 +230,16 @@ fn fmt_satoshi_in(
f.write_str("-")?;
}
if denom.precision() > 0 {
let precision = denom.precision();
match precision.cmp(&0) {
Ordering::Greater => {
// add zeroes in the end
let width = denom.precision() as usize;
let width = precision as usize;
write!(f, "{}{:0width$}", satoshi, 0, width = width)?;
} else if denom.precision() < 0 {
}
Ordering::Less => {
// need to inject a comma in the number
let nb_decimals = denom.precision().abs() as usize;
let nb_decimals = precision.abs() as usize;
let real = format!("{:0width$}", satoshi, width = nb_decimals);
if real.len() == nb_decimals {
write!(f, "0.{}", &real[real.len() - nb_decimals..])?;
@ -247,9 +251,8 @@ fn fmt_satoshi_in(
&real[real.len() - nb_decimals..]
)?;
}
} else {
// denom.precision() == 0
write!(f, "{}", satoshi)?;
}
Ordering::Equal => write!(f, "{}", satoshi)?,
}
Ok(())
}
@ -327,7 +330,7 @@ impl Amount {
/// If you want to parse only the amount without the denomination,
/// use [from_str_in].
pub fn from_str_with_denomination(s: &str) -> Result<Amount, ParseAmountError> {
let mut split = s.splitn(3, " ");
let mut split = s.splitn(3, ' ');
let amt_str = split.next().unwrap();
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
if split.next().is_some() {
@ -614,7 +617,7 @@ impl SignedAmount {
return Err(ParseAmountError::TooBig);
}
Ok(match negative {
true => SignedAmount(-1 * satoshi as i64),
true => SignedAmount(-(satoshi as i64)),
false => SignedAmount(satoshi as i64),
})
}
@ -624,7 +627,7 @@ impl SignedAmount {
/// If you want to parse only the amount without the denomination,
/// use [from_str_in].
pub fn from_str_with_denomination(s: &str) -> Result<SignedAmount, ParseAmountError> {
let mut split = s.splitn(3, " ");
let mut split = s.splitn(3, ' ');
let amt_str = split.next().unwrap();
let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?;
if split.next().is_some() {

View File

@ -103,7 +103,7 @@ impl<T: Default + Copy> SmallVec<T> {
}
}
static BASE58_CHARS: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BASE58_CHARS: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BASE58_DIGITS: [Option<u8>; 128] = [
None, None, None, None, None, None, None, None, // 0-7

View File

@ -49,6 +49,8 @@ use std::collections::HashSet;
use std::error;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use std::cmp::Ordering;
use hashes::{Hash, siphash24};
use hash_types::{BlockHash, FilterHash};
@ -260,17 +262,17 @@ impl GCSFilterReader {
let mut remaining = n_elements.0 - 1;
for p in mapped {
loop {
if data == p {
return Ok(true);
} else if data < p {
match data.cmp(&p) {
Ordering::Equal => return Ok(true),
Ordering::Less => {
if remaining > 0 {
data += self.filter.golomb_rice_decode(&mut reader)?;
remaining -= 1;
} else {
return Ok(false);
}
} else {
break;
}
Ordering::Greater => break,
}
}
}
@ -301,17 +303,17 @@ impl GCSFilterReader {
let mut remaining = n_elements.0 - 1;
for p in mapped {
loop {
if data == p {
break;
} else if data < p {
match data.cmp(&p) {
Ordering::Equal => break,
Ordering::Less => {
if remaining > 0 {
data += self.filter.golomb_rice_decode(&mut reader)?;
remaining -= 1;
} else {
return Ok(false);
}
} else {
return Ok(false);
},
Ordering::Greater => return Ok(false),
}
}
}
@ -423,7 +425,7 @@ impl GCSFilter {
q += 1;
}
let r = reader.read(self.p)?;
return Ok((q << self.p) + r);
Ok((q << self.p) + r)
}
/// Hash an arbitrary slice with siphash using parameters of this filter

View File

@ -179,13 +179,11 @@ impl FromStr for ChildNumber {
type Err = Error;
fn from_str(inp: &str) -> Result<ChildNumber, Error> {
Ok(match inp.chars().last().map_or(false, |l| l == '\'' || l == 'h') {
true => ChildNumber::from_hardened_idx(
inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?
)?,
false => ChildNumber::from_normal_idx(
inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?
)?,
let is_hardened = inp.chars().last().map_or(false, |l| l == '\'' || l == 'h');
Ok(if is_hardened {
ChildNumber::from_hardened_idx(inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?)?
} else {
ChildNumber::from_normal_idx(inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?)?
})
}
}
@ -258,7 +256,7 @@ impl FromStr for DerivationPath {
type Err = Error;
fn from_str(path: &str) -> Result<DerivationPath, Error> {
let mut parts = path.split("/");
let mut parts = path.split('/');
// First parts must be `m`.
if parts.next().unwrap() != "m" {
return Err(Error::InvalidDerivationPathFormat);
@ -292,11 +290,7 @@ impl<'a> Iterator for DerivationPathIterator<'a> {
type Item = DerivationPath;
fn next(&mut self) -> Option<Self::Item> {
if self.next_child.is_none() {
return None;
}
let ret = self.next_child.unwrap();
let ret = self.next_child?;
self.next_child = ret.increment().ok();
Some(self.base.child(ret))
}

View File

@ -30,7 +30,7 @@ pub fn bitcoin_merkle_root_inline<T>(data: &mut [T]) -> T
<T as Hash>::Engine: io::Write,
{
// Base case
if data.len() < 1 {
if data.is_empty() {
return Default::default();
}
if data.len() < 2 {

View File

@ -25,12 +25,10 @@
//! # Examples
//!
//! ```rust
//! extern crate bitcoin;
//! use bitcoin::hash_types::Txid;
//! use bitcoin::hashes::hex::FromHex;
//! use bitcoin::{Block, MerkleBlock};
//!
//! # fn main() {
//! // Get the proof from a bitcoind by running in the terminal:
//! // $ TXID="5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2"
//! // $ bitcoin-cli gettxoutproof [\"$TXID\"]
@ -52,7 +50,6 @@
//! );
//! assert_eq!(1, index.len());
//! assert_eq!(1, index[0]);
//! # }
//! ```
use std::collections::HashSet;
@ -133,12 +130,10 @@ impl PartialMerkleTree {
/// # Examples
///
/// ```rust
/// extern crate bitcoin;
/// use bitcoin::hash_types::Txid;
/// use bitcoin::hashes::hex::FromHex;
/// use bitcoin::util::merkleblock::PartialMerkleTree;
///
/// # fn main() {
/// // Block 80000
/// let txids: Vec<Txid> = [
/// "c06fbab289f723c6261d3030ddb6be121f7d2508d77862bb1e484f5cd7f92b25",
@ -152,7 +147,6 @@ impl PartialMerkleTree {
/// let matches = vec![false, true];
/// let tree = PartialMerkleTree::from_txids(&txids, &matches);
/// assert!(tree.extract_matches(&mut vec![], &mut vec![]).is_ok());
/// # }
/// ```
pub fn from_txids(txids: &[Txid], matches: &[bool]) -> Self {
// We can never have zero txs in a merkle block, we always need the coinbase tx
@ -271,7 +265,7 @@ impl PartialMerkleTree {
if height == 0 || !parent_of_match {
// If at height 0, or nothing interesting below, store hash and stop
let hash = self.calc_hash(height, pos, txids);
self.hashes.push(hash.into());
self.hashes.push(hash);
} else {
// Otherwise, don't store any hash, but descend into the subtrees
self.traverse_and_build(height - 1, pos * 2, txids, matches);
@ -407,12 +401,10 @@ impl MerkleBlock {
/// # Examples
///
/// ```rust
/// extern crate bitcoin;
/// use bitcoin::hash_types::Txid;
/// use bitcoin::hashes::hex::FromHex;
/// use bitcoin::{Block, MerkleBlock};
///
/// # fn main() {
/// // Block 80000
/// let block_bytes = Vec::from_hex("01000000ba8b9cda965dd8e536670f9ddec10e53aab14b20bacad2\
/// 7b9137190000000000190760b278fe7b8565fda3b968b918d5fd997f993b23674c0af3b6fde300b38f33\
@ -437,7 +429,6 @@ impl MerkleBlock {
/// let mut index: Vec<u32> = vec![];
/// assert!(mb.extract_matches(&mut matches, &mut index).is_ok());
/// assert_eq!(txid, matches[0]);
/// # }
/// ```
pub fn from_block(block: &Block, match_txids: &HashSet<Txid>) -> Self {
let header = block.header;

View File

@ -20,14 +20,14 @@ use hashes::{sha256d, Hash};
use blockdata::opcodes;
use consensus::encode;
static MSG_SIGN_PREFIX: &'static [u8] = b"\x18Bitcoin Signed Message:\n";
static MSG_SIGN_PREFIX: &[u8] = b"\x18Bitcoin Signed Message:\n";
/// Search for `needle` in the vector `haystack` and remove every
/// instance of it, returning the number of instances removed.
/// Loops through the vector opcode by opcode, skipping pushed data.
pub fn script_find_and_remove(haystack: &mut Vec<u8>, needle: &[u8]) -> usize {
if needle.len() > haystack.len() { return 0; }
if needle.len() == 0 { return 0; }
if needle.is_empty() { return 0; }
let mut top = haystack.len() - needle.len();
let mut n_deleted = 0;

View File

@ -104,7 +104,7 @@ macro_rules! impl_psbtmap_consensus_enc_dec_oding {
macro_rules! impl_psbt_insert_pair {
($slf:ident.$unkeyed_name:ident <= <$raw_key:ident: _>|<$raw_value:ident: $unkeyed_value_type:ty>) => {
if $raw_key.key.is_empty() {
if let None = $slf.$unkeyed_name {
if $slf.$unkeyed_name.is_none() {
let val: $unkeyed_value_type = ::util::psbt::serialize::Deserialize::deserialize(&$raw_value)?;
$slf.$unkeyed_name = Some(val)