Parcourir la source

Merge pull request #403 from crawford/clippy

Last round of suggestions by clippy
whitequark il y a 4 ans
Parent
commit
5cfbfbb02e

+ 1 - 0
.github/workflows/clippy.yml

@@ -23,3 +23,4 @@ jobs:
       - uses: actions-rs/clippy-check@v1
         with:
           token: ${{ secrets.GITHUB_TOKEN }}
+          args: -- -D warnings

+ 2 - 0
examples/benchmark.rs

@@ -1,3 +1,5 @@
+#![allow(clippy::collapsible_if)]
+
 mod utils;
 
 use std::cmp;

+ 1 - 1
examples/dhcp_client.rs

@@ -95,6 +95,6 @@ fn main() {
         iface.poll_delay(&sockets, timestamp)
             .map(|sockets_timeout| timeout = sockets_timeout);
         phy_wait(fd, Some(timeout))
-            .unwrap_or_else(|e| println!("Wait: {:?}", e));;
+            .unwrap_or_else(|e| println!("Wait: {:?}", e));
     }
 }

+ 1 - 0
examples/loopback.rs

@@ -1,5 +1,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 #![allow(unused_mut)]
+#![allow(clippy::collapsible_if)]
 
 #[cfg(feature = "std")]
 #[allow(dead_code)]

+ 10 - 21
src/iface/ethernet.rs

