Merge branch 'master' of github.com:ethcore/parity into io

This commit is contained in:
arkpar
2016-01-22 14:44:17 +01:00
58 changed files with 395 additions and 434 deletions

View File

@@ -106,18 +106,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
}
}
}
@@ -299,7 +299,7 @@ pub trait FromBytes: Sized {
impl FromBytes for String {
fn from_bytes(bytes: &[u8]) -> FromBytesResult<String> {
Ok(::std::str::from_utf8(bytes).unwrap().to_string())
Ok(::std::str::from_utf8(bytes).unwrap().to_owned())
}
}

View File

@@ -323,10 +323,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

View File

@@ -207,11 +207,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(),
@@ -221,7 +221,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(())
@@ -229,11 +229,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(())
@@ -291,36 +291,36 @@ macro_rules! impl_hash {
impl Index<usize> 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<usize> 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<ops::Range<usize>> for $from {
type Output = [u8];
fn index<'a>(&'a self, index: ops::Range<usize>) -> &'a [u8] {
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut<'a>(&'a mut self, index: ops::Range<usize>) -> &'a mut [u8] {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> 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<ops::RangeFull> 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
}
}
@@ -440,9 +440,9 @@ 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_else(|_| $from::new())
} else {
$from::from_str(clean_0x(s)).unwrap_or($from::new())
$from::from_str(clean_0x(s)).unwrap_or_else(|_| $from::new())
}
}
}
@@ -565,6 +565,7 @@ mod tests {
use std::str::FromStr;
#[test]
#[allow(eq_op)]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);

View File

@@ -132,7 +132,7 @@ impl<Message> IoManager<Message> where Message: Send + Sync + Clone + 'static {
pub fn start(event_loop: &mut EventLoop<IoManager<Message>>) -> Result<(), UtilError> {
let (worker, stealer) = chase_lev::deque();
let num_workers = 4;
let work_ready_mutex = Arc::new(Mutex::new(false));
let work_ready_mutex = Arc::new(Mutex::new(()));
let work_ready = Arc::new(Condvar::new());
let workers = (0..num_workers).map(|i|
Worker::new(i, stealer.clone(), IoChannel::new(event_loop.channel()), work_ready.clone(), work_ready_mutex.clone())).collect();

View File

@@ -35,7 +35,7 @@ impl Worker {
stealer: chase_lev::Stealer<Work<Message>>,
channel: IoChannel<Message>,
wait: Arc<Condvar>,
wait_mutex: Arc<Mutex<bool>>) -> Worker
wait_mutex: Arc<Mutex<()>>) -> Worker
where Message: Send + Sync + Clone + 'static {
let deleting = Arc::new(AtomicBool::new(false));
let mut worker = Worker {
@@ -51,7 +51,7 @@ impl Worker {
fn work_loop<Message>(stealer: chase_lev::Stealer<Work<Message>>,
channel: IoChannel<Message>, wait: Arc<Condvar>,
wait_mutex: Arc<Mutex<bool>>,
wait_mutex: Arc<Mutex<()>>,
deleting: Arc<AtomicBool>)
where Message: Send + Sync + Clone + 'static {
while !deleting.load(AtomicOrdering::Relaxed) {
@@ -62,13 +62,8 @@ impl Worker {
return;
}
}
loop {
match stealer.steal() {
chase_lev::Steal::Data(work) => {
Worker::do_work(work, channel.clone());
}
_ => break
}
while let chase_lev::Steal::Data(work) = stealer.steal() {
Worker::do_work(work, channel.clone());
}
}
}
@@ -76,19 +71,19 @@ impl Worker {
fn do_work<Message>(work: Work<Message>, channel: IoChannel<Message>) where Message: Send + Sync + Clone + 'static {
match work.work_type {
WorkType::Readable => {
work.handler.stream_readable(&mut IoContext::new(channel, work.handler_id), work.token);
work.handler.stream_readable(&IoContext::new(channel, work.handler_id), work.token);
},
WorkType::Writable => {
work.handler.stream_writable(&mut IoContext::new(channel, work.handler_id), work.token);
work.handler.stream_writable(&IoContext::new(channel, work.handler_id), work.token);
}
WorkType::Hup => {
work.handler.stream_hup(&mut IoContext::new(channel, work.handler_id), work.token);
work.handler.stream_hup(&IoContext::new(channel, work.handler_id), work.token);
}
WorkType::Timeout => {
work.handler.timeout(&mut IoContext::new(channel, work.handler_id), work.token);
work.handler.timeout(&IoContext::new(channel, work.handler_id), work.token);
}
WorkType::Message(message) => {
work.handler.message(&mut IoContext::new(channel, work.handler_id), &message);
work.handler.message(&IoContext::new(channel, work.handler_id), &message);
}
}
}

View File

@@ -106,7 +106,7 @@ impl JournalDB {
})) {
let rlp = Rlp::new(&rlp_data);
let to_remove: Vec<H256> = rlp.val_at(if canon_id == rlp.val_at(0) {2} else {1});
for i in to_remove.iter() {
for i in &to_remove {
self.forward.remove(i);
}
try!(self.backing.delete(&last));

View File

@@ -11,18 +11,18 @@ pub fn clean(s: &str) -> &str {
fn u256_from_str(s: &str) -> U256 {
if s.len() >= 2 && &s[0..2] == "0x" {
U256::from_str(&s[2..]).unwrap_or(U256::from(0))
U256::from_str(&s[2..]).unwrap_or_else(|_| U256::zero())
} else {
U256::from_dec_str(s).unwrap_or(U256::from(0))
U256::from_dec_str(s).unwrap_or_else(|_| U256::zero())
}
}
impl FromJson for Bytes {
fn from_json(json: &Json) -> Self {
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![]),
match *json {
Json::String(ref s) => match s.len() % 2 {
0 => FromHex::from_hex(clean(s)).unwrap_or_else(|_| vec![]),
_ => FromHex::from_hex(&("0".to_owned() + &(clean(s).to_owned()))[..]).unwrap_or_else(|_| vec![]),
},
_ => vec![],
}
@@ -31,8 +31,8 @@ impl FromJson for Bytes {
impl FromJson for BTreeMap<H256, H256> {
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(),
}
}
@@ -40,8 +40,8 @@ impl FromJson for BTreeMap<H256, H256> {
impl<T> FromJson for Vec<T> 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(),
}
}
@@ -49,9 +49,9 @@ impl<T> FromJson for Vec<T> where T: FromJson {
impl<T> FromJson for Option<T> 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)),
}
}
@@ -135,4 +135,4 @@ fn option_types() {
assert_eq!(None, v);
let v: Option<u16> = xjson!(&j["empty"]);
assert_eq!(None, v);
}
}

