From 062193ceb59fc3128a93f4503d2564e3b4a5657b Mon Sep 17 00:00:00 2001 From: Tomusdrw Date: Tue, 19 Jan 2016 12:14:29 +0100 Subject: [PATCH] Fixing clippy errors in util --- README.md | 4 +++ util/src/bytes.rs | 14 +++++------ util/src/chainfilter.rs | 7 +++--- util/src/hash.rs | 26 +++++++++---------- util/src/io/service.rs | 12 ++++----- util/src/json_aid.rs | 22 ++++++++-------- util/src/lib.rs | 1 + util/src/misc.rs | 6 ++--- util/src/network/connection.rs | 9 +++---- util/src/network/discovery.rs | 13 +++++----- util/src/network/handshake.rs | 18 +++++-------- util/src/network/host.rs | 46 +++++++++++++++++----------------- util/src/network/node.rs | 6 +++-- util/src/network/session.rs | 4 +-- util/src/overlaydb.rs | 11 +++----- util/src/rlp/rlpstream.rs | 6 ++--- util/src/rlp/rlptraits.rs | 6 ++--- util/src/rlp/untrusted_rlp.rs | 9 ++++--- util/src/squeeze.rs | 4 +-- util/src/trie/triedb.rs | 12 ++++----- util/src/trie/triedbmut.rs | 15 ++++++----- util/src/uint.rs | 14 +++++------ 22 files changed, 128 insertions(+), 137 deletions(-) diff --git a/README.md b/README.md index 216ac8091..48172bb60 100644 --- a/README.md +++ b/README.md @@ -1 +1,5 @@ # ethcore + + +# Running clippy + diff --git a/util/src/bytes.rs b/util/src/bytes.rs index 479a91df0..a954d8acd 100644 --- a/util/src/bytes.rs +++ b/util/src/bytes.rs @@ -99,18 +99,18 @@ impl<'a> Deref for BytesRef<'a> { type Target = [u8]; fn deref(&self) -> &[u8] { - match self { - &BytesRef::Flexible(ref bytes) => bytes, - &BytesRef::Fixed(ref bytes) => bytes + match *self { + BytesRef::Flexible(ref bytes) => bytes, + BytesRef::Fixed(ref bytes) => bytes } } } impl <'a> DerefMut for BytesRef<'a> { fn deref_mut(&mut self) -> &mut [u8] { - match self { - &mut BytesRef::Flexible(ref mut bytes) => bytes, - &mut BytesRef::Fixed(ref mut bytes) => bytes + match *self { + BytesRef::Flexible(ref mut bytes) => bytes, + BytesRef::Fixed(ref mut bytes) => bytes } } } @@ -283,7 +283,7 @@ pub trait FromBytes: Sized { impl FromBytes for String { fn from_bytes(bytes: &[u8]) -> FromBytesResult { - Ok(::std::str::from_utf8(bytes).unwrap().to_string()) + Ok(::std::str::from_utf8(bytes).unwrap().to_owned()) } } diff --git a/util/src/chainfilter.rs b/util/src/chainfilter.rs index e1804c191..386664837 100644 --- a/util/src/chainfilter.rs +++ b/util/src/chainfilter.rs @@ -321,10 +321,9 @@ impl<'a, D> ChainFilter<'a, D> where D: FilterDataSource let offset = level_size * index; // go doooown! - match self.blocks(bloom, from_block, to_block, max_level, offset) { - Some(blocks) => result.extend(blocks), - None => () - }; + if let Some(blocks) = self.blocks(bloom, from_block, to_block, max_level, offset) { + result.extend(blocks); + } } result diff --git a/util/src/hash.rs b/util/src/hash.rs index 17057ef07..793924f8f 100644 --- a/util/src/hash.rs +++ b/util/src/hash.rs @@ -193,11 +193,11 @@ macro_rules! impl_hash { impl FromJson for $from { fn from_json(json: &Json) -> Self { - match json { - &Json::String(ref s) => { + match *json { + Json::String(ref s) => { match s.len() % 2 { 0 => FromStr::from_str(clean_0x(s)).unwrap(), - _ => FromStr::from_str(&("0".to_string() + &(clean_0x(s).to_string()))[..]).unwrap() + _ => FromStr::from_str(&("0".to_owned() + &(clean_0x(s).to_owned()))[..]).unwrap() } }, _ => Default::default(), @@ -207,7 +207,7 @@ macro_rules! impl_hash { impl fmt::Debug for $from { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - for i in self.0.iter() { + for i in &self.0[..] { try!(write!(f, "{:02x}", i)); } Ok(()) @@ -215,11 +215,11 @@ macro_rules! impl_hash { } impl fmt::Display for $from { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - for i in self.0[0..2].iter() { + for i in &self.0[0..2] { try!(write!(f, "{:02x}", i)); } try!(write!(f, "…")); - for i in self.0[$size - 4..$size].iter() { + for i in &self.0[$size - 4..$size] { try!(write!(f, "{:02x}", i)); } Ok(()) @@ -277,36 +277,36 @@ macro_rules! impl_hash { impl Index for $from { type Output = u8; - fn index<'a>(&'a self, index: usize) -> &'a u8 { + fn index(&self, index: usize) -> &u8 { &self.0[index] } } impl IndexMut for $from { - fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut u8 { + fn index_mut(&mut self, index: usize) -> &mut u8 { &mut self.0[index] } } impl Index> for $from { type Output = [u8]; - fn index<'a>(&'a self, index: ops::Range) -> &'a [u8] { + fn index(&self, index: ops::Range) -> &[u8] { &self.0[index] } } impl IndexMut> for $from { - fn index_mut<'a>(&'a mut self, index: ops::Range) -> &'a mut [u8] { + fn index_mut(&mut self, index: ops::Range) -> &mut [u8] { &mut self.0[index] } } impl Index for $from { type Output = [u8]; - fn index<'a>(&'a self, _index: ops::RangeFull) -> &'a [u8] { + fn index(&self, _index: ops::RangeFull) -> &[u8] { &self.0 } } impl IndexMut for $from { - fn index_mut<'a>(&'a mut self, _index: ops::RangeFull) -> &'a mut [u8] { + fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] { &mut self.0 } } @@ -424,7 +424,7 @@ macro_rules! impl_hash { fn from(s: &'_ str) -> $from { use std::str::FromStr; if s.len() % 2 == 1 { - $from::from_str(&("0".to_string() + &(clean_0x(s).to_string()))[..]).unwrap_or($from::new()) + $from::from_str(&("0".to_owned() + &(clean_0x(s).to_owned()))[..]).unwrap_or($from::new()) } else { $from::from_str(clean_0x(s)).unwrap_or($from::new()) } diff --git a/util/src/io/service.rs b/util/src/io/service.rs index 4a96d19a7..537f26b8f 100644 --- a/util/src/io/service.rs +++ b/util/src/io/service.rs @@ -93,17 +93,17 @@ impl Handler for IoManager where Message: Send + 'static { fn ready(&mut self, event_loop: &mut EventLoop, token: Token, events: EventSet) { if events.is_hup() { - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.stream_hup(&mut IoContext::new(event_loop, &mut self.timers), token.as_usize()); } } else if events.is_readable() { - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.stream_readable(&mut IoContext::new(event_loop, &mut self.timers), token.as_usize()); } } else if events.is_writable() { - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.stream_writable(&mut IoContext::new(event_loop, &mut self.timers), token.as_usize()); } } @@ -116,13 +116,13 @@ impl Handler for IoManager where Message: Send + 'static { let timer = self.timers.get_mut(token).expect("Unknown user timer token"); timer.delay }; - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.timeout(&mut IoContext::new(event_loop, &mut self.timers), token.as_usize()); } event_loop.timeout_ms(token, delay).expect("Error re-registering user timer"); } _ => { // Just pass the event down. IoHandler is supposed to re-register it if required. - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.timeout(&mut IoContext::new(event_loop, &mut self.timers), token.as_usize()); } } @@ -140,7 +140,7 @@ impl Handler for IoManager where Message: Send + 'static { self.handlers.last_mut().unwrap().initialize(&mut IoContext::new(event_loop, &mut self.timers)); }, IoMessage::UserMessage(ref mut data) => { - for h in self.handlers.iter_mut() { + for h in &mut self.handlers { h.message(&mut IoContext::new(event_loop, &mut self.timers), data); } } diff --git a/util/src/json_aid.rs b/util/src/json_aid.rs index 79a71cac6..417017c31 100644 --- a/util/src/json_aid.rs +++ b/util/src/json_aid.rs @@ -18,10 +18,10 @@ fn u256_from_str(s: &str) -> U256 { impl FromJson for Bytes { fn from_json(json: &Json) -> Self { - match json { - &Json::String(ref s) => match s.len() % 2 { + match *json { + Json::String(ref s) => match s.len() % 2 { 0 => FromHex::from_hex(clean(s)).unwrap_or(vec![]), - _ => FromHex::from_hex(&("0".to_string() + &(clean(s).to_string()))[..]).unwrap_or(vec![]), + _ => FromHex::from_hex(&("0".to_owned() + &(clean(s).to_owned()))[..]).unwrap_or(vec![]), }, _ => vec![], } @@ -30,8 +30,8 @@ impl FromJson for Bytes { impl FromJson for BTreeMap { fn from_json(json: &Json) -> Self { - match json { - &Json::Object(ref o) => o.iter().map(|(key, value)| (x!(&u256_from_str(key)), x!(&U256::from_json(value)))).collect(), + match *json { + Json::Object(ref o) => o.iter().map(|(key, value)| (x!(&u256_from_str(key)), x!(&U256::from_json(value)))).collect(), _ => BTreeMap::new(), } } @@ -39,8 +39,8 @@ impl FromJson for BTreeMap { impl FromJson for Vec where T: FromJson { fn from_json(json: &Json) -> Self { - match json { - &Json::Array(ref o) => o.iter().map(|x|T::from_json(x)).collect(), + match *json { + Json::Array(ref o) => o.iter().map(|x|T::from_json(x)).collect(), _ => Vec::new(), } } @@ -48,9 +48,9 @@ impl FromJson for Vec where T: FromJson { impl FromJson for Option where T: FromJson { fn from_json(json: &Json) -> Self { - match json { - &Json::String(ref o) if o.is_empty() => None, - &Json::Null => None, + match *json { + Json::String(ref o) if o.is_empty() => None, + Json::Null => None, _ => Some(FromJson::from_json(json)), } } @@ -134,4 +134,4 @@ fn option_types() { assert_eq!(None, v); let v: Option = xjson!(&j["empty"]); assert_eq!(None, v); -} \ No newline at end of file +} diff --git a/util/src/lib.rs b/util/src/lib.rs index 4bc47e61c..ffa091c37 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -2,6 +2,7 @@ #![feature(augmented_assignments)] #![feature(associated_consts)] #![feature(wrapping)] +#![allow(needless_range_loop, match_bool)] //! Ethcore-util library //! //! ### Rust version: diff --git a/util/src/misc.rs b/util/src/misc.rs index e5efd33bb..d540ccf5b 100644 --- a/util/src/misc.rs +++ b/util/src/misc.rs @@ -14,13 +14,13 @@ impl Diff where T: Eq { pub fn new(pre: T, post: T) -> Self { if pre == post { Diff::Same } else { Diff::Changed(pre, post) } } /// Get the before value, if there is one. - pub fn pre(&self) -> Option<&T> { match self { &Diff::Died(ref x) | &Diff::Changed(ref x, _) => Some(x), _ => None } } + pub fn pre(&self) -> Option<&T> { match *self { Diff::Died(ref x) | Diff::Changed(ref x, _) => Some(x), _ => None } } /// Get the after value, if there is one. - pub fn post(&self) -> Option<&T> { match self { &Diff::Born(ref x) | &Diff::Changed(_, ref x) => Some(x), _ => None } } + pub fn post(&self) -> Option<&T> { match *self { Diff::Born(ref x) | Diff::Changed(_, ref x) => Some(x), _ => None } } /// Determine whether there was a change or not. - pub fn is_same(&self) -> bool { match self { &Diff::Same => true, _ => false }} + pub fn is_same(&self) -> bool { match *self { Diff::Same => true, _ => false }} } #[derive(PartialEq,Eq,Clone,Copy)] diff --git a/util/src/network/connection.rs b/util/src/network/connection.rs index f11c10384..6127cf838 100644 --- a/util/src/network/connection.rs +++ b/util/src/network/connection.rs @@ -86,7 +86,7 @@ impl Connection { /// Add a packet to send queue. pub fn send(&mut self, data: Bytes) { - if data.len() != 0 { + if !data.is_empty() { self.send_queue.push_back(Cursor::new(data)); } if !self.interest.is_writable() { @@ -341,11 +341,8 @@ impl EncryptedConnection { self.idle_timeout.map(|t| event_loop.clear_timeout(t)); match self.read_state { EncryptedConnectionState::Header => { - match try!(self.connection.readable()) { - Some(data) => { - try!(self.read_header(&data)); - }, - None => {} + if let Some(data) = try!(self.connection.readable()) { + try!(self.read_header(&data)); }; Ok(None) }, diff --git a/util/src/network/discovery.rs b/util/src/network/discovery.rs index d2a4f21a2..1f2bd4e06 100644 --- a/util/src/network/discovery.rs +++ b/util/src/network/discovery.rs @@ -62,7 +62,7 @@ impl Discovery { discovery_round: 0, discovery_id: NodeId::new(), discovery_nodes: HashSet::new(), - node_buckets: (0..NODE_BINS).map(|x| NodeBucket::new(x)).collect(), + node_buckets: (0..NODE_BINS).map(NodeBucket::new).collect(), } } @@ -122,7 +122,8 @@ impl Discovery { ret } - fn nearest_node_entries<'b>(source: &NodeId, target: &NodeId, buckets: &'b Vec) -> Vec<&'b NodeId> + #[allow(cyclomatic_complexity)] + fn nearest_node_entries<'b>(source: &NodeId, target: &NodeId, buckets: &'b [NodeBucket]) -> Vec<&'b NodeId> { // send ALPHA FindNode packets to nodes we know, closest to target const LAST_BIN: u32 = NODE_BINS - 1; @@ -136,7 +137,7 @@ impl Discovery { if head > 1 && tail != LAST_BIN { while head != tail && head < NODE_BINS && count < BUCKET_SIZE { - for n in buckets[head as usize].nodes.iter() + for n in &buckets[head as usize].nodes { if count < BUCKET_SIZE { count += 1; @@ -147,7 +148,7 @@ impl Discovery { } } if count < BUCKET_SIZE && tail != 0 { - for n in buckets[tail as usize].nodes.iter() { + for n in &buckets[tail as usize].nodes { if count < BUCKET_SIZE { count += 1; found.entry(Discovery::distance(target, &n)).or_insert(Vec::new()).push(n); @@ -166,7 +167,7 @@ impl Discovery { } else if head < 2 { while head < NODE_BINS && count < BUCKET_SIZE { - for n in buckets[head as usize].nodes.iter() { + for n in &buckets[head as usize].nodes { if count < BUCKET_SIZE { count += 1; found.entry(Discovery::distance(target, &n)).or_insert(Vec::new()).push(n); @@ -180,7 +181,7 @@ impl Discovery { } else { while tail > 0 && count < BUCKET_SIZE { - for n in buckets[tail as usize].nodes.iter() { + for n in &buckets[tail as usize].nodes { if count < BUCKET_SIZE { count += 1; found.entry(Discovery::distance(target, &n)).or_insert(Vec::new()).push(n); diff --git a/util/src/network/handshake.rs b/util/src/network/handshake.rs index ca95808b4..e7a669e25 100644 --- a/util/src/network/handshake.rs +++ b/util/src/network/handshake.rs @@ -93,21 +93,15 @@ impl Handshake { self.idle_timeout.map(|t| event_loop.clear_timeout(t)); match self.state { HandshakeState::ReadingAuth => { - match try!(self.connection.readable()) { - Some(data) => { - try!(self.read_auth(host, &data)); - try!(self.write_ack()); - }, - None => {} + if let Some(data) = try!(self.connection.readable()) { + try!(self.read_auth(host, &data)); + try!(self.write_ack()); }; }, HandshakeState::ReadingAck => { - match try!(self.connection.readable()) { - Some(data) => { - try!(self.read_ack(host, &data)); - self.state = HandshakeState::StartSession; - }, - None => {} + if let Some(data) = try!(self.connection.readable()) { + try!(self.read_ack(host, &data)); + self.state = HandshakeState::StartSession; }; }, _ => { panic!("Unexpected state"); } diff --git a/util/src/network/host.rs b/util/src/network/host.rs index 37b58f1f0..060fd5217 100644 --- a/util/src/network/host.rs +++ b/util/src/network/host.rs @@ -175,7 +175,7 @@ impl<'s, 'io, Message> NetworkContext<'s, 'io, Message> where Message: Send + 's s.info.client_version.clone() }, _ => { - "unknown".to_string() + "unknown".to_owned() } } } @@ -213,7 +213,7 @@ impl HostInfo { /// Increments and returns connection nonce. pub fn next_nonce(&mut self) -> H256 { self.nonce = self.nonce.sha3(); - return self.nonce.clone(); + self.nonce.clone() } } @@ -246,7 +246,7 @@ impl Host where Message: Send { config: config, nonce: H256::random(), protocol_version: 4, - client_version: "parity".to_string(), + client_version: "parity".to_owned(), listen_port: 0, capabilities: Vec::new(), }, @@ -274,11 +274,11 @@ impl Host where Message: Send { } fn have_session(&self, id: &NodeId) -> bool { - self.connections.iter().any(|e| match e { &ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false }) + self.connections.iter().any(|e| match *e { ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false }) } fn connecting_to(&self, id: &NodeId) -> bool { - self.connections.iter().any(|e| match e { &ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false }) + self.connections.iter().any(|e| match *e { ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false }) } fn connect_peers(&mut self, io: &mut IoContext>) { @@ -303,7 +303,7 @@ impl Host where Message: Send { } } - for n in to_connect.iter() { + for n in &to_connect { if n.peer_type == PeerType::Required { if req_conn < IDEAL_PEERS { self.connect_peer(&n.id, io); @@ -318,7 +318,7 @@ impl Host where Message: Send { let peer_count = 0; let mut open_slots = IDEAL_PEERS - peer_count - pending_count + req_conn; if open_slots > 0 { - for n in to_connect.iter() { + for n in &to_connect { if n.peer_type == PeerType::Optional && open_slots > 0 { open_slots -= 1; self.connect_peer(&n.id, io); @@ -328,6 +328,7 @@ impl Host where Message: Send { } } + #[allow(single_match)] fn connect_peer(&mut self, id: &NodeId, io: &mut IoContext>) { if self.have_session(id) { @@ -376,6 +377,7 @@ impl Host where Message: Send { trace!(target: "net", "accept"); } + #[allow(single_match)] fn connection_writable<'s>(&'s mut self, token: StreamToken, io: &mut IoContext<'s, NetworkIoMessage>) { let mut kill = false; let mut create_session = false; @@ -436,7 +438,7 @@ impl Host where Message: Send { }) }; match sd { SessionData::Ready => { - for (p, _) in self.handlers.iter_mut() { + for (p, _) in &mut self.handlers { if s.have_capability(p) { ready_data.push(p); } @@ -475,11 +477,8 @@ impl Host where Message: Send { h.read(&mut NetworkContext::new(io, p, Some(token), &mut self.connections, &mut self.timers), &token, packet_id, &data[1..]); } - match self.connections.get_mut(token) { - Some(&mut ConnectionEntry::Session(ref mut s)) => { - s.reregister(io.event_loop).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e)); - }, - _ => (), + if let Some(&mut ConnectionEntry::Session(ref mut s)) = self.connections.get_mut(token) { + s.reregister(io.event_loop).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e)); } } @@ -523,7 +522,7 @@ impl Host where Message: Send { match self.connections.get_mut(token) { Some(&mut ConnectionEntry::Handshake(_)) => (), // just abandon handshake Some(&mut ConnectionEntry::Session(ref mut s)) if s.is_ready() => { - for (p, _) in self.handlers.iter_mut() { + for (p, _) in &mut self.handlers { if s.have_capability(p) { to_disconnect.push(p); } @@ -600,19 +599,20 @@ impl IoHandler> for Host where Messa FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, io), NODETABLE_DISCOVERY => {}, NODETABLE_MAINTAIN => {}, - _ => match self.timers.get_mut(&token).map(|p| *p) { - Some(protocol) => match self.handlers.get_mut(protocol) { + _ => { + if let Some(protocol) = self.timers.get_mut(&token).map(|p| *p) { + match self.handlers.get_mut(protocol) { None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) }, Some(h) => { h.timeout(&mut NetworkContext::new(io, protocol, Some(token), &mut self.connections, &mut self.timers), token); } - }, - None => {} // time not registerd through us + }; + } // else time not registerd through us } } } fn message<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage>, message: &'s mut NetworkIoMessage) { - match message { - &mut NetworkIoMessage::AddHandler { + match *message { + NetworkIoMessage::AddHandler { ref mut handler, ref protocol, ref versions @@ -624,7 +624,7 @@ impl IoHandler> for Host where Messa self.info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 }); } }, - &mut NetworkIoMessage::Send { + NetworkIoMessage::Send { ref peer, ref packet_id, ref protocol, @@ -641,8 +641,8 @@ impl IoHandler> for Host where Messa } } }, - &mut NetworkIoMessage::User(ref message) => { - for (p, h) in self.handlers.iter_mut() { + NetworkIoMessage::User(ref message) => { + for (p, h) in &mut self.handlers { h.message(&mut NetworkContext::new(io, p, None, &mut self.connections, &mut self.timers), &message); } } diff --git a/util/src/network/node.rs b/util/src/network/node.rs index 5c08e0a66..fd27e58e2 100644 --- a/util/src/network/node.rs +++ b/util/src/network/node.rs @@ -20,14 +20,16 @@ pub struct NodeEndpoint { pub udp_port: u16 } -impl NodeEndpoint { +impl FromStr for NodeEndpoint { + type Err = UtilError; + /// Create endpoint from string. Performs name resolution if given a host name. fn from_str(s: &str) -> Result { let address = s.to_socket_addrs().map(|mut i| i.next()); match address { Ok(Some(a)) => Ok(NodeEndpoint { address: a, - address_str: s.to_string(), + address_str: s.to_owned(), udp_port: a.port() }), Ok(_) => Err(UtilError::AddressResolve(None)), diff --git a/util/src/network/session.rs b/util/src/network/session.rs index 828e4b062..d20448fdd 100644 --- a/util/src/network/session.rs +++ b/util/src/network/session.rs @@ -182,7 +182,7 @@ impl Session { // map to protocol let protocol = self.info.capabilities[i].protocol; let pid = packet_id - self.info.capabilities[i].id_offset; - return Ok(SessionData::Packet { data: packet.data, protocol: protocol, packet_id: pid } ) + Ok(SessionData::Packet { data: packet.data, protocol: protocol, packet_id: pid } ) }, _ => { debug!(target: "net", "Unkown packet: {:?}", packet_id); @@ -212,7 +212,7 @@ impl Session { // Intersect with host capabilities // Leave only highset mutually supported capability version let mut caps: Vec = Vec::new(); - for hc in host.capabilities.iter() { + for hc in &host.capabilities { if peer_caps.iter().any(|c| c.protocol == hc.protocol && c.version == hc.version) { caps.push(SessionCapabilityInfo { protocol: hc.protocol, diff --git a/util/src/overlaydb.rs b/util/src/overlaydb.rs index 1006cd28c..0bda2660d 100644 --- a/util/src/overlaydb.rs +++ b/util/src/overlaydb.rs @@ -159,7 +159,7 @@ impl HashDB for OverlayDB { match k { Some(&(ref d, rc)) if rc > 0 => Some(d), _ => { - let memrc = k.map(|&(_, rc)| rc).unwrap_or(0); + let memrc = k.map_or(0, |&(_, rc)| rc); match self.payload(key) { Some(x) => { let (d, rc) = x; @@ -184,16 +184,11 @@ impl HashDB for OverlayDB { match k { Some(&(_, rc)) if rc > 0 => true, _ => { - let memrc = k.map(|&(_, rc)| rc).unwrap_or(0); + let memrc = k.map_or(0, |&(_, rc)| rc); match self.payload(key) { Some(x) => { let (_, rc) = x; - if rc as i32 + memrc > 0 { - true - } - else { - false - } + rc as i32 + memrc > 0 } // Replace above match arm with this once https://github.com/rust-lang/rust/issues/15287 is done. //Some((d, rc)) if rc + memrc > 0 => true, diff --git a/util/src/rlp/rlpstream.rs b/util/src/rlp/rlpstream.rs index b8954ae6f..1487e3912 100644 --- a/util/src/rlp/rlpstream.rs +++ b/util/src/rlp/rlpstream.rs @@ -41,7 +41,7 @@ impl Stream for RlpStream { stream } - fn append<'a, E>(&'a mut self, object: &E) -> &'a mut RlpStream where E: Encodable { + fn append(&mut self, object: &E) -> &mut RlpStream where E: Encodable { // encode given value and add it at the end of the stream object.encode(&mut self.encoder); @@ -52,7 +52,7 @@ impl Stream for RlpStream { self } - fn append_list<'a>(&'a mut self, len: usize) -> &'a mut RlpStream { + fn append_list(&mut self, len: usize) -> &mut RlpStream { match len { 0 => { // we may finish, if the appended list len is equal 0 @@ -69,7 +69,7 @@ impl Stream for RlpStream { self } - fn append_empty_data<'a>(&'a mut self) -> &'a mut RlpStream { + fn append_empty_data(&mut self) -> &mut RlpStream { // self push raw item self.encoder.bytes.push(0x80); diff --git a/util/src/rlp/rlptraits.rs b/util/src/rlp/rlptraits.rs index 407d62daf..162f990fe 100644 --- a/util/src/rlp/rlptraits.rs +++ b/util/src/rlp/rlptraits.rs @@ -5,7 +5,7 @@ pub trait Decoder: Sized { where F: FnOnce(&[u8]) -> Result; fn as_list(&self) -> Result, DecoderError>; - fn as_rlp<'a>(&'a self) -> &'a UntrustedRlp<'a>; + fn as_rlp(&self) -> &UntrustedRlp; fn as_raw(&self) -> &[u8]; } @@ -231,7 +231,7 @@ pub trait Stream: Sized { /// assert_eq!(out, vec![0xca, 0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g', 0x80]); /// } /// ``` - fn append_list<'a>(&'a mut self, len: usize) -> &'a mut Self; + fn append_list(&mut self, len: usize) -> &mut Self; /// Apends null to the end of stream, chainable. /// @@ -246,7 +246,7 @@ pub trait Stream: Sized { /// assert_eq!(out, vec![0xc2, 0x80, 0x80]); /// } /// ``` - fn append_empty_data<'a>(&'a mut self) -> &'a mut Self; + fn append_empty_data(&mut self) -> &mut Self; /// Appends raw (pre-serialised) RLP data. Use with caution. Chainable. fn append_raw<'a>(&'a mut self, bytes: &[u8], item_count: usize) -> &'a mut Self; diff --git a/util/src/rlp/untrusted_rlp.rs b/util/src/rlp/untrusted_rlp.rs index 2bf33ba68..9c9246115 100644 --- a/util/src/rlp/untrusted_rlp.rs +++ b/util/src/rlp/untrusted_rlp.rs @@ -282,7 +282,7 @@ impl<'a> BasicDecoder<'a> { /// Return first item info fn payload_info(bytes: &[u8]) -> Result { - let item = match bytes.first().map(|&x| x) { + let item = match bytes.first().cloned() { None => return Err(DecoderError::RlpIsTooShort), Some(0...0x7f) => PayloadInfo::new(0, 1), Some(l @ 0x80...0xb7) => PayloadInfo::new(1, l as usize - 0x80), @@ -318,7 +318,7 @@ impl<'a> Decoder for BasicDecoder<'a> { let bytes = self.rlp.as_raw(); - match bytes.first().map(|&x| x) { + match bytes.first().cloned() { // rlp is too short None => Err(DecoderError::RlpIsTooShort), // single byt value @@ -349,12 +349,12 @@ impl<'a> Decoder for BasicDecoder<'a> { fn as_list(&self) -> Result, DecoderError> { let v: Vec> = self.rlp.iter() - .map(| i | BasicDecoder::new(i)) + .map(BasicDecoder::new) .collect(); Ok(v) } - fn as_rlp<'s>(&'s self) -> &'s UntrustedRlp<'s> { + fn as_rlp(&self) -> &UntrustedRlp { &self.rlp } } @@ -399,6 +399,7 @@ impl Decodable for Option where T: Decodable { macro_rules! impl_array_decodable { ($index_type:ty, $len:expr ) => ( impl Decodable for [T; $len] where T: Decodable { + #[allow(len_zero)] fn decode(decoder: &D) -> Result where D: Decoder { let decoders = try!(decoder.as_list()); diff --git a/util/src/squeeze.rs b/util/src/squeeze.rs index e81a13793..f83c5cee9 100644 --- a/util/src/squeeze.rs +++ b/util/src/squeeze.rs @@ -41,7 +41,7 @@ pub trait Squeeze { impl Squeeze for HashMap where K: Eq + Hash + Clone + HeapSizeOf, T: HeapSizeOf { fn squeeze(&mut self, size: usize) { - if self.len() == 0 { + if self.is_empty() { return } @@ -49,7 +49,7 @@ impl Squeeze for HashMap where K: Eq + Hash + Clone + HeapSizeOf, T: let all_entries = size_of_entry * self.len(); let mut shrinked_size = all_entries; - while self.len() > 0 && shrinked_size > size { + while !self.is_empty() && shrinked_size > size { // could be optimized let key = self.keys().next().unwrap().clone(); self.remove(&key); diff --git a/util/src/trie/triedb.rs b/util/src/trie/triedb.rs index 9e4cf36e2..612bcdf7a 100644 --- a/util/src/trie/triedb.rs +++ b/util/src/trie/triedb.rs @@ -37,6 +37,7 @@ pub struct TrieDB<'db> { pub hash_count: usize, } +#[allow(wrong_self_convention)] impl<'db> TrieDB<'db> { /// Create a new trie with the backing database `db` and `root` /// Panics, if `root` does not exist @@ -102,7 +103,7 @@ impl<'db> TrieDB<'db> { match node { Node::Extension(_, payload) => handle_payload(payload), - Node::Branch(payloads, _) => for payload in payloads.iter() { handle_payload(payload) }, + Node::Branch(payloads, _) => for payload in &payloads { handle_payload(payload) }, _ => {}, } } @@ -140,12 +141,9 @@ impl<'db> TrieDB<'db> { }, Node::Branch(ref nodes, ref value) => { try!(writeln!(f, "")); - match value { - &Some(v) => { - try!(self.fmt_indent(f, deepness + 1)); - try!(writeln!(f, "=: {:?}", v.pretty())) - }, - &None => {} + if let Some(v) = *value { + try!(self.fmt_indent(f, deepness + 1)); + try!(writeln!(f, "=: {:?}", v.pretty())) } for i in 0..16 { match self.get_node(nodes[i]) { diff --git a/util/src/trie/triedbmut.rs b/util/src/trie/triedbmut.rs index 0f3dde4fb..bd39f87ae 100644 --- a/util/src/trie/triedbmut.rs +++ b/util/src/trie/triedbmut.rs @@ -49,6 +49,7 @@ enum MaybeChanged<'a> { Changed(Bytes), } +#[allow(wrong_self_convention)] impl<'db> TrieDBMut<'db> { /// Create a new trie with the backing database `db` and empty `root` /// Initialise to the state entailed by the genesis block. @@ -144,7 +145,7 @@ impl<'db> TrieDBMut<'db> { match node { Node::Extension(_, payload) => handle_payload(payload), - Node::Branch(payloads, _) => for payload in payloads.iter() { handle_payload(payload) }, + Node::Branch(payloads, _) => for payload in &payloads { handle_payload(payload) }, _ => {}, } } @@ -177,12 +178,9 @@ impl<'db> TrieDBMut<'db> { }, Node::Branch(ref nodes, ref value) => { try!(writeln!(f, "")); - match value { - &Some(v) => { - try!(self.fmt_indent(f, deepness + 1)); - try!(writeln!(f, "=: {:?}", v.pretty())) - }, - &None => {} + if let Some(v) = *value { + try!(self.fmt_indent(f, deepness + 1)); + try!(writeln!(f, "=: {:?}", v.pretty())) } for i in 0..16 { match self.get_node(nodes[i]) { @@ -330,6 +328,7 @@ impl<'db> TrieDBMut<'db> { } } + #[allow(cyclomatic_complexity)] /// Determine the RLP of the node, assuming we're inserting `partial` into the /// node currently of data `old`. This will *not* delete any hash of `old` from the database; /// it will just return the new RLP that includes the new node. @@ -704,7 +703,7 @@ mod tests { } fn unpopulate_trie<'a, 'db>(t: &mut TrieDBMut<'db>, v: &Vec<(Vec, Vec)>) { - for i in v.iter() { + for i in &v { let key: &[u8]= &i.0; t.remove(&key); } diff --git a/util/src/uint.rs b/util/src/uint.rs index ec70cddb2..3562a2b81 100644 --- a/util/src/uint.rs +++ b/util/src/uint.rs @@ -174,7 +174,7 @@ macro_rules! construct_uint { #[inline] fn byte(&self, index: usize) -> u8 { let &$name(ref arr) = self; - (arr[index / 8] >> ((index % 8)) * 8) as u8 + (arr[index / 8] >> (((index % 8)) * 8)) as u8 } fn to_bytes(&self, bytes: &mut[u8]) { @@ -328,16 +328,16 @@ macro_rules! construct_uint { impl FromJson for $name { fn from_json(json: &Json) -> Self { - match json { - &Json::String(ref s) => { + match *json { + Json::String(ref s) => { if s.len() >= 2 && &s[0..2] == "0x" { FromStr::from_str(&s[2..]).unwrap_or(Default::default()) } else { Uint::from_dec_str(s).unwrap_or(Default::default()) } }, - &Json::U64(u) => From::from(u), - &Json::I64(i) => From::from(i as u64), + Json::U64(u) => From::from(u), + Json::I64(i) => From::from(i as u64), _ => Uint::zero(), } } @@ -370,7 +370,7 @@ macro_rules! construct_uint { for i in 0..bytes.len() { let rev = bytes.len() - 1 - i; let pos = rev / 8; - ret[pos] += (bytes[i] as u64) << (rev % 8) * 8; + ret[pos] += (bytes[i] as u64) << ((rev % 8) * 8); } $name(ret) } @@ -382,7 +382,7 @@ macro_rules! construct_uint { fn from_str(value: &str) -> Result<$name, Self::Err> { let bytes: Vec = match value.len() % 2 == 0 { true => try!(value.from_hex()), - false => try!(("0".to_string() + value).from_hex()) + false => try!(("0".to_owned() + value).from_hex()) }; let bytes_ref: &[u8] = &bytes;