Skip to content

Commit 3022fef

Browse files
author
ChallengeDev210
committed
Merge rust-bitcoin/rust-bitcoin#1040: Introduce rustfmt in a non-invasive manner
ee9a3ec Enable formatter for "src" (Tobin C. Harding) 743b197 Add use for Unexpected (Tobin C. Harding) fd217e7 Use f instead of formatter (Tobin C. Harding) 7b50a96 Do not format prelude module (Tobin C. Harding) 01471f7 Shield hash_newtypes from rustfmt (Tobin C. Harding) 65d19d9 Refactor compile_error message (Tobin C. Harding) 6461e2d Run formatter on examples/ (Tobin C. Harding) fd1c658 Add a rustfmt configuration file with explicit ignores (Tobin C. Harding) Pull request description: Looks like we are getting to a place that rustfmt _might_ be able to be used. In an effort to introduce `rustfmt` without requiring devs to do excessively mundane reviews introduce `rustfmt` in a non-invasive manner. What this means is - Add a fully fleshed out `rustfmt` config file that explicitly ignores all the source files - Enable sections of code one by one so review is easier (including preparatory patches before doing each section). This PR currently does `examples` and all the source files at the root level of the crate (i.e. excludes all directories in `src/`). The other directories can then be done one at a time. Please see discussion on: rust-bitcoin/rust-bitcoin#959 for more context. ACKs for top commit: sanket1729: ACK ee9a3ec apoelstra: ACK ee9a3ec Tree-SHA512: f4ff3c031b5d685777e09bac2df59ed8217576b807da7699f44fe00aa509d0b7fe47617a8b3eff00d3125aeece3e010b8f9dd8733d315ccb2adc0e9a7d7f07e3
2 parents fb33515 + 854b310 commit 3022fef

File tree

8 files changed

+234
-160
lines changed

8 files changed

+234
-160
lines changed

examples/bip32.rs

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
extern crate bitcoin;
22

3-
use std::{env, process};
43
use std::str::FromStr;
4+
use std::{env, process};
55

6+
use bitcoin::hashes::hex::FromHex;
7+
use bitcoin::secp256k1::ffi::types::AlignedType;
68
use bitcoin::secp256k1::Secp256k1;
7-
use bitcoin::PublicKey;
8-
use bitcoin::util::bip32::ExtendedPrivKey;
9-
use bitcoin::util::bip32::ExtendedPubKey;
10-
use bitcoin::util::bip32::DerivationPath;
11-
use bitcoin::util::bip32::ChildNumber;
129
use bitcoin::util::address::Address;
13-
use bitcoin::secp256k1::ffi::types::AlignedType;
14-
use bitcoin::hashes::hex::FromHex;
10+
use bitcoin::util::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey};
11+
use bitcoin::PublicKey;
1512

1613
fn main() {
1714
// This example derives root xprv from a 32-byte seed,
@@ -55,10 +52,7 @@ fn main() {
5552
// generate first receiving address at m/0/0
5653
// manually creating indexes this time
5754
let zero = ChildNumber::from_normal_idx(0).unwrap();
58-
let public_key = xpub.derive_pub(&secp, &vec![zero, zero])
59-
.unwrap()
60-
.public_key;
55+
let public_key = xpub.derive_pub(&secp, &vec![zero, zero]).unwrap().public_key;
6156
let address = Address::p2wpkh(&PublicKey::new(public_key), network).unwrap();
6257
println!("First receiving address: {}", address);
63-
6458
}

examples/handshake.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
extern crate bitcoin;
22

3+
use std::io::{BufReader, Write};
34
use std::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, TcpStream};
45
use std::time::{SystemTime, UNIX_EPOCH};
56
use std::{env, process};
6-
use std::io::{Write, BufReader};
77