View File

@@ -2,6 +2,9 @@
#![feature(op_assign_traits)]
#![feature(augmented_assignments)]
#![feature(associated_consts)]
#![feature(plugin)]
#![plugin(clippy)]
#![allow(needless_range_loop, match_bool)]
//! Ethcore-util library
//!
//! ### Rust version:

View File

@@ -18,13 +18,13 @@ impl<T> Diff<T> 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)]

View File

@@ -88,7 +88,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() {
@@ -340,13 +340,10 @@ impl EncryptedConnection {
io.clear_timer(self.connection.token).unwrap();
match self.read_state {
EncryptedConnectionState::Header => {
match try!(self.connection.readable()) {
Some(data) => {
try!(self.read_header(&data));
try!(io.register_timer(self.connection.token, RECIEVE_PAYLOAD_TIMEOUT));
},
None => {}
};
if let Some(data) = try!(self.connection.readable()) {
try!(self.read_header(&data));
try!(io.register_timer(self.connection.token, RECIEVE_PAYLOAD_TIMEOUT));
}
Ok(None)
},
EncryptedConnectionState::Payload => {

View File

@@ -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<NodeBucket>) -> 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,21 +137,21 @@ 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;
found.entry(Discovery::distance(target, &n)).or_insert(Vec::new()).push(n);
found.entry(Discovery::distance(target, &n)).or_insert_with(Vec::new).push(n);
}
else {
break;
}
}
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);
found.entry(Discovery::distance(target, &n)).or_insert_with(Vec::new).push(n);
}
else {
break;
@@ -166,10 +167,10 @@ 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);
found.entry(Discovery::distance(target, &n)).or_insert_with(Vec::new).push(n);
}
else {
break;
@@ -180,10 +181,10 @@ 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);
found.entry(Discovery::distance(target, &n)).or_insert_with(Vec::new).push(n);
}
else {
break;

View File

@@ -93,21 +93,15 @@ impl Handshake {
io.clear_timer(self.connection.token).unwrap();
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;
};
},
HandshakeState::StartSession => {},

View File

