Making clippy happy

This commit is contained in:
Dennis Schwerdel 2016-06-11 16:08:57 +02:00
parent b8c2ce5bea
commit f933db2dd9
9 changed files with 120 additions and 103 deletions

View File

@ -65,23 +65,23 @@ impl PeerList {
del del
} }
#[inline(always)] #[inline]
fn contains_addr(&self, addr: &SocketAddr) -> bool { fn contains_addr(&self, addr: &SocketAddr) -> bool {
self.addresses.contains(addr) self.addresses.contains(addr)
} }
#[inline] #[inline]
fn is_connected<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> { fn is_connected<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> {
let mut addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name"))); let addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
while let Some(a) = addrs.next() { for addr in addrs {
if self.contains_addr(&a) { if self.contains_addr(&addr) {
return Ok(true); return Ok(true);
} }
} }
Ok(false) Ok(false)
} }
#[inline(always)] #[inline]
fn contains_node(&self, node_id: &NodeId) -> bool { fn contains_node(&self, node_id: &NodeId) -> bool {
self.nodes.contains_key(node_id) self.nodes.contains_key(node_id)
} }
@ -112,14 +112,20 @@ impl PeerList {
#[inline] #[inline]
fn as_vec(&self) -> Vec<SocketAddr> { fn as_vec(&self) -> Vec<SocketAddr> {
self.addresses.iter().map(|addr| *addr).collect() self.addresses.iter().cloned().collect()
} }
#[inline(always)] #[inline]
fn len(&self) -> usize { fn len(&self) -> usize {
self.peers.len() self.peers.len()
} }
#[inline]
#[allow(dead_code)]
fn is_empty(&self) -> bool {
self.peers.is_empty()
}
#[inline] #[inline]
fn subset(&self, size: usize) -> Vec<SocketAddr> { fn subset(&self, size: usize) -> Vec<SocketAddr> {
sample(&mut thread_rng(), self.as_vec(), size) sample(&mut thread_rng(), self.as_vec(), size)
@ -127,7 +133,7 @@ impl PeerList {
#[inline] #[inline]
fn remove(&mut self, addr: &SocketAddr) { fn remove(&mut self, addr: &SocketAddr) {
if let Some((_timeout, node_id, alt_addrs)) = self.peers.remove(&addr) { if let Some((_timeout, node_id, alt_addrs)) = self.peers.remove(addr) {
info!("Removed peer: {}", addr); info!("Removed peer: {}", addr);
self.nodes.remove(&node_id); self.nodes.remove(&node_id);
self.addresses.remove(addr); self.addresses.remove(addr);
@ -214,11 +220,11 @@ impl<P: Protocol> GenericCloud<P> {
#[inline] #[inline]
fn broadcast_msg(&mut self, msg: &mut Message) -> Result<(), Error> { fn broadcast_msg(&mut self, msg: &mut Message) -> Result<(), Error> {
debug!("Broadcasting {:?}", msg); debug!("Broadcasting {:?}", msg);
let msg_data = encode(&mut self.options, msg, &mut self.buffer_out, &mut self.crypto); let msg_data = encode(&self.options, msg, &mut self.buffer_out, &mut self.crypto);
for addr in &self.peers.as_vec() { for addr in self.peers.as_vec() {
let socket = match addr { let socket = match addr {
&SocketAddr::V4(_) => &self.socket4, SocketAddr::V4(_) => &self.socket4,
&SocketAddr::V6(_) => &self.socket6 SocketAddr::V6(_) => &self.socket6
}; };
try!(match socket.send_to(msg_data, addr) { try!(match socket.send_to(msg_data, addr) {
Ok(written) if written == msg_data.len() => Ok(()), Ok(written) if written == msg_data.len() => Ok(()),
@ -235,10 +241,10 @@ impl<P: Protocol> GenericCloud<P> {
#[inline] #[inline]
fn send_msg(&mut self, addr: SocketAddr, msg: &mut Message) -> Result<(), Error> { fn send_msg(&mut self, addr: SocketAddr, msg: &mut Message) -> Result<(), Error> {
debug!("Sending {:?} to {}", msg, addr); debug!("Sending {:?} to {}", msg, addr);
let msg_data = encode(&mut self.options, msg, &mut self.buffer_out, &mut self.crypto); let msg_data = encode(&self.options, msg, &mut self.buffer_out, &mut self.crypto);
let socket = match &addr { let socket = match addr {
&SocketAddr::V4(_) => &self.socket4, SocketAddr::V4(_) => &self.socket4,
&SocketAddr::V6(_) => &self.socket6 SocketAddr::V6(_) => &self.socket6
}; };
match socket.send_to(msg_data, addr) { match socket.send_to(msg_data, addr) {
Ok(written) if written == msg_data.len() => Ok(()), Ok(written) if written == msg_data.len() => Ok(()),
@ -270,9 +276,9 @@ impl<P: Protocol> GenericCloud<P> {
} }
fn is_blacklisted<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> { fn is_blacklisted<Addr: ToSocketAddrs+fmt::Display>(&self, addr: Addr) -> Result<bool, Error> {
let mut addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name"))); let addrs = try!(addr.to_socket_addrs().map_err(|_| Error::SocketError("Error looking up name")));
while let Some(a) = addrs.next() { for addr in addrs {
if self.blacklist_peers.contains(&a) { if self.blacklist_peers.contains(&addr) {
return Ok(true); return Ok(true);
} }
} }
@ -285,7 +291,7 @@ impl<P: Protocol> GenericCloud<P> {
} }
debug!("Connecting to {}", addr); debug!("Connecting to {}", addr);
let subnets = self.addresses.clone(); let subnets = self.addresses.clone();
let node_id = self.node_id.clone(); let node_id = self.node_id;
let mut msg = Message::Init(0, node_id, subnets); let mut msg = Message::Init(0, node_id, subnets);
if let Ok(addrs) = addr.to_socket_addrs() { if let Ok(addrs) = addr.to_socket_addrs() {
let mut addrs = addrs.collect::<Vec<_>>(); let mut addrs = addrs.collect::<Vec<_>>();
@ -414,13 +420,13 @@ impl<P: Protocol> GenericCloud<P> {
} else { } else {
self.peers.add(node_id, peer); self.peers.add(node_id, peer);
for range in ranges { for range in ranges {
self.table.learn(range.base, Some(range.prefix_len), peer.clone()); self.table.learn(range.base, Some(range.prefix_len), peer);
} }
} }
if stage == 0 { if stage == 0 {
let peers = self.peers.as_vec(); let peers = self.peers.as_vec();
let own_addrs = self.addresses.clone(); let own_addrs = self.addresses.clone();
let own_node_id = self.node_id.clone(); let own_node_id = self.node_id;
try!(self.send_msg(peer, &mut Message::Init(stage+1, own_node_id, own_addrs))); try!(self.send_msg(peer, &mut Message::Init(stage+1, own_node_id, own_addrs)));
try!(self.send_msg(peer, &mut Message::Peers(peers))); try!(self.send_msg(peer, &mut Message::Peers(peers)));
} }
@ -451,23 +457,23 @@ impl<P: Protocol> GenericCloud<P> {
loop { loop {
let count = try_fail!(epoll::wait(epoll_handle, &mut events, 1000), "Epoll wait failed: {}") as usize; let count = try_fail!(epoll::wait(epoll_handle, &mut events, 1000), "Epoll wait failed: {}") as usize;
// Process events // Process events
for i in 0..count { for evt in events.iter().take(count) {
match &events[i].data { match evt.data {
&0 => { 0 => {
let (size, src) = try_fail!(self.socket4.recv_from(&mut buffer), "Failed to read from ipv4 network socket: {}"); let (size, src) = try_fail!(self.socket4.recv_from(&mut buffer), "Failed to read from ipv4 network socket: {}");
match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) { match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) {
Ok(_) => (), Ok(_) => (),
Err(e) => error!("Error: {}, from: {}", e, src) Err(e) => error!("Error: {}, from: {}", e, src)
} }
}, },
&1 => { 1 => {
let (size, src) = try_fail!(self.socket6.recv_from(&mut buffer), "Failed to read from ipv6 network socket: {}"); let (size, src) = try_fail!(self.socket6.recv_from(&mut buffer), "Failed to read from ipv6 network socket: {}");
match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) { match decode(&mut buffer[..size], &mut self.crypto).and_then(|(options, msg)| self.handle_net_message(src, options, msg)) {
Ok(_) => (), Ok(_) => (),
Err(e) => error!("Error: {}, from: {}", e, src) Err(e) => error!("Error: {}, from: {}", e, src)
} }
}, },
&2 => { 2 => {
let start = 64; let start = 64;
let size = try_fail!(self.device.read(&mut buffer[start..]), "Failed to read from tap device: {}"); let size = try_fail!(self.device.read(&mut buffer[start..]), "Failed to read from tap device: {}");
match self.handle_interface_data(&mut buffer, start, start+size) { match self.handle_interface_data(&mut buffer, start, start+size) {

View File

@ -170,31 +170,31 @@ impl Crypto {
} }
pub fn method(&self) -> u8 { pub fn method(&self) -> u8 {
match self { match *self {
&Crypto::None => 0, Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, nonce: _} => 1, Crypto::ChaCha20Poly1305{..} => 1,
&Crypto::AES256GCM{state: _, nonce: _} => 2 Crypto::AES256GCM{..} => 2
} }
} }
pub fn nonce_bytes(&self) -> usize { pub fn nonce_bytes(&self) -> usize {
match self { match *self {
&Crypto::None => 0, Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, ref nonce} => nonce.len(), Crypto::ChaCha20Poly1305{ref nonce, ..} => nonce.len(),
&Crypto::AES256GCM{state: _, ref nonce} => nonce.len() Crypto::AES256GCM{ref nonce, ..} => nonce.len()
} }
} }
pub fn additional_bytes(&self) -> usize { pub fn additional_bytes(&self) -> usize {
match self { match *self {
&Crypto::None => 0, Crypto::None => 0,
&Crypto::ChaCha20Poly1305{key: _, nonce: _} => crypto_aead_chacha20poly1305_ietf_ABYTES, Crypto::ChaCha20Poly1305{..} => crypto_aead_chacha20poly1305_ietf_ABYTES,
&Crypto::AES256GCM{state: _, nonce: _} => crypto_aead_aes256gcm_ABYTES Crypto::AES256GCM{..} => crypto_aead_aes256gcm_ABYTES
} }
} }
pub fn from_shared_key(method: CryptoMethod, password: &str) -> Self { pub fn from_shared_key(method: CryptoMethod, password: &str) -> Self {
let salt = "vpncloudVPNCLOUDvpncl0udVpnCloud".as_bytes(); let salt = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
assert_eq!(salt.len(), crypto_pwhash_scryptsalsa208sha256_SALTBYTES); assert_eq!(salt.len(), crypto_pwhash_scryptsalsa208sha256_SALTBYTES);
let mut key = [0; crypto_pwhash_scryptsalsa208sha256_STRBYTES]; let mut key = [0; crypto_pwhash_scryptsalsa208sha256_STRBYTES];
let res = unsafe { crypto_pwhash_scryptsalsa208sha256( let res = unsafe { crypto_pwhash_scryptsalsa208sha256(
@ -235,9 +235,9 @@ impl Crypto {
} }
pub fn decrypt(&self, mut buf: &mut [u8], nonce: &[u8], header: &[u8]) -> Result<usize, Error> { pub fn decrypt(&self, mut buf: &mut [u8], nonce: &[u8], header: &[u8]) -> Result<usize, Error> {
match self { match *self {
&Crypto::None => Ok(buf.len()), Crypto::None => Ok(buf.len()),
&Crypto::ChaCha20Poly1305{ref key, nonce: _} => { Crypto::ChaCha20Poly1305{ref key, ..} => {
let mut mlen: u64 = buf.len() as u64; let mut mlen: u64 = buf.len() as u64;
let res = unsafe { crypto_aead_chacha20poly1305_ietf_decrypt( let res = unsafe { crypto_aead_chacha20poly1305_ietf_decrypt(
buf.as_mut_ptr(), // Base pointer to buffer buf.as_mut_ptr(), // Base pointer to buffer
@ -255,7 +255,7 @@ impl Crypto {
_ => Err(Error::CryptoError("Failed to decrypt")) _ => Err(Error::CryptoError("Failed to decrypt"))
} }
}, },
&Crypto::AES256GCM{ref state, nonce: _} => { Crypto::AES256GCM{ref state, ..} => {
let mut mlen: u64 = buf.len() as u64; let mut mlen: u64 = buf.len() as u64;
let res = unsafe { crypto_aead_aes256gcm_decrypt_afternm( let res = unsafe { crypto_aead_aes256gcm_decrypt_afternm(
buf.as_mut_ptr(), // Base pointer to buffer buf.as_mut_ptr(), // Base pointer to buffer
@ -277,9 +277,9 @@ impl Crypto {
} }
pub fn encrypt(&mut self, mut buf: &mut [u8], mlen: usize, nonce_bytes: &mut [u8], header: &[u8]) -> usize { pub fn encrypt(&mut self, mut buf: &mut [u8], mlen: usize, nonce_bytes: &mut [u8], header: &[u8]) -> usize {
match self { match *self {
&mut Crypto::None => mlen, Crypto::None => mlen,
&mut Crypto::ChaCha20Poly1305{ref key, ref mut nonce} => { Crypto::ChaCha20Poly1305{ref key, ref mut nonce} => {
inc_nonce_12(nonce); inc_nonce_12(nonce);
let mut clen: u64 = buf.len() as u64; let mut clen: u64 = buf.len() as u64;
assert!(nonce_bytes.len() == nonce.len()); assert!(nonce_bytes.len() == nonce.len());
@ -301,7 +301,7 @@ impl Crypto {
} }
clen as usize clen as usize
}, },
&mut Crypto::AES256GCM{ref state, ref mut nonce} => { Crypto::AES256GCM{ref state, ref mut nonce} => {
inc_nonce_12(nonce); inc_nonce_12(nonce);
let mut clen: u64 = buf.len() as u64; let mut clen: u64 = buf.len() as u64;
assert!(nonce_bytes.len() == nonce.len()); assert!(nonce_bytes.len() == nonce.len());

View File

@ -47,7 +47,7 @@ impl Device {
Ok(Device{fd: try!(fs::OpenOptions::new().create(true).read(true).write(true).open(path)), ifname: ifname.to_string()}) Ok(Device{fd: try!(fs::OpenOptions::new().create(true).read(true).write(true).open(path)), ifname: ifname.to_string()})
} }
#[inline(always)] #[inline]
pub fn ifname(&self) -> &str { pub fn ifname(&self) -> &str {
&self.ifname &self.ifname
} }
@ -59,7 +59,7 @@ impl Device {
#[inline] #[inline]
pub fn write(&mut self, data: &[u8]) -> Result<(), Error> { pub fn write(&mut self, data: &[u8]) -> Result<(), Error> {
match self.fd.write_all(&data) { match self.fd.write_all(data) {
Ok(_) => self.fd.flush().map_err(|_| Error::TunTapDevError("Flush error")), Ok(_) => self.fd.flush().map_err(|_| Error::TunTapDevError("Flush error")),
Err(_) => Err(Error::TunTapDevError("Write error")) Err(_) => Err(Error::TunTapDevError("Write error"))
} }
@ -67,7 +67,7 @@ impl Device {
} }
impl AsRawFd for Device { impl AsRawFd for Device {
#[inline(always)] #[inline]
fn as_raw_fd(&self) -> RawFd { fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd() self.fd.as_raw_fd()
} }

View File

@ -32,8 +32,8 @@ impl Protocol for Frame {
let mut dst = [0; 16]; let mut dst = [0; 16];
src[0] = data[pos]; src[1] = data[pos+1]; src[0] = data[pos]; src[1] = data[pos+1];
dst[0] = data[pos]; dst[1] = data[pos+1]; dst[0] = data[pos]; dst[1] = data[pos+1];
src[2..8].clone_from_slice(&src_data); src[2..8].clone_from_slice(src_data);
dst[2..8].clone_from_slice(&dst_data); dst[2..8].clone_from_slice(dst_data);
Ok((Address{data: src, len: 8}, Address{data: dst, len: 8})) Ok((Address{data: src, len: 8}, Address{data: dst, len: 8}))
} else { } else {
let src = try!(Address::read_from_fixed(&src_data, 6)); let src = try!(Address::read_from_fixed(&src_data, 6));
@ -69,7 +69,7 @@ impl Table for SwitchTable {
let mut del: Vec<Address> = Vec::new(); let mut del: Vec<Address> = Vec::new();
for (key, val) in &self.table { for (key, val) in &self.table {
if val.timeout < now { if val.timeout < now {
del.push(key.clone()); del.push(*key);
} }
} }
for key in del { for key in del {
@ -102,9 +102,9 @@ impl Table for SwitchTable {
fn remove_all(&mut self, addr: &SocketAddr) { fn remove_all(&mut self, addr: &SocketAddr) {
let mut remove = Vec::new(); let mut remove = Vec::new();
for (key, val) in self.table.iter() { for (key, val) in &self.table {
if &val.address == addr { if &val.address == addr {
remove.push(key.clone()); remove.push(*key);
} }
} }
for key in remove { for key in remove {

View File

@ -140,7 +140,7 @@ impl Table for RoutingTable {
} }
fn remove_all(&mut self, addr: &SocketAddr) { fn remove_all(&mut self, addr: &SocketAddr) {
for (_key, entry) in self.0.iter_mut() { for (_key, entry) in &mut self.0 {
entry.retain(|entr| &entr.address != addr); entry.retain(|entr| &entr.address != addr);
} }
} }

View File

@ -47,12 +47,12 @@ use util::Duration;
struct SimpleLogger; struct SimpleLogger;
impl log::Log for SimpleLogger { impl log::Log for SimpleLogger {
#[inline(always)] #[inline]
fn enabled(&self, _metadata: &log::LogMetadata) -> bool { fn enabled(&self, _metadata: &log::LogMetadata) -> bool {
true true
} }
#[inline(always)] #[inline]
fn log(&self, record: &log::LogRecord) { fn log(&self, record: &log::LogRecord) {
if self.enabled(record.metadata()) { if self.enabled(record.metadata()) {
println!("{} - {}", record.level(), record.args()); println!("{} - {}", record.level(), record.args());
@ -87,9 +87,10 @@ fn run_script(script: String, ifname: &str) {
cmd.arg("-c").arg(&script).env("IFNAME", ifname); cmd.arg("-c").arg(&script).env("IFNAME", ifname);
debug!("Running script: {:?}", cmd); debug!("Running script: {:?}", cmd);
match cmd.status() { match cmd.status() {
Ok(status) => match status.success() { Ok(status) => if status.success() {
true => (), ()
false => error!("Script returned with error: {:?}", status.code()) } else {
error!("Script returned with error: {:?}", status.code())
}, },
Err(e) => error!("Failed to execute script {:?}: {}", script, e) Err(e) => error!("Failed to execute script {:?}: {}", script, e)
} }

View File

@ -5,6 +5,7 @@
use std::net::{SocketAddr, Ipv4Addr, Ipv6Addr}; use std::net::{SocketAddr, Ipv4Addr, Ipv6Addr};
use std::fmt; use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use std::hash::{Hash, Hasher};
use super::util::{bytes_to_hex, Encoder}; use super::util::{bytes_to_hex, Encoder};
@ -14,7 +15,7 @@ pub type NetworkId = u64;
pub type NodeId = [u8; NODE_ID_BYTES]; pub type NodeId = [u8; NODE_ID_BYTES];
#[derive(PartialOrd, Eq, Ord, Clone, Hash, Copy)] #[derive(PartialOrd, Eq, Ord, Clone, Copy)]
pub struct Address { pub struct Address {
pub data: [u8; 16], pub data: [u8; 16],
pub len: u8 pub len: u8
@ -70,6 +71,15 @@ impl PartialEq for Address {
} }
} }
impl Hash for Address {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write(&self.data[0..self.len as usize])
}
}
impl fmt::Display for Address { impl fmt::Display for Address {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let d = &self.data; let d = &self.data;
@ -121,7 +131,7 @@ impl FromStr for Address {
} }
return Ok(Address{data: bytes, len: 6}); return Ok(Address{data: bytes, len: 6});
} }
return Err(Error::ParseError("Failed to parse address")) Err(Error::ParseError("Failed to parse address"))
} }
} }
@ -156,7 +166,7 @@ impl FromStr for Range {
type Err=Error; type Err=Error;
fn from_str(text: &str) -> Result<Self, Self::Err> { fn from_str(text: &str) -> Result<Self, Self::Err> {
let pos = match text.find("/") { let pos = match text.find('/') {
Some(pos) => pos, Some(pos) => pos,
None => return Err(Error::ParseError("Invalid range format")) None => return Err(Error::ParseError("Invalid range format"))
}; };
@ -186,9 +196,9 @@ pub enum Type {
} }
impl fmt::Display for Type { impl fmt::Display for Type {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self { match *self {
&Type::Tun => write!(formatter, "tun"), Type::Tun => write!(formatter, "tun"),
&Type::Tap => write!(formatter, "tap"), Type::Tap => write!(formatter, "tap"),
} }
} }
} }
@ -200,11 +210,11 @@ pub enum Mode {
} }
impl fmt::Display for Mode { impl fmt::Display for Mode {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self { match *self {
&Mode::Normal => write!(formatter, "normal"), Mode::Normal => write!(formatter, "normal"),
&Mode::Hub => write!(formatter, "hub"), Mode::Hub => write!(formatter, "hub"),
&Mode::Switch => write!(formatter, "switch"), Mode::Switch => write!(formatter, "switch"),
&Mode::Router => write!(formatter, "router"), Mode::Router => write!(formatter, "router"),
} }
} }
} }
@ -231,13 +241,13 @@ pub enum Error {
} }
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self { match *self {
&Error::ParseError(ref msg) => write!(formatter, "{}", msg), Error::ParseError(ref msg) => write!(formatter, "{}", msg),
&Error::SocketError(ref msg) => write!(formatter, "{}", msg), Error::SocketError(ref msg) => write!(formatter, "{}", msg),
&Error::TunTapDevError(ref msg) => write!(formatter, "{}", msg), Error::TunTapDevError(ref msg) => write!(formatter, "{}", msg),
&Error::CryptoError(ref msg) => write!(formatter, "{}", msg), Error::CryptoError(ref msg) => write!(formatter, "{}", msg),
&Error::WrongNetwork(Some(net)) => write!(formatter, "wrong network id: {}", net), Error::WrongNetwork(Some(net)) => write!(formatter, "wrong network id: {}", net),
&Error::WrongNetwork(None) => write!(formatter, "wrong network id: none"), Error::WrongNetwork(None) => write!(formatter, "wrong network id: none"),
} }
} }
} }

View File

@ -26,7 +26,7 @@ struct TopHeader {
} }
impl TopHeader { impl TopHeader {
#[inline(always)] #[inline]
pub fn size() -> usize { pub fn size() -> usize {
8 8
} }
@ -74,9 +74,9 @@ pub enum Message<'a> {
impl<'a> fmt::Debug for Message<'a> { impl<'a> fmt::Debug for Message<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self { match *self {
&Message::Data(_, start, end) => write!(formatter, "Data({} bytes)", end-start), Message::Data(_, start, end) => write!(formatter, "Data({} bytes)", end-start),
&Message::Peers(ref peers) => { Message::Peers(ref peers) => {
try!(write!(formatter, "Peers [")); try!(write!(formatter, "Peers ["));
let mut first = true; let mut first = true;
for p in peers { for p in peers {
@ -88,8 +88,8 @@ impl<'a> fmt::Debug for Message<'a> {
} }
write!(formatter, "]") write!(formatter, "]")
}, },
&Message::Init(stage, ref node_id, ref peers) => write!(formatter, "Init(stage={}, node_id={}, {:?})", stage, bytes_to_hex(node_id), peers), Message::Init(stage, ref node_id, ref peers) => write!(formatter, "Init(stage={}, node_id={}, {:?})", stage, bytes_to_hex(node_id), peers),
&Message::Close => write!(formatter, "Close"), Message::Close => write!(formatter, "Close"),
} }
} }
} }
@ -196,19 +196,19 @@ pub fn decode<'a>(data: &'a mut [u8], crypto: &mut Crypto) -> Result<(Options, M
pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8], crypto: &mut Crypto) -> &'a mut [u8] { pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8], crypto: &mut Crypto) -> &'a mut [u8] {
let mut start = 64; let mut start = 64;
let mut end = 64; let mut end = 64;
match msg { match *msg {
&mut Message::Data(ref mut data, data_start, data_end) => { Message::Data(ref mut data, data_start, data_end) => {
buf = data; buf = data;
start = data_start; start = data_start;
end = data_end; end = data_end;
}, },
&mut Message::Peers(ref peers) => { Message::Peers(ref peers) => {
let mut v4addrs = Vec::new(); let mut v4addrs = Vec::new();
let mut v6addrs = Vec::new(); let mut v6addrs = Vec::new();
for p in peers { for p in peers {
match p { match *p {
&SocketAddr::V4(addr) => v4addrs.push(addr), SocketAddr::V4(addr) => v4addrs.push(addr),
&SocketAddr::V6(addr) => v6addrs.push(addr) SocketAddr::V6(addr) => v6addrs.push(addr)
} }
}; };
assert!(v4addrs.len() <= 255); assert!(v4addrs.len() <= 255);
@ -237,7 +237,7 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
}; };
end = pos; end = pos;
}, },
&mut Message::Init(stage, ref node_id, ref ranges) => { Message::Init(stage, ref node_id, ref ranges) => {
let mut pos = start; let mut pos = start;
assert!(buf.len() >= pos + 2 + NODE_ID_BYTES); assert!(buf.len() >= pos + 2 + NODE_ID_BYTES);
buf[pos] = stage; buf[pos] = stage;
@ -252,7 +252,7 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
} }
end = pos; end = pos;
}, },
&mut Message::Close => { Message::Close => {
} }
} }
assert!(start >= 64); assert!(start >= 64);
@ -265,11 +265,11 @@ pub fn encode<'a>(options: &Options, msg: &'a mut Message, mut buf: &'a mut [u8]
let crypto_start = start; let crypto_start = start;
start -= crypto.nonce_bytes(); start -= crypto.nonce_bytes();
let mut header = TopHeader::default(); let mut header = TopHeader::default();
header.msgtype = match msg { header.msgtype = match *msg {
&mut Message::Data(_, _, _) => 0, Message::Data(_, _, _) => 0,
&mut Message::Peers(_) => 1, Message::Peers(_) => 1,
&mut Message::Init(_, _, _) => 2, Message::Init(_, _, _) => 2,
&mut Message::Close => 3 Message::Close => 3
}; };
header.crypto_method = crypto.method(); header.crypto_method = crypto.method();
if options.network_id.is_some() { if options.network_id.is_some() {

View File

@ -42,18 +42,18 @@ pub fn bytes_to_hex(bytes: &[u8]) -> String {
pub struct Encoder; pub struct Encoder;
impl Encoder { impl Encoder {
#[inline(always)] #[inline]
pub fn read_u16(data: &[u8]) -> u16 { pub fn read_u16(data: &[u8]) -> u16 {
((data[0] as u16) << 8) | data[1] as u16 ((data[0] as u16) << 8) | data[1] as u16
} }
#[inline(always)] #[inline]
pub fn write_u16(val: u16, data: &mut [u8]) { pub fn write_u16(val: u16, data: &mut [u8]) {
data[0] = ((val >> 8) & 0xff) as u8; data[0] = ((val >> 8) & 0xff) as u8;
data[1] = (val & 0xff) as u8; data[1] = (val & 0xff) as u8;
} }
#[inline(always)] #[inline]
pub fn read_u64(data: &[u8]) -> u64 { pub fn read_u64(data: &[u8]) -> u64 {
((data[0] as u64) << 56) | ((data[1] as u64) << 48) | ((data[0] as u64) << 56) | ((data[1] as u64) << 48) |
((data[2] as u64) << 40) | ((data[3] as u64) << 32) | ((data[2] as u64) << 40) | ((data[3] as u64) << 32) |
@ -61,7 +61,7 @@ impl Encoder {
((data[6] as u64) << 8) | data[7] as u64 ((data[6] as u64) << 8) | data[7] as u64
} }
#[inline(always)] #[inline]
pub fn write_u64(val: u64, data: &mut [u8]) { pub fn write_u64(val: u64, data: &mut [u8]) {
data[0] = ((val >> 56) & 0xff) as u8; data[0] = ((val >> 56) & 0xff) as u8;
data[1] = ((val >> 48) & 0xff) as u8; data[1] = ((val >> 48) & 0xff) as u8;