88
use bitcoin::consensus::{encode, Decodable};
99
use bitcoin::network::{address, constants, message, message_network};
@@ -80,10 +80,7 @@ fn build_version_message(address: SocketAddr) -> message::NetworkMessage {
8080
let services = constants::ServiceFlags::NONE;
8181

8282
// "standard UNIX timestamp in seconds"
83-
let timestamp = SystemTime::now()
84-
.duration_since(UNIX_EPOCH)
85-
.expect("Time error")
86-
.as_secs();
83+
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time error").as_secs();
8784

8885
// "The network address of the node receiving this message"
8986
let addr_recv = address::Address::new(&address, constants::ServiceFlags::NONE);

rustfmt.toml

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,85 @@
1-
disable_all_formatting = true
1+
# Eventually this shoud be: ignore = []
2+
ignore = [
3+
"src/blockdata",
4+
"src/consensus",
5+
"src/network",
6+
"src/util",
7+
]
8+
9+
hard_tabs = false
10+
tab_spaces = 4
11+
newline_style = "Auto"
12+
indent_style = "Block"
13+
14+
max_width = 100 # This is number of characters.
15+
# `use_small_heuristics` is ignored if the granular width config values are explicitly set.
16+
use_small_heuristics = "Max" # "Max" == All granular width settings same as `max_width`.
17+
# # Granular width configuration settings. These are percentages of `max_width`.
18+
# fn_call_width = 60
19+
# attr_fn_like_width = 70
20+
# struct_lit_width = 18
21+
# struct_variant_width = 35
22+
# array_width = 60
23+
# chain_width = 60
24+
# single_line_if_else_max_width = 50
25+
26+
wrap_comments = false
27+
format_code_in_doc_comments = false
28+
comment_width = 100 # Default 80
29+
normalize_comments = false
30+
normalize_doc_attributes = false
31+
format_strings = false
32+
format_macro_matchers = false
33+
format_macro_bodies = true
34+
hex_literal_case = "Preserve"
35+
empty_item_single_line = true
36+
struct_lit_single_line = true
37+
fn_single_line = true # Default false
38+
where_single_line = false
39+
imports_indent = "Block"
40+
imports_layout = "Mixed"
41+
imports_granularity = "Module" # Default "Preserve"
42+
group_imports = "StdExternalCrate" # Default "Preserve"
43+
reorder_imports = true
44+
reorder_modules = true
45+
reorder_impl_items = false
46+
type_punctuation_density = "Wide"
47+
space_before_colon = false
48+
space_after_colon = true
49+
spaces_around_ranges = false
50+
binop_separator = "Front"
51+
remove_nested_parens = true
52+
combine_control_expr = true
53+
overflow_delimited_expr = false
54+
struct_field_align_threshold = 0
55+
enum_discrim_align_threshold = 0
56+
match_arm_blocks = false # Default true
57+
match_arm_leading_pipes = "Never"
58+
force_multiline_blocks = false
59+
fn_args_layout = "Tall"
60+
brace_style = "SameLineWhere"
61+
control_brace_style = "AlwaysSameLine"
62+
trailing_semicolon = true
63+
trailing_comma = "Vertical"
64+
match_block_trailing_comma = false
65+
blank_lines_upper_bound = 1
66+
blank_lines_lower_bound = 0
67+
edition = "2018"
68+
version = "One"
69+
inline_attribute_width = 0
70+
format_generated_files = true
71+
merge_derives = true
72+
use_try_shorthand = false
73+
use_field_init_shorthand = false
74+
force_explicit_abi = true
75+
condense_wildcard_suffixes = false
76+
color = "Auto"
77+
required_version = "1.5.1"
78+
unstable_features = false
79+
disable_all_formatting = false
80+
skip_children = false
81+
hide_parse_errors = false
82+
error_on_line_overflow = false
83+
error_on_unformatted = false
84+
emit_mode = "Files"
85+
make_backup = false

src/hash_types.rs

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
//! hash).
1010
//!
1111
12-
use bitcoin_hashes::{sha256, sha256d, hash160, hash_newtype};
13-
12+
#[rustfmt::skip]
1413
macro_rules! impl_hashencode {
1514
($hashtype:ident) => {
1615
impl $crate::consensus::Encodable for $hashtype {
@@ -25,43 +24,50 @@ macro_rules! impl_hashencode {
2524
Ok(Self::from_inner(<<$hashtype as $crate::hashes::Hash>::Inner>::consensus_decode(r)?))
2625
}
2726
}
28-
}
27+
};
2928
}
3029