@@ -295,11 +295,11 @@ impl<'a> IpPacket<'a> {
     pub(crate) fn ip_repr(&self) -> IpRepr {
         match self {
             #[cfg(feature = "proto-ipv4")]
-            IpPacket::Icmpv4((ipv4_repr, _)) => IpRepr::Ipv4(ipv4_repr.clone()),
+            IpPacket::Icmpv4((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
             #[cfg(feature = "proto-igmp")]
-            IpPacket::Igmp((ipv4_repr, _)) => IpRepr::Ipv4(ipv4_repr.clone()),
+            IpPacket::Igmp((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
             #[cfg(feature = "proto-ipv6")]
-            IpPacket::Icmpv6((ipv6_repr, _)) => IpRepr::Ipv6(ipv6_repr.clone()),
+            IpPacket::Icmpv6((ipv6_repr, _)) => IpRepr::Ipv6(*ipv6_repr),
             #[cfg(feature = "socket-raw")]
             IpPacket::Raw((ip_repr, _)) => ip_repr.clone(),
             #[cfg(feature = "socket-udp")]
@@ -1156,11 +1156,7 @@ impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
             Icmpv6Repr::EchoRequest { ident, seq_no, data } => {
                 match ip_repr {
                     IpRepr::Ipv6(ipv6_repr) => {
-                        let icmp_reply_repr = Icmpv6Repr::EchoReply {
-                            ident:  ident,
-                            seq_no: seq_no,
-                            data:   data
-                        };
+                        let icmp_reply_repr = Icmpv6Repr::EchoReply { ident, seq_no, data };
                         Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
                     },
                     _ => Err(Error::Unrecognized),
@@ -1196,10 +1192,8 @@ impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
                     Some(lladdr) if lladdr.is_unicast() && target_addr.is_unicast() => {
                         if flags.contains(NdiscNeighborFlags::OVERRIDE) {
                             self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
-                        } else {
-                            if !self.neighbor_cache.lookup(&ip_addr, timestamp).found() {
-                                    self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
-                            }
+                        } else if !self.neighbor_cache.lookup(&ip_addr, timestamp).found() {
+                                self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
                         }
                     },
                     _ => (),
@@ -1295,11 +1289,7 @@ impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
             // Respond to echo requests.
             #[cfg(feature = "proto-ipv4")]
             Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
-                let icmp_reply_repr = Icmpv4Repr::EchoReply {
-                    ident:  ident,
-                    seq_no: seq_no,
-                    data:   data
-                };
+                let icmp_reply_repr = Icmpv4Repr::EchoReply { ident, seq_no, data };
                 match ip_repr {
                     IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
                     _ => Err(Error::Unrecognized),
@@ -1451,7 +1441,7 @@ impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
 
             match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
                 // The packet is valid and handled by socket.
-                Ok(reply) => return Ok(reply.map(|x| IpPacket::Tcp(x))),
+                Ok(reply) => return Ok(reply.map(IpPacket::Tcp)),
                 // The packet is malformed, or doesn't match the socket state,
                 // or the socket buffer is full.
                 Err(e) => return Err(e)
@@ -1686,14 +1676,13 @@ impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
     fn igmp_leave_packet<'any>(&self, group_addr: Ipv4Address) -> Option<IpPacket<'any>> {
         self.ipv4_address().map(|iface_addr| {
             let igmp_repr = IgmpRepr::LeaveGroup { group_addr };
-            let pkt = IpPacket::Igmp((Ipv4Repr {
+            IpPacket::Igmp((Ipv4Repr {
                 src_addr:    iface_addr,
                 dst_addr:    Ipv4Address::MULTICAST_ALL_ROUTERS,
                 protocol:    IpProtocol::Igmp,
                 payload_len: igmp_repr.buffer_len(),
                 hop_limit:   1,
-            }, igmp_repr));
-            pkt
+            }, igmp_repr))
         })
     }
 }

+ 3 - 0
src/lib.rs

@@ -91,6 +91,9 @@ compile_error!("at least one socket needs to be enabled"); */
 #![allow(clippy::if_same_then_else)]
 #![allow(clippy::manual_non_exhaustive)]
 #![allow(clippy::match_like_matches_macro)]
+#![allow(clippy::redundant_field_names)]
+#![allow(clippy::identity_op)]
+#![allow(clippy::option_map_unit_fn)]
 
 #[cfg(feature = "alloc")]
 extern crate alloc;

+ 4 - 4
src/parsers.rs

@@ -121,8 +121,8 @@ impl<'a> Parser<'a> {
     #[cfg(feature = "ethernet")]
     fn accept_mac_joined_with(&mut self, separator: u8) -> Result<EthernetAddress> {
         let mut octets = [0u8; 6];
-        for n in 0..6 {
-            octets[n] = self.accept_number(2, 0x100, true)? as u8;
+        for (n, octet) in octets.iter_mut().enumerate() {
+            *octet = self.accept_number(2, 0x100, true)? as u8;
             if n != 5 {
                 self.accept_char(separator)?;
             }
@@ -270,8 +270,8 @@ impl<'a> Parser<'a> {
 
     fn accept_ipv4_octets(&mut self) -> Result<[u8; 4]> {
         let mut octets = [0u8; 4];
-        for n in 0..4 {
-            octets[n] = self.accept_number(3, 0x100, false)? as u8;
+        for (n, octet) in octets.iter_mut().enumerate() {
+            *octet = self.accept_number(3, 0x100, false)? as u8;
             if n != 3 {
                 self.accept_char(b'.')?;
             }

+ 2 - 1
src/phy/loopback.rs

@@ -19,6 +19,7 @@ pub struct Loopback {
     queue: VecDeque<Vec<u8>>,
 }
 
+#[allow(clippy::new_without_default)]
 impl Loopback {
     /// Creates a loopback device.
     ///
@@ -44,7 +45,7 @@ impl<'a> Device<'a> for Loopback {
 
     fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
         self.queue.pop_front().map(move |buffer| {
-            let rx = RxToken { buffer: buffer };
+            let rx = RxToken { buffer };
             let tx = TxToken { queue: &mut self.queue };
             (rx, tx)
         })

+ 3 - 3
src/phy/pcap_writer.rs

@@ -146,8 +146,8 @@ impl<'a, D, S> Device<'a> for PcapWriter<D, S>
     fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
         let &mut Self { ref mut lower, ref sink, mode, .. } = self;
         lower.receive().map(|(rx_token, tx_token)| {
-            let rx = RxToken { token: rx_token, sink: sink.clone(), mode: mode };
-            let tx = TxToken { token: tx_token, sink: sink.clone(), mode: mode };
+            let rx = RxToken { token: rx_token, sink: sink.clone(), mode };
+            let tx = TxToken { token: tx_token, sink: sink.clone(), mode };
             (rx, tx)
         })
     }
@@ -155,7 +155,7 @@ impl<'a, D, S> Device<'a> for PcapWriter<D, S>
     fn transmit(&'a mut self) -> Option<Self::TxToken> {
         let &mut Self { ref mut lower, ref sink, mode } = self;
         lower.transmit().map(|token| {
-            TxToken { token, sink: sink.clone(), mode: mode }
+            TxToken { token, sink: sink.clone(), mode }
         })
     }
 }

+ 0 - 3
src/phy/sys/linux.rs

@@ -1,5 +1,3 @@
-use libc;
-
 #[cfg(any(feature = "phy-raw_socket",
           feature = "phy-tap_interface"))]
 pub const SIOCGIFMTU:   libc::c_ulong = 0x8921;
@@ -14,4 +12,3 @@ pub const TUNSETIFF:    libc::c_ulong = 0x400454CA;
 pub const IFF_TAP:      libc::c_int   = 0x0002;
 #[cfg(feature = "phy-tap_interface")]
 pub const IFF_NO_PI:    libc::c_int   = 0x1000;
-

+ 0 - 1
src/phy/sys/mod.rs

@@ -1,6 +1,5 @@
 #![allow(unsafe_code)]
 
-use libc;
 use std::{mem, ptr, io};
 use std::os::unix::io::RawFd;
 use crate::time::Duration;

+ 0 - 1
src/phy/sys/raw_socket.rs

@@ -1,6 +1,5 @@
 use std::{mem, io};
 use std::os::unix::io::{RawFd, AsRawFd};
-use libc;
 use super::*;
 use crate::wire::EthernetFrame;
 

+ 0 - 1
src/phy/sys/tap_interface.rs

@@ -1,6 +1,5 @@
 use std::io;
 use std::os::unix::io::{RawFd, AsRawFd};
-use libc;
 use super::*;
 use crate::wire::EthernetFrame;
 

+ 3 - 3
src/phy/tracer.rs

@@ -52,8 +52,8 @@ impl<'a, D, P> Device<'a> for Tracer<D, P>
     fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
         let &mut Self { ref mut inner, writer, .. } = self;
         inner.receive().map(|(rx_token, tx_token)| {
-            let rx = RxToken { token: rx_token, writer: writer };
-            let tx = TxToken { token: tx_token, writer: writer };
+            let rx = RxToken { token: rx_token, writer };
+            let tx = TxToken { token: tx_token, writer };
             (rx, tx)
         })
     }
@@ -61,7 +61,7 @@ impl<'a, D, P> Device<'a> for Tracer<D, P>
     fn transmit(&'a mut self) -> Option<Self::TxToken> {
         let &mut Self { ref mut inner, writer } = self;
         inner.transmit().map(|tx_token| {
-            TxToken { token: tx_token, writer: writer }
+            TxToken { token: tx_token, writer }
         })
     }
 }

+ 2 - 4
src/socket/set.rs

@@ -38,9 +38,7 @@ impl<'a, 'b: 'a, 'c: 'a + 'b> Set<'a, 'b, 'c> {
     pub fn new<SocketsT>(sockets: SocketsT) -> Set<'a, 'b, 'c>
             where SocketsT: Into<ManagedSlice<'a, Option<Item<'b, 'c>>>> {
         let sockets = sockets.into();
-        Set {
-            sockets: sockets
-        }
+        Set { sockets }
     }
 
     /// Add a socket to the set with the reference count 1, and return its handle.
@@ -55,7 +53,7 @@ impl<'a, 'b: 'a, 'c: 'a + 'b> Set<'a, 'b, 'c> {
             net_trace!("[{}]: adding", index);
             let handle = Handle(index);
             socket.meta_mut().handle = handle;
-            *slot = Some(Item { socket: socket, refs: 1 });
+            *slot = Some(Item { socket, refs: 1 });
             handle
         }
 

+ 4 - 7
src/wire/dhcpv4.rs

@@ -759,14 +759,11 @@ impl<'a> Repr<'a> {
                     parameter_request_list = Some(data);
                 }
                 DhcpOption::Other {kind: field::OPT_DOMAIN_NAME_SERVER, data} => {
-                    let mut dns_servers_inner = [None; 3];
-                    for i in 0..3 {
-                        let offset = 4 * i;
-                        let end = offset + 4;
-                        if end > data.len() { break }
-                        dns_servers_inner[i] = Some(Ipv4Address::from_bytes(&data[offset..end]));
+                    let mut servers = [None; 3];
+                    for (server, chunk) in servers.iter_mut().zip(data.chunks(4)) {
+                        *server = Some(Ipv4Address::from_bytes(chunk));
                     }
-                    dns_servers = Some(dns_servers_inner);
+                    dns_servers = Some(servers);
                 }
                 DhcpOption::Other {..} => {}
             }

+ 2 - 6
src/wire/icmpv6.rs

@@ -271,14 +271,10 @@ impl<T: AsRef<[u8]>> Packet<T> {
     /// Returns `Err(Error::Truncated)` if the buffer is too short.
     pub fn check_len(&self) -> Result<()> {
         let len = self.buffer.as_ref().len();
-        if len < field::HEADER_END {
+        if len < field::HEADER_END || len < self.header_len() {
             Err(Error::Truncated)
         } else {
-            if len < self.header_len() {
-                Err(Error::Truncated)
-            } else {
-                Ok(())
-            }
+            Ok(())
         }
     }
 

+ 7 - 8
src/wire/ip.rs

@@ -108,6 +108,7 @@ impl Address {
 
     /// Create an address wrapping an IPv6 address with the given octets.
     #[cfg(feature = "proto-ipv6")]
+    #[allow(clippy::too_many_arguments)]
     pub fn v6(a0: u16, a1: u16, a2: u16, a3: u16,
               a4: u16, a5: u16, a6: u16, a7: u16) -> Address {
         Address::Ipv6(Ipv6Address::new(a0, a1, a2, a3, a4, a5, a6, a7))
@@ -201,11 +202,9 @@ impl Address {
                     } else {
                         ones = false;
                     }
-                } else {
-                    if one {
-                        // 1 where 0 was expected
-                        return None
-                    }
+                } else if one {
+                    // 1 where 0 was expected
+                    return None
                 }
                 mask >>= 1;
             }
@@ -408,7 +407,7 @@ impl Endpoint {
 
     /// Create an endpoint address from given address and port.
     pub fn new(addr: Address, port: u16) -> Endpoint {
-        Endpoint { addr: addr, port: port }
+        Endpoint { addr, port }
     }
 
     /// Query whether the endpoint has a specified address and port.
@@ -455,13 +454,13 @@ impl fmt::Display for Endpoint {
 
 impl From<u16> for Endpoint {
     fn from(port: u16) -> Endpoint {
-        Endpoint { addr: Address::Unspecified, port: port }
+        Endpoint { addr: Address::Unspecified, port }
     }
 }
 
 impl<T: Into<Address>> From<(T, u16)> for Endpoint {
     fn from((addr, port): (T, u16)) -> Endpoint {
-        Endpoint { addr: addr.into(), port: port }
+        Endpoint { addr: addr.into(), port }
     }
 }
 

+ 5 - 6
src/wire/ipv6.rs

@@ -47,6 +47,7 @@ impl Address {
                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]);
 
     /// Construct an IPv6 address from parts.
+    #[allow(clippy::too_many_arguments)]
     pub fn new(a0: u16, a1: u16, a2: u16, a3: u16,
                a4: u16, a5: u16, a6: u16, a7: u16) -> Address {
         let mut addr = [0u8; 16];
@@ -78,9 +79,8 @@ impl Address {
     pub fn from_parts(data: &[u16]) -> Address {
         assert!(data.len() >= 8);
         let mut bytes = [0; 16];
-        for word_idx in 0..8 {
-            let byte_idx = word_idx * 2;
-            NetworkEndian::write_u16(&mut bytes[byte_idx..(byte_idx + 2)], data[word_idx]);
+        for (word_idx, chunk) in bytes.chunks_mut(2).enumerate() {
+            NetworkEndian::write_u16(chunk, data[word_idx]);
         }
         Address(bytes)
     }
@@ -91,9 +91,8 @@ impl Address {
     /// The function panics if `data` is not 8 words long.
     pub fn write_parts(&self, data: &mut [u16]) {
         assert!(data.len() >= 8);
-        for i in 0..8 {
-            let byte_idx = i * 2;
-            data[i] = NetworkEndian::read_u16(&self.0[byte_idx..(byte_idx + 2)]);
+        for (i, chunk) in self.0.chunks(2).enumerate() {
+            data[i] = NetworkEndian::read_u16(chunk);
         }
     }
 

+ 1 - 1
src/wire/pretty_print.rs

@@ -43,7 +43,7 @@ impl PrettyIndent {
     /// Create an indentation state. The entire listing will be indented by the width
     /// of `prefix`, and `prefix` will appear at the start of the first line.
     pub fn new(prefix: &'static str) -> PrettyIndent {
-        PrettyIndent { prefix: prefix, level: 0 }
+        PrettyIndent { prefix, level: 0 }
     }
 
     /// Increase indentation level.

+ 1 - 1
src/wire/tcp.rs

@@ -629,7 +629,7 @@ impl<'a> TcpOption<'a> {
                         option = TcpOption::SackRange(sack_ranges);
                     },
                     (_, _) =>
-                        option = TcpOption::Unknown { kind: kind, data: data }
+                        option = TcpOption::Unknown { kind, data }
                 }
             }
         }