@@ -133,9 +133,9 @@ impl<'s, Message> NetworkContext<'s, Message> where Message: Send + Sync + Clone
/// Send a packet over the network to another peer.
pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
if let Some(connection) = self.connections.read().unwrap().get(peer).map(|c| c.clone()) {
match connection.lock().unwrap().deref_mut() {
&mut ConnectionEntry::Session(ref mut s) => {
if let Some(connection) = self.connections.read().unwrap().get(peer).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Session(ref mut s) => {
s.send_packet(self.protocol, packet_id as u8, &data).unwrap_or_else(|e| {
warn!(target: "net", "Send error: {:?}", e);
}); //TODO: don't copy vector data
@@ -175,15 +175,12 @@ impl<'s, Message> NetworkContext<'s, Message> where Message: Send + Sync + Clone
/// Returns peer identification string
pub fn peer_info(&self, peer: PeerId) -> String {
if let Some(connection) = self.connections.read().unwrap().get(peer).map(|c| c.clone()) {
match connection.lock().unwrap().deref() {
&ConnectionEntry::Session(ref s) => {
return s.info.client_version.clone()
},
_ => {}
if let Some(connection) = self.connections.read().unwrap().get(peer).cloned() {
if let ConnectionEntry::Session(ref s) = *connection.lock().unwrap().deref() {
return s.info.client_version.clone()
}
}
"unknown".to_string()
"unknown".to_owned()
}
}
@@ -219,7 +216,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()
}
}
@@ -261,7 +258,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
config: config,
nonce: H256::random(),
protocol_version: 4,
client_version: "parity".to_string(),
client_version: "parity".to_owned(),
listen_port: 0,
capabilities: Vec::new(),
}),
@@ -314,11 +311,11 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
fn have_session(&self, id: &NodeId) -> bool {
self.connections.read().unwrap().iter().any(|e| match e.lock().unwrap().deref() { &ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
self.connections.read().unwrap().iter().any(|e| match *e.lock().unwrap().deref() { ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
}
fn connecting_to(&self, id: &NodeId) -> bool {
self.connections.read().unwrap().iter().any(|e| match e.lock().unwrap().deref() { &ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
self.connections.read().unwrap().iter().any(|e| match *e.lock().unwrap().deref() { ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
}
fn connect_peers(&self, io: &IoContext<NetworkIoMessage<Message>>) {
@@ -344,7 +341,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
}
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);
@@ -358,7 +355,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
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);
@@ -368,8 +365,11 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
}
#[allow(single_match)]
#[allow(block_in_if_condition_stmt)]
fn connect_peer(&self, id: &NodeId, io: &IoContext<NetworkIoMessage<Message>>) {
if self.have_session(id) {
if self.have_session(id)
{
warn!("Aborted connect. Node already connected.");
return;
}
@@ -410,12 +410,13 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
trace!(target: "net", "accept");
}
#[allow(single_match)]
fn connection_writable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
let mut create_session = false;
let mut kill = false;
if let Some(connection) = self.connections.read().unwrap().get(token).map(|c| c.clone()) {
match connection.lock().unwrap().deref_mut() {
&mut ConnectionEntry::Handshake(ref mut h) => {
if let Some(connection) = self.connections.read().unwrap().get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(ref mut h) => {
match h.writable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Handshake write error: {:?}", e);
@@ -427,7 +428,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
create_session = true;
}
},
&mut ConnectionEntry::Session(ref mut s) => {
ConnectionEntry::Session(ref mut s) => {
match s.writable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Session write error: {:?}", e);
@@ -457,21 +458,18 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
let mut packet_data: Option<(ProtocolId, PacketId, Vec<u8>)> = None;
let mut create_session = false;
let mut kill = false;
if let Some(connection) = self.connections.read().unwrap().get(token).map(|c| c.clone()) {
match connection.lock().unwrap().deref_mut() {
&mut ConnectionEntry::Handshake(ref mut h) => {
match h.readable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Handshake read error: {:?}", e);
kill = true;
},
Ok(_) => ()
if let Some(connection) = self.connections.read().unwrap().get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(ref mut h) => {
if let Err(e) = h.readable(io, &self.info.read().unwrap()) {
debug!(target: "net", "Handshake read error: {:?}", e);
kill = true;
}
if h.done() {
create_session = true;
}
},
&mut ConnectionEntry::Session(ref mut s) => {
ConnectionEntry::Session(ref mut s) => {
match s.readable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Handshake read error: {:?}", e);
@@ -508,11 +506,11 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
for p in ready_data {
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.connected(&mut NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
h.connected(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
}
if let Some((p, packet_id, data)) = packet_data {
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.read(&mut NetworkContext::new(io, p, Some(token), self.connections.clone()), &token, packet_id, &data[1..]);
h.read(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token, packet_id, &data[1..]);
}
io.update_registration(token).unwrap_or_else(|e| debug!(target: "net", "Token registration error: {:?}", e));
}
@@ -538,12 +536,12 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
let mut to_disconnect: Vec<ProtocolId> = Vec::new();
{
let mut connections = self.connections.write().unwrap();
if let Some(connection) = connections.get(token).map(|c| c.clone()) {
match connection.lock().unwrap().deref_mut() {
&mut ConnectionEntry::Handshake(_) => {
if let Some(connection) = connections.get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(_) => {
connections.remove(token);
},
&mut ConnectionEntry::Session(ref mut s) if s.is_ready() => {
ConnectionEntry::Session(ref mut s) if s.is_ready() => {
for (p, _) in self.handlers.read().unwrap().iter() {
if s.have_capability(p) {
to_disconnect.push(p);
@@ -557,7 +555,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
for p in to_disconnect {
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.disconnected(&mut NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
h.disconnected(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
}
}
}
@@ -602,8 +600,8 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, io),
NODETABLE_DISCOVERY => {},
NODETABLE_MAINTAIN => {},
_ => match self.timers.read().unwrap().get(&token).map(|p| *p) {
Some(timer) => match self.handlers.read().unwrap().get(timer.protocol).map(|h| h.clone()) {
_ => match self.timers.read().unwrap().get(&token).cloned() {
Some(timer) => match self.handlers.read().unwrap().get(timer.protocol).cloned() {
None => { warn!(target: "net", "No handler found for protocol: {:?}", timer.protocol) },
Some(h) => { h.timeout(&NetworkContext::new(io, timer.protocol, None, self.connections.clone()), timer.token); }
},
@@ -613,8 +611,8 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
}
fn message(&self, io: &IoContext<NetworkIoMessage<Message>>, message: &NetworkIoMessage<Message>) {
match message {
&NetworkIoMessage::AddHandler {
match *message {
NetworkIoMessage::AddHandler {
ref handler,
ref protocol,
ref versions
@@ -627,7 +625,7 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 });
}
},
&NetworkIoMessage::AddTimer {
NetworkIoMessage::AddTimer {
ref protocol,
ref delay,
ref token,
@@ -642,9 +640,9 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
self.timers.write().unwrap().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token });
io.register_timer(handler_token, *delay).expect("Error registering timer");
},
&NetworkIoMessage::User(ref message) => {
NetworkIoMessage::User(ref message) => {
for (p, h) in self.handlers.read().unwrap().iter() {
h.message(&mut NetworkContext::new(io, p, None, self.connections.clone()), &message);
h.message(&NetworkContext::new(io, p, None, self.connections.clone()), &message);
}
}
}
@@ -653,10 +651,10 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => {
if let Some(connection) = self.connections.read().unwrap().get(stream).map(|c| c.clone()) {
match connection.lock().unwrap().deref() {
&ConnectionEntry::Handshake(ref h) => h.register_socket(reg, event_loop).expect("Error registering socket"),
&ConnectionEntry::Session(_) => warn!("Unexpected session stream registration")
if let Some(connection) = self.connections.read().unwrap().get(stream).cloned() {
match *connection.lock().unwrap().deref() {
ConnectionEntry::Handshake(ref h) => h.register_socket(reg, event_loop).expect("Error registering socket"),
ConnectionEntry::Session(_) => warn!("Unexpected session stream registration")
}
} else {} // expired
}
@@ -669,10 +667,10 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => {
if let Some(connection) = self.connections.read().unwrap().get(stream).map(|c| c.clone()) {
match connection.lock().unwrap().deref() {
&ConnectionEntry::Handshake(ref h) => h.update_socket(reg, event_loop).expect("Error updating socket"),
&ConnectionEntry::Session(ref s) => s.update_socket(reg, event_loop).expect("Error updating socket"),
if let Some(connection) = self.connections.read().unwrap().get(stream).cloned() {
match *connection.lock().unwrap().deref() {
ConnectionEntry::Handshake(ref h) => h.update_socket(reg, event_loop).expect("Error updating socket"),
ConnectionEntry::Session(ref s) => s.update_socket(reg, event_loop).expect("Error updating socket"),
}
} else {} // expired
}

View File

@@ -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<NodeEndpoint, UtilError> {
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)),

View File

@@ -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<SessionCapabilityInfo> = 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,

View File

@@ -169,7 +169,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;
@@ -194,16 +194,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,

View File

@@ -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<E>(&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);

View File

@@ -9,7 +9,7 @@ pub trait Decoder: Sized {
/// TODO [arkpar] Please document me
fn as_list(&self) -> Result<Vec<Self>, DecoderError>;
/// TODO [Gav Wood] Please document me
fn as_rlp<'a>(&'a self) -> &'a UntrustedRlp<'a>;
fn as_rlp(&self) -> &UntrustedRlp;
/// TODO [debris] Please document me
fn as_raw(&self) -> &[u8];
}
@@ -255,7 +255,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.
///
@@ -270,7 +270,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;

View File

@@ -15,25 +15,25 @@ fn rlp_at() {
assert!(rlp.is_list());
//let animals = <Vec<String> as rlp::Decodable>::decode_untrusted(&rlp).unwrap();
let animals: Vec<String> = rlp.as_val().unwrap();
assert_eq!(animals, vec!["cat".to_string(), "dog".to_string()]);
assert_eq!(animals, vec!["cat".to_owned(), "dog".to_owned()]);
let cat = rlp.at(0).unwrap();
assert!(cat.is_data());
assert_eq!(cat.as_raw(), &[0x83, b'c', b'a', b't']);
//assert_eq!(String::decode_untrusted(&cat).unwrap(), "cat".to_string());
assert_eq!(cat.as_val::<String>().unwrap(), "cat".to_string());
//assert_eq!(String::decode_untrusted(&cat).unwrap(), "cat".to_owned());
assert_eq!(cat.as_val::<String>().unwrap(), "cat".to_owned());
let dog = rlp.at(1).unwrap();
assert!(dog.is_data());
assert_eq!(dog.as_raw(), &[0x83, b'd', b'o', b'g']);
//assert_eq!(String::decode_untrusted(&dog).unwrap(), "dog".to_string());
assert_eq!(dog.as_val::<String>().unwrap(), "dog".to_string());
//assert_eq!(String::decode_untrusted(&dog).unwrap(), "dog".to_owned());
assert_eq!(dog.as_val::<String>().unwrap(), "dog".to_owned());
let cat_again = rlp.at(0).unwrap();
assert!(cat_again.is_data());
assert_eq!(cat_again.as_raw(), &[0x83, b'c', b'a', b't']);
//assert_eq!(String::decode_untrusted(&cat_again).unwrap(), "cat".to_string());
assert_eq!(cat_again.as_val::<String>().unwrap(), "cat".to_string());
//assert_eq!(String::decode_untrusted(&cat_again).unwrap(), "cat".to_owned());
assert_eq!(cat_again.as_val::<String>().unwrap(), "cat".to_owned());
}
}
@@ -268,13 +268,13 @@ fn decode_untrusted_u256() {
#[test]
fn decode_untrusted_str() {
let tests = vec![DTestPair("cat".to_string(), vec![0x83, b'c', b'a', b't']),
DTestPair("dog".to_string(), vec![0x83, b'd', b'o', b'g']),
DTestPair("Marek".to_string(),
let tests = vec![DTestPair("cat".to_owned(), vec![0x83, b'c', b'a', b't']),
DTestPair("dog".to_owned(), vec![0x83, b'd', b'o', b'g']),
DTestPair("Marek".to_owned(),
vec![0x85, b'M', b'a', b'r', b'e', b'k']),
DTestPair("".to_string(), vec![0x80]),
DTestPair("".to_owned(), vec![0x80]),
DTestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit"
.to_string(),
.to_owned(),
vec![0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i',
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o',
b'r', b' ', b's', b'i', b't', b' ', b'a', b'm', b'e',
@@ -311,14 +311,14 @@ fn decode_untrusted_vector_u64() {
#[test]
fn decode_untrusted_vector_str() {
let tests = vec![DTestPair(vec!["cat".to_string(), "dog".to_string()],
let tests = vec![DTestPair(vec!["cat".to_owned(), "dog".to_owned()],
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])];
run_decode_tests(tests);
}
#[test]
fn decode_untrusted_vector_of_vectors_str() {
let tests = vec![DTestPair(vec![vec!["cat".to_string()]],
let tests = vec![DTestPair(vec![vec!["cat".to_owned()]],
vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])];
run_decode_tests(tests);
}

View File

@@ -288,7 +288,7 @@ impl<'a> BasicDecoder<'a> {
/// Return first item info
fn payload_info(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
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),
@@ -324,7 +324,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
@@ -355,12 +355,12 @@ impl<'a> Decoder for BasicDecoder<'a> {
fn as_list(&self) -> Result<Vec<Self>, DecoderError> {
let v: Vec<BasicDecoder<'a>> = 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
}
}
@@ -405,6 +405,7 @@ impl<T> Decodable for Option<T> where T: Decodable {
macro_rules! impl_array_decodable {
($index_type:ty, $len:expr ) => (
impl<T> Decodable for [T; $len] where T: Decodable {
#[allow(len_zero)]
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let decoders = try!(decoder.as_list());

View File

@@ -42,7 +42,7 @@ pub trait Squeeze {
impl<K, T> Squeeze for HashMap<K, T> where K: Eq + Hash + Clone + HeapSizeOf, T: HeapSizeOf {
fn squeeze(&mut self, size: usize) {
if self.len() == 0 {
if self.is_empty() {
return
}
@@ -50,7 +50,7 @@ impl<K, T> Squeeze for HashMap<K, T> 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);

View File

@@ -38,6 +38,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
@@ -103,7 +104,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) },
_ => {},
}
}
@@ -141,12 +142,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]) {

View File

@@ -50,6 +50,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.
@@ -145,7 +146,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) },
_ => {},
}
}
@@ -178,12 +179,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]) {
@@ -331,6 +329,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.
@@ -694,7 +693,7 @@ mod tests {
}
}
fn populate_trie<'db>(db: &'db mut HashDB, root: &'db mut H256, v: &Vec<(Vec<u8>, Vec<u8>)>) -> TrieDBMut<'db> {
fn populate_trie<'db>(db: &'db mut HashDB, root: &'db mut H256, v: &[(Vec<u8>, Vec<u8>)]) -> TrieDBMut<'db> {
let mut t = TrieDBMut::new(db, root);
for i in 0..v.len() {
let key: &[u8]= &v[i].0;
@@ -704,8 +703,8 @@ mod tests {
t
}
fn unpopulate_trie<'a, 'db>(t: &mut TrieDBMut<'db>, v: &Vec<(Vec<u8>, Vec<u8>)>) {
for i in v.iter() {
fn unpopulate_trie<'db>(t: &mut TrieDBMut<'db>, v: &[(Vec<u8>, Vec<u8>)]) {
for i in v {
let key: &[u8]= &i.0;
t.remove(&key);
}
@@ -761,7 +760,7 @@ mod tests {
println!("TRIE MISMATCH");
println!("");
println!("{:?} vs {:?}", memtrie.root(), real);
for i in x.iter() {
for i in &x {
println!("{:?} -> {:?}", i.0.pretty(), i.1.pretty());
}
println!("{:?}", memtrie);
@@ -774,7 +773,7 @@ mod tests {
println!("");
println!("remaining: {:?}", memtrie.db_items_remaining());
println!("{:?} vs {:?}", memtrie.root(), real);
for i in x.iter() {
for i in &x {
println!("{:?} -> {:?}", i.0.pretty(), i.1.pretty());
}
println!("{:?}", memtrie);
@@ -1051,12 +1050,12 @@ mod tests {
println!("TRIE MISMATCH");
println!("");
println!("ORIGINAL... {:?}", memtrie.root());
for i in x.iter() {
for i in &x {
println!("{:?} -> {:?}", i.0.pretty(), i.1.pretty());
}
println!("{:?}", memtrie);
println!("SORTED... {:?}", memtrie_sorted.root());
for i in y.iter() {
for i in &y {
println!("{:?} -> {:?}", i.0.pretty(), i.1.pretty());
}
println!("{:?}", memtrie_sorted);

View File

@@ -200,7 +200,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]) {
@@ -446,16 +446,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())
FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default())
} else {
Uint::from_dec_str(s).unwrap_or(Default::default())
Uint::from_dec_str(s).unwrap_or_else(|_| 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(),
}
}
@@ -488,7 +488,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)
}
@@ -500,7 +500,7 @@ macro_rules! construct_uint {
fn from_str(value: &str) -> Result<$name, Self::Err> {
let bytes: Vec<u8> = 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;
@@ -1061,6 +1061,7 @@ mod tests {
}
#[test]
#[allow(eq_op)]
pub fn uint256_comp_test() {
let small = U256([10u64, 0, 0, 0]);
let big = U256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);