31-
hash_newtype!(
32-
Txid, sha256d::Hash, 32, doc="A bitcoin transaction hash/transaction ID.
30+
// newtypes module is solely here so we can rustfmt::skip.
31+
pub use newtypes::*;
32+
33+
#[rustfmt::skip]
34+
mod newtypes {
35+
use crate::hashes::{sha256, sha256d, hash160, hash_newtype};
36+
37+
hash_newtype!(
38+
Txid, sha256d::Hash, 32, doc="A bitcoin transaction hash/transaction ID.
3339
3440
For compatibility with the existing Bitcoin infrastructure and historical
3541
and current versions of the Bitcoin Core software itself, this and
3642
other [`sha256d::Hash`] types, are serialized in reverse
3743
byte order when converted to a hex string via [`std::fmt::Display`] trait operations.
3844
See [`hashes::Hash::DISPLAY_BACKWARD`] for more details.
3945
");
40-
hash_newtype!(Wtxid, sha256d::Hash, 32, doc="A bitcoin witness transaction ID.");
41-
hash_newtype!(BlockHash, sha256d::Hash, 32, doc="A bitcoin block hash.");
42-
hash_newtype!(Sighash, sha256d::Hash, 32, doc="Hash of the transaction according to the signature algorithm");
46+
hash_newtype!(Wtxid, sha256d::Hash, 32, doc="A bitcoin witness transaction ID.");
47+
hash_newtype!(BlockHash, sha256d::Hash, 32, doc="A bitcoin block hash.");
48+
hash_newtype!(Sighash, sha256d::Hash, 32, doc="Hash of the transaction according to the signature algorithm");
4349

44-
hash_newtype!(PubkeyHash, hash160::Hash, 20, doc="A hash of a public key.");
45-
hash_newtype!(ScriptHash, hash160::Hash, 20, doc="A hash of Bitcoin Script bytecode.");
46-
hash_newtype!(WPubkeyHash, hash160::Hash, 20, doc="SegWit version of a public key hash.");
47-
hash_newtype!(WScriptHash, sha256::Hash, 32, doc="SegWit version of a Bitcoin Script bytecode hash.");
50+
hash_newtype!(PubkeyHash, hash160::Hash, 20, doc="A hash of a public key.");
51+
hash_newtype!(ScriptHash, hash160::Hash, 20, doc="A hash of Bitcoin Script bytecode.");
52+
hash_newtype!(WPubkeyHash, hash160::Hash, 20, doc="SegWit version of a public key hash.");
53+
hash_newtype!(WScriptHash, sha256::Hash, 32, doc="SegWit version of a Bitcoin Script bytecode hash.");
4854

49-
hash_newtype!(TxMerkleNode, sha256d::Hash, 32, doc="A hash of the Merkle tree branch or root for transactions");
50-
hash_newtype!(WitnessMerkleNode, sha256d::Hash, 32, doc="A hash corresponding to the Merkle tree root for witness data");
51-
hash_newtype!(WitnessCommitment, sha256d::Hash, 32, doc="A hash corresponding to the witness structure commitment in the coinbase transaction");
52-
hash_newtype!(XpubIdentifier, hash160::Hash, 20, doc="XpubIdentifier as defined in BIP-32.");
55+
hash_newtype!(TxMerkleNode, sha256d::Hash, 32, doc="A hash of the Merkle tree branch or root for transactions");
56+
hash_newtype!(WitnessMerkleNode, sha256d::Hash, 32, doc="A hash corresponding to the Merkle tree root for witness data");
57+
hash_newtype!(WitnessCommitment, sha256d::Hash, 32, doc="A hash corresponding to the witness structure commitment in the coinbase transaction");
58+
hash_newtype!(XpubIdentifier, hash160::Hash, 20, doc="XpubIdentifier as defined in BIP-32.");
5359

54-
hash_newtype!(FilterHash, sha256d::Hash, 32, doc="Filter hash, as defined in BIP-157");
55-
hash_newtype!(FilterHeader, sha256d::Hash, 32, doc="Filter header, as defined in BIP-157");
60+
hash_newtype!(FilterHash, sha256d::Hash, 32, doc="Filter hash, as defined in BIP-157");
61+
hash_newtype!(FilterHeader, sha256d::Hash, 32, doc="Filter header, as defined in BIP-157");
5662

63+
impl_hashencode!(Txid);
64+
impl_hashencode!(Wtxid);
65+
impl_hashencode!(BlockHash);
66+
impl_hashencode!(Sighash);
5767

58-
impl_hashencode!(Txid);
59-
impl_hashencode!(Wtxid);
60-
impl_hashencode!(BlockHash);
61-
impl_hashencode!(Sighash);
68+
impl_hashencode!(TxMerkleNode);
69+
impl_hashencode!(WitnessMerkleNode);
6270

63-
impl_hashencode!(TxMerkleNode);
64-
impl_hashencode!(WitnessMerkleNode);
65-
66-
impl_hashencode!(FilterHash);
67-
impl_hashencode!(FilterHeader);
71+
impl_hashencode!(FilterHash);
72+
impl_hashencode!(FilterHeader);
73+
}

src/internal_macros.rs

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,9 @@ macro_rules! impl_array_newtype {
100100
type Output = <[$ty] as core::ops::Index<I>>::Output;
101101

102102
#[inline]
103-
fn index(&self, index: I) -> &Self::Output {
104-
&self.0[index]
105-
}
103+
fn index(&self, index: I) -> &Self::Output { &self.0[index] }
106104
}
107-
}
105+
};
108106
}
109107

110108
macro_rules! display_from_debug {
@@ -114,7 +112,7 @@ macro_rules! display_from_debug {
114112
core::fmt::Debug::fmt(self, f)
115113
}
116114
}
117-
}
115+
};
118116
}
119117

120118
#[cfg(test)]
@@ -142,8 +140,8 @@ macro_rules! serde_string_impl {
142140
impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
143141
type Value = $name;
144142

145-
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
146-
formatter.write_str($expecting)
143+
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
144+
f.write_str($expecting)
147145
}
148146

149147
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
@@ -190,8 +188,8 @@ macro_rules! serde_struct_human_string_impl {
190188
impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
191189
type Value = $name;
192190

193-
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
194-
formatter.write_str($expecting)
191+
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
192+
f.write_str($expecting)
195193
}
196194

197195
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
@@ -215,8 +213,8 @@ macro_rules! serde_struct_human_string_impl {
215213
impl<'de> $crate::serde::de::Visitor<'de> for EnumVisitor {
216214
type Value = Enum;
217215

218-
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
219-
formatter.write_str("a field name")
216+
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
217+
f.write_str("a field name")
220218
}
221219

222220
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
@@ -246,8 +244,8 @@ macro_rules! serde_struct_human_string_impl {
246244
impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
247245
type Value = $name;
248246

249-
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
250-
formatter.write_str("a struct")
247+
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
248+
f.write_str("a struct")
251249
}
252250

253251
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
@@ -352,8 +350,7 @@ macro_rules! serde_struct_human_string_impl {
352350
/// - core::str::FromStr
353351
/// - hashes::hex::FromHex
354352
macro_rules! impl_bytes_newtype {
355-
($t:ident, $len:literal) => (
356-
353+
($t:ident, $len:literal) => {
357354
impl core::fmt::LowerHex for $t {
358355
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
359356
for &ch in self.0.iter() {
@@ -378,9 +375,9 @@ macro_rules! impl_bytes_newtype {
378375
impl $crate::hashes::hex::FromHex for $t {
379376
fn from_byte_iter<I>(iter: I) -> Result<Self, $crate::hashes::hex::Error>
380377
where
381-
I: core::iter::Iterator<Item=Result<u8, $crate::hashes::hex::Error>>
382-
+ core::iter::ExactSizeIterator
383-
+ core::iter::DoubleEndedIterator,
378+
I: core::iter::Iterator<Item = Result<u8, $crate::hashes::hex::Error>>
379+
+ core::iter::ExactSizeIterator
380+
+ core::iter::DoubleEndedIterator,
384381
{
385382
if iter.len() == $len {
386383
let mut ret = [0; $len];
@@ -423,18 +420,20 @@ macro_rules! impl_bytes_newtype {
423420
impl<'de> $crate::serde::de::Visitor<'de> for HexVisitor {
424421
type Value = $t;
425422

426-
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
427-
formatter.write_str("an ASCII hex string")
423+
fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
424+
f.write_str("an ASCII hex string")
428425
}
429426

430427
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
431428
where
432429
E: $crate::serde::de::Error,
433430
{
431+
use $crate::serde::de::Unexpected;
432+
434433
if let Ok(hex) = core::str::from_utf8(v) {
435434
$crate::hashes::hex::FromHex::from_hex(hex).map_err(E::custom)
436435
} else {
437-
return Err(E::invalid_value($crate::serde::de::Unexpected::Bytes(v), &self));
436+
return Err(E::invalid_value(Unexpected::Bytes(v), &self));
438437
}
439438
}
440439

@@ -453,8 +452,8 @@ macro_rules! impl_bytes_newtype {
453452
impl<'de> $crate::serde::de::Visitor<'de> for BytesVisitor {
454453
type Value = $t;
455454

456-
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
457-
formatter.write_str("a bytestring")
455+
fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
456+
f.write_str("a bytestring")
458457
}
459458

460459
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
@@ -475,7 +474,7 @@ macro_rules! impl_bytes_newtype {
475474
}
476475
}
477476
}
478-
)
477+
};
479478
}
480479

481480
macro_rules! user_enum {
@@ -531,8 +530,8 @@ macro_rules! user_enum {
531530
impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
532531
type Value = $name;
533532

534-
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
535-
formatter.write_str("an enum value")
533+
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
534+
f.write_str("an enum value")
536535
}
537536

538537
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
@@ -586,9 +585,7 @@ macro_rules! write_err {
586585

587586
/// Asserts a boolean expression at compile time.
588587
macro_rules! const_assert {
589-
($x:expr) => {
590-
{
591-
const _: [(); 0 - !$x as usize] = [];
592-
}
593-
};
588+
($x:expr) => {{
589+
const _: [(); 0 - !$x as usize] = [];
590+
}};
594591
}

0 commit comments

Comments
 (0)