From cacc5b1a6b4c9d6590fe90f4e514c7130905afd7 Mon Sep 17 00:00:00 2001 From: Nils Andreas Svee Date: Sat, 15 Oct 2022 14:58:05 +0200 Subject: [PATCH] Apply Clippy recommendations --- src/cake.rs | 10 +++++----- src/config.rs | 40 +++++++++++++++++---------------------- src/log.rs | 2 +- src/main.rs | 39 ++++++++++++++++++-------------------- src/netlink.rs | 2 +- src/pinger.rs | 22 ++++++++++----------- src/pinger_icmp.rs | 22 +++++++-------------- src/pinger_icmp_ts.rs | 22 +++++++-------------- src/ratecontroller.rs | 18 +++++++++--------- src/reflector_selector.rs | 4 ++-- src/utils.rs | 6 +++++- 11 files changed, 82 insertions(+), 105 deletions(-) diff --git a/src/cake.rs b/src/cake.rs index b20e4ff..56b840c 100644 --- a/src/cake.rs +++ b/src/cake.rs @@ -4,21 +4,21 @@ pub enum TcaCake { Pad = 1, BaseRate64 = 2, DiffservMode = 3, - ATM = 4, + Atm = 4, FlowMode = 5, Overhead = 6, - RTT = 7, + Rtt = 7, Target = 8, Autorate = 9, Memory = 10, - NAT = 11, + Nat = 11, Raw = 12, Wash = 13, - MPU = 14, + Mpu = 14, Ingress = 15, AckFilter = 16, SplitGso = 17, FwMark = 18, FwMarkStore = 19, - SCE = 20, + Sce = 20, } diff --git a/src/config.rs b/src/config.rs index 83c1866..bca5910 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,10 +33,10 @@ where #[derive(Clone, Copy, Debug)] pub enum MeasurementType { - ICMP = 1, - ICMPTimestamps, - NTP, - TCPTimestamps, + Icmp = 1, + IcmpTimestamps, + Ntp, + TcpTimestamps, } impl FromStr for MeasurementType { @@ -44,10 +44,10 @@ impl FromStr for MeasurementType { fn from_str(s: &str) -> Result { return match s.to_lowercase().as_str() { - "icmp" => Ok(MeasurementType::ICMP), - "icmp-timestamps" => Ok(MeasurementType::ICMPTimestamps), - "ntp" => Ok(MeasurementType::NTP), - "tcp-timestamps" => Ok(MeasurementType::TCPTimestamps), + "icmp" => Ok(MeasurementType::Icmp), + "icmp-timestamps" => Ok(MeasurementType::IcmpTimestamps), + "ntp" => Ok(MeasurementType::Ntp), + "tcp-timestamps" => Ok(MeasurementType::TcpTimestamps), &_ => Err(ConfigError::InvalidMeasurementType(s.to_string())), }; } @@ -150,7 +150,7 @@ impl Config { measurement_type: Self::get::( "SQMA_MEASUREMENT_TYPE", "sqm-autorate.@advanced_settings[0].measurement_type", - Some(MeasurementType::ICMPTimestamps), + Some(MeasurementType::IcmpTimestamps), )?, min_change_interval: Self::get::( "SQMA_MIN_CHANGE_INTERVAL", @@ -185,25 +185,19 @@ impl Config { }) } - fn get( - env_key: &str, - uci_key: &str, - default: Option, - ) -> Result { - return match Self::get_value(env_key, uci_key) { + fn get(env_key: &str, uci_key: &str, default: Option) -> Result { + match Self::get_value(env_key, uci_key) { Some(val) => match val.parse::() { Ok(parsed_val) => Ok(parsed_val), // Ran into an compilation error while trying to return the // error as-is, so using my own error type to indicate something went wrong while parsing Err(_) => Err(ConfigError::ParseError(env_key.to_string())), }, - None => { - return match default { - Some(val) => Ok(val), - None => Err(ConfigError::MissingValue(env_key.to_string())), - } - } - }; + None => match default { + Some(val) => Ok(val), + None => Err(ConfigError::MissingValue(env_key.to_string())), + }, + } } fn get_value(env_key: &str, uci_key: &str) -> Option { @@ -256,7 +250,7 @@ impl Config { } let line = line?; - let columns: Vec<&str> = line.split(",").collect(); + let columns: Vec<&str> = line.split(',').collect(); reflectors.push(IpAddr::from_str(columns[0])?); } diff --git a/src/log.rs b/src/log.rs index cf14a2e..6b0ecd8 100644 --- a/src/log.rs +++ b/src/log.rs @@ -13,7 +13,7 @@ const LOG_DATETIME_FORMAT: &[FormatItem] = format_description!( #[derive(Clone, Copy)] pub struct SimpleLogger { - pub level: log::Level, + pub level: Level, } fn time_format(dt: T, format: &(impl Formattable + ?Sized)) -> String diff --git a/src/main.rs b/src/main.rs index 9381611..2107aa2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -78,15 +78,15 @@ fn main() -> anyhow::Result<()> { let (reselect_sender, reselect_receiver) = channel(); let (mut pinger_receiver, mut pinger_sender) = match config.measurement_type { - MeasurementType::ICMP => ( + MeasurementType::Icmp => ( Box::new(PingerICMPEchoListener {}) as Box, Box::new(PingerICMPEchoSender {}) as Box, ), - MeasurementType::ICMPTimestamps => ( + MeasurementType::IcmpTimestamps => ( Box::new(PingerICMPTimestampListener {}) as Box, Box::new(PingerICMPTimestampSender {}) as Box, ), - MeasurementType::NTP | MeasurementType::TCPTimestamps => { + MeasurementType::Ntp | MeasurementType::TcpTimestamps => { todo!() } }; @@ -150,30 +150,27 @@ fn main() -> anyhow::Result<()> { // Sleep 10 seconds before we start adjusting speeds sleep(Duration::new(10, 0)); - let dl_direction; - let ul_direction; - - if config.download_interface.starts_with("ifb") || config.download_interface.starts_with("veth") + let dl_direction = if config.download_interface.starts_with("ifb") + || config.download_interface.starts_with("veth") { - dl_direction = StatsDirection::TX; - } else if config.download_interface == "br-lan" { - dl_direction = StatsDirection::RX; + StatsDirection::TX } else { - dl_direction = StatsDirection::RX; - } - - if config.upload_interface.starts_with("ifb") || config.upload_interface.starts_with("veth") { - ul_direction = StatsDirection::RX; + StatsDirection::RX + }; + let ul_direction = if config.upload_interface.starts_with("ifb") + || config.upload_interface.starts_with("veth") + { + StatsDirection::RX } else { - ul_direction = StatsDirection::TX; - } + StatsDirection::TX + }; let mut ratecontroller = Ratecontroller::new( config.clone(), - owd_baseline.clone(), - owd_recent.clone(), - reflector_peers_lock.clone(), - reselect_sender.clone(), + owd_baseline, + owd_recent, + reflector_peers_lock, + reselect_sender, )?; debug!( diff --git a/src/netlink.rs b/src/netlink.rs index eb8fcfd..8a40dad 100644 --- a/src/netlink.rs +++ b/src/netlink.rs @@ -241,7 +241,7 @@ impl Netlink { } } - return Err(NetlinkError::NoQdiscFound(ifindex.to_string())); + Err(NetlinkError::NoQdiscFound(ifindex.to_string())) } pub fn qdisc_from_ifname(ifname: &str) -> Result { diff --git a/src/pinger.rs b/src/pinger.rs index 3f18949..f63cce6 100644 --- a/src/pinger.rs +++ b/src/pinger.rs @@ -40,12 +40,12 @@ pub struct PingReply { pub last_receive_time_s: f64, } -fn open_socket(type_: MeasurementType) -> std::io::Result { +fn open_socket(type_: MeasurementType) -> io::Result { match type_ { - MeasurementType::ICMP | MeasurementType::ICMPTimestamps => { + MeasurementType::Icmp | MeasurementType::IcmpTimestamps => { Socket::new(Domain::IPV4, Type::RAW, Some(Protocol::ICMPV4)) } - MeasurementType::NTP => Socket::new(Domain::IPV4, Type::DGRAM, None), + MeasurementType::Ntp => Socket::new(Domain::IPV4, Type::DGRAM, None), _ => { unimplemented!() } @@ -131,20 +131,18 @@ pub trait PingSender { drop(reflectors_unlocked); for reflector in reflectors.iter() { - let addr: SockAddr; - - match reflector.is_ipv4() { + let addr: SockAddr = match reflector.is_ipv4() { true => { let ip4 = Ipv4Addr::from_str(&*reflector.to_string()).unwrap(); let sock4 = SocketAddrV4::new(ip4, 0); - addr = sock4.into(); + sock4.into() } false => { let ip6 = Ipv6Addr::from_str(&*reflector.to_string()).unwrap(); let sock6 = SocketAddrV6::new(ip6, 0, 0, 0); - addr = sock6.into(); + sock6.into() } - } + }; let buf_v = self.craft_packet(id, seq); let buf = buf_v.as_slice(); @@ -154,10 +152,10 @@ pub trait PingSender { thread::sleep(sleep_duration); - seq += 1; - - if seq >= u16::MAX { + if seq == u16::MAX { seq = 0; + } else { + seq += 1; } } } diff --git a/src/pinger_icmp.rs b/src/pinger_icmp.rs index fd9329a..80e97e4 100644 --- a/src/pinger_icmp.rs +++ b/src/pinger_icmp.rs @@ -15,7 +15,7 @@ impl PingListener for PingerICMPEchoListener { // Result: RTT, down time, up time fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result { match SlicedPacket::from_ip(buf) { - Err(err) => return Err(PingError::InvalidPacket(err)), + Err(err) => Err(PingError::InvalidPacket(err)), Ok(value) => match value.transport { Some(Icmpv4(icmp)) => match icmp.icmp_type() { Icmpv4Type::EchoReply(echo) => { @@ -36,7 +36,7 @@ impl PingListener for PingerICMPEchoListener { let time_ms = clock.to_milliseconds() as i64; let rtt: i64 = time_ms - time_sent; - return Ok(PingReply { + Ok(PingReply { reflector, seq: echo.seq, rtt, @@ -48,21 +48,13 @@ impl PingListener for PingerICMPEchoListener { transmit_timestamp: 0, last_receive_time_s: clock.get_seconds() as f64 + (clock.get_nanoseconds() as f64 / 1e9), - }); - } - type_ => { - return Err(PingError::InvalidType(format!("{:?}", type_))); + }) } + type_ => Err(PingError::InvalidType(format!("{:?}", type_))), }, - Some(Icmpv6(slice)) => { - return Err(PingError::InvalidProtocol(format!("{:?}", slice))); - } - Some(type_) => { - return Err(PingError::InvalidProtocol(format!("{:?}", type_))); - } - None => { - return Err(PingError::NoTransport); - } + Some(Icmpv6(slice)) => Err(PingError::InvalidProtocol(format!("{:?}", slice))), + Some(type_) => Err(PingError::InvalidProtocol(format!("{:?}", type_))), + None => Err(PingError::NoTransport), }, } } diff --git a/src/pinger_icmp_ts.rs b/src/pinger_icmp_ts.rs index b4ac07d..3093a2f 100644 --- a/src/pinger_icmp_ts.rs +++ b/src/pinger_icmp_ts.rs @@ -15,7 +15,7 @@ impl PingListener for PingerICMPTimestampListener { // Result: RTT, down time, up time fn parse_packet(&self, id: u16, reflector: IpAddr, buf: &[u8]) -> Result { match SlicedPacket::from_ip(buf) { - Err(err) => return Err(PingError::InvalidPacket(err)), + Err(err) => Err(PingError::InvalidPacket(err)), Ok(value) => match value.transport { Some(Icmpv4(icmp)) => match icmp.icmp_type() { Icmpv4Type::TimestampReply(reply) => { @@ -37,7 +37,7 @@ impl PingListener for PingerICMPTimestampListener { let dl_time: i64 = time_since_midnight - transmit_timestamp as i64; let ul_time: i64 = receive_timestamp as i64 - originate_timestamp as i64; - return Ok(PingReply { + Ok(PingReply { reflector, seq: reply.seq, rtt, @@ -49,21 +49,13 @@ impl PingListener for PingerICMPTimestampListener { transmit_timestamp: transmit_timestamp as i64, last_receive_time_s: time_now.get_seconds() as f64 + (time_now.get_nanoseconds() as f64 / 1e9), - }); - } - type_ => { - return Err(PingError::InvalidType(format!("{:?}", type_))); + }) } + type_ => Err(PingError::InvalidType(format!("{:?}", type_))), }, - Some(Icmpv6(slice)) => { - return Err(PingError::InvalidType(format!("{:?}", slice))); - } - Some(type_) => { - return Err(PingError::InvalidType(format!("{:?}", type_))); - } - None => { - return Err(PingError::NoTransport); - } + Some(Icmpv6(slice)) => Err(PingError::InvalidType(format!("{:?}", slice))), + Some(type_) => Err(PingError::InvalidType(format!("{:?}", type_))), + None => Err(PingError::NoTransport), }, } } diff --git a/src/ratecontroller.rs b/src/ratecontroller.rs index bd57d7f..9d9612c 100644 --- a/src/ratecontroller.rs +++ b/src/ratecontroller.rs @@ -39,7 +39,7 @@ fn generate_initial_speeds(base_speed: f64, size: u32) -> Vec { let mut rates = Vec::new(); for _ in 0..size { - rates.push((rand::thread_rng().next_u64() as f64 * 0.2 + 0.75) * base_speed); + rates.push((thread_rng().next_u64() as f64 * 0.2 + 0.75) * base_speed); } rates @@ -116,7 +116,7 @@ impl Ratecontroller { debug!("direction: {:?} -> state: {:#?}", direction, state); - if state.deltas.len() > 0 { + if !state.deltas.is_empty() { state.next_rate = state.current_rate; if state.deltas.len() < 3 { @@ -148,8 +148,8 @@ impl Ratecontroller { state.next_rate = state.current_rate * (1.0 + 0.1 * (1.0_f64 - state.current_rate / max_rate).max(0.0)) + (base_rate * 0.03); - state.nrate = state.nrate + 1; - state.nrate = state.nrate % self.config.speed_hist_size as usize; + state.nrate += 1; + state.nrate %= self.config.speed_hist_size as usize; } if state.delta_stat > delay_ms { @@ -314,7 +314,7 @@ impl Ratecontroller { .write(true) .open(self.config.speed_hist_file.as_str())?; - speed_hist_fd_inner.write("time,counter,upspeed,downspeed\n".as_bytes())?; + speed_hist_fd_inner.write_all("time,counter,upspeed,downspeed\n".as_bytes())?; speed_hist_fd_inner.flush()?; speed_hist_fd = Some(speed_hist_fd_inner); @@ -324,7 +324,7 @@ impl Ratecontroller { .write(true) .open(self.config.stats_file.as_str())?; - stats_fd_inner.write( + stats_fd_inner.write_all( "times,timens,rxload,txload,deltadelaydown,deltadelayup,dlrate,uprate\n".as_bytes(), )?; stats_fd_inner.flush()?; @@ -338,7 +338,7 @@ impl Ratecontroller { let now = Clock::new(ClockId::Monotonic); let (mut now_s, now_ns) = (now.get_seconds() as f64, now.get_nanoseconds() as f64); let now_abstime = now_s + now_ns / 1e9; - now_s = now_s - start_s; + now_s -= start_s; let now_t = now_s + now_ns / 1e9; if now_t - lastchg_t > self.config.min_change_interval { @@ -416,14 +416,14 @@ impl Ratecontroller { } } - lastchg_s = lastchg_s - start_s; + lastchg_s -= start_s; lastchg_t = lastchg_s + lastchg_ns / 1e9; } if let Some(ref mut fd) = speed_hist_fd { if now_t - lastdump_t > 300.0 { for i in 0..self.config.speed_hist_size as usize { - if let Err(e) = fd.write( + if let Err(e) = fd.write_all( format!( "{},{},{},{}\n", now_t, i, self.state_ul.safe_rates[i], self.state_dl.safe_rates[i] diff --git a/src/reflector_selector.rs b/src/reflector_selector.rs index 560c8ff..8328877 100644 --- a/src/reflector_selector.rs +++ b/src/reflector_selector.rs @@ -99,7 +99,7 @@ impl ReflectorSelector { candidates.sort_by(|a, b| a.1.cmp(&b.1)); // Now we will just limit the candidates down to 2 * num_reflectors - let mut num_reflectors = self.config.num_reflectors.clone(); + let mut num_reflectors = self.config.num_reflectors; let candidate_pool_num = (2 * num_reflectors) as usize; candidates = candidates[0..candidate_pool_num - 1].to_vec(); @@ -108,7 +108,7 @@ impl ReflectorSelector { } // Shuffle the deck so we avoid overwhelming good reflectors (Fisher-Yates) - for i in (1 as usize..candidates.len()).rev() { + for i in (1_usize..candidates.len()).rev() { let j = rng.gen_range(0..(i + 1)); candidates.swap(i, j); } diff --git a/src/utils.rs b/src/utils.rs index aa35045..262eba0 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -2,7 +2,11 @@ pub struct Utils {} impl Utils { pub fn a_else_b(a: f64, b: f64) -> f64 { - return if a > 0.0 { a } else { b }; + if a > 0.0 { + a + } else { + b + } } pub fn ewma_factor(tick: f64, dur: f64) -> f64 { ((0.5_f64).ln() / (dur / tick)).exp()