From b1c0cf82c2af455526a9041b0844c283b356f2f2 Mon Sep 17 00:00:00 2001 From: wyhaya Date: Fri, 15 Nov 2019 16:49:14 +0800 Subject: [PATCH] reference clippy optimization --- Dockerfile | 2 +- src/config.rs | 20 +++++++++------- src/lib.rs | 1 + src/main.rs | 66 ++++++++++++++++++++++++++------------------------- src/watch.rs | 15 ++++++------ 5 files changed, 55 insertions(+), 49 deletions(-) diff --git a/Dockerfile b/Dockerfile index 5d62349..f9e76be 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ -FROM rustlang/rust:nightly as builder +FROM rust as builder WORKDIR /root COPY . /root RUN cargo build --release diff --git a/src/config.rs b/src/config.rs index fc2dde4..fe3ff71 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,15 @@ use futures::future::{BoxFuture, FutureExt}; use regex::Regex; -use std::net::{IpAddr, SocketAddr}; -use std::path::{Path, PathBuf}; -use std::result; -use std::slice::Iter; -use tokio::fs::{create_dir_all, File, OpenOptions}; -use tokio::io::{AsyncReadExt, AsyncWriteExt, Result}; +use std::{ + net::{IpAddr, SocketAddr}, + path::{Path, PathBuf}, + result, + slice::Iter, +}; +use tokio::{ + fs::{create_dir_all, File, OpenOptions}, + io::{AsyncReadExt, AsyncWriteExt, Result}, +}; lazy_static! { static ref REG_IGNORE: Regex = Regex::new(r#"^\s*(#.*)?$"#).unwrap(); @@ -65,7 +69,7 @@ fn cap_ip_addr(text: &str) -> Option return Some(Err(InvalidType::Regex)), }; - return Some(Ok((reg, ip))); + Some(Ok((reg, ip))) } #[derive(Debug)] @@ -192,7 +196,7 @@ impl Config { } pub async fn add(&mut self, domain: &str, ip: &str) -> Result { - if self.read_to_string().await?.ends_with("\n") { + if self.read_to_string().await?.ends_with('\n') { self.file .write(format!("{} {}", domain, ip).as_bytes()) .await diff --git a/src/lib.rs b/src/lib.rs index 11a1201..527ff7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ // From : EmilHernvall/dnsguide // GitHub : https://github.com/EmilHernvall/dnsguide +#![allow(clippy::all)] #![allow(dead_code)] use std::io::{Error, ErrorKind, Result}; diff --git a/src/main.rs b/src/main.rs index 2190578..2388ccb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,21 +10,25 @@ use config::{Config, Hosts, Invalid, ParseConfig}; use dirs; use lib::*; use regex::Regex; -use std::env::current_exe; -use std::net::{IpAddr, SocketAddr}; -use std::path::PathBuf; -use std::process::Command; -use std::time::Duration; -use tokio::io::{Error, ErrorKind, Result}; -use tokio::net::UdpSocket; -use tokio::prelude::*; -use tokio::timer::Timeout; +use std::{ + env, + net::{IpAddr, SocketAddr}, + path::PathBuf, + process::Command, + time::Duration, +}; +use tokio::{ + io::{Error, ErrorKind, Result}, + net::UdpSocket, + prelude::*, + timer::Timeout, +}; use watch::Watch; -const CONFIG_FILE: [&'static str; 2] = [".updns", "config"]; +const CONFIG_FILE: [&str; 2] = [".updns", "config"]; -const DEFAULT_BIND: &'static str = "0.0.0.0:53"; -const DEFAULT_PROXY: [&'static str; 2] = ["8.8.8.8:53", "1.1.1.1:53"]; +const DEFAULT_BIND: &str = "0.0.0.0:53"; +const DEFAULT_PROXY: [&str; 2] = ["8.8.8.8:53", "1.1.1.1:53"]; const DEFAULT_TIMEOUT: u64 = 2000; static mut PROXY: Vec = Vec::new(); @@ -91,8 +95,8 @@ async fn main() { if values.is_empty() { exit!("'-w' value: [ms]"); } - match &values[0].parse::() { - Ok(t) => *t, + match values[0].parse::() { + Ok(t) => t, Err(_) => exit!("Cannot resolve '{}' to number", &values[0]), } } @@ -102,7 +106,7 @@ async fn main() { if let Some(cmd) = app.command() { match cmd.as_str() { "add" => { - let values = app.value("add").unwrap_or(vec![]); + let values = app.value("add").unwrap_or_default(); if values.len() != 2 { exit!("'add' value: [DOMAIN] [IP]"); } @@ -114,7 +118,7 @@ async fn main() { err ); } - if let Err(_) = values[1].parse::() { + if values[1].parse::().is_err() { exit!("Cannot resolve '{}' to ip address", values[1]); } @@ -122,18 +126,19 @@ async fn main() { Ok(c) => c, Err(err) => exit!("Failed to read config file {:?}\n{:?}", &config_path, err), }; - if let Err(err) = config.add(&values[0], &values[1]).await { + if let Err(err) = config.add(values[0], values[1]).await { exit!("Add record failed\n{:?}", err); } } "ls" => { let mut config = config_parse(&config_path).await; - let mut n = 0; - for (reg, _) in config.hosts.iter() { - if reg.as_str().len() > n { - n = reg.as_str().len(); - } - } + + let n = config + .hosts + .iter() + .map(|(r, _)| r.as_str().len()) + .fold(0, |a, b| a.max(b)); + for (domain, ip) in config.hosts.iter() { println!("{:domain$} {}", domain.as_str(), ip, domain = n); } @@ -152,7 +157,7 @@ async fn main() { } } "path" => { - let binary = match current_exe() { + let binary = match env::current_exe() { Ok(p) => p.display().to_string(), Err(err) => exit!("Failed to get directory\n{:?}", err), }; @@ -185,7 +190,7 @@ async fn main() { // Run server for addr in parse.bind { - tokio::spawn(run_server(addr.clone())); + tokio::spawn(run_server(addr)); } // watch config watch_config(config_path, watch_interval).await; @@ -201,10 +206,7 @@ fn update_config(mut proxy: Vec, hosts: Hosts, timeout: Option) unsafe { PROXY = proxy; HOSTS = Some(hosts); - TIMEOUT = match timeout { - Some(t) => t, - None => DEFAULT_TIMEOUT, - }; + TIMEOUT = timeout.unwrap_or(DEFAULT_TIMEOUT); }; } @@ -223,7 +225,7 @@ async fn config_parse(file: &PathBuf) -> ParseConfig { parse } -fn output_invalid(errors: &Vec) { +fn output_invalid(errors: &[Invalid]) { for invalid in errors { error!( "[line:{}] {} `{}`", @@ -319,7 +321,7 @@ fn get_answer(domain: &str, query: QueryType) -> Option { if let IpAddr::V4(addr) = ip { return Some(DnsRecord::A { domain: domain.to_string(), - addr: addr.clone(), + addr: *addr, ttl: 3600, }); } @@ -328,7 +330,7 @@ fn get_answer(domain: &str, query: QueryType) -> Option { if let IpAddr::V6(addr) = ip { return Some(DnsRecord::AAAA { domain: domain.to_string(), - addr: addr.clone(), + addr: *addr, ttl: 3600, }); } diff --git a/src/watch.rs b/src/watch.rs index f50352a..124bd98 100644 --- a/src/watch.rs +++ b/src/watch.rs @@ -1,12 +1,11 @@ use futures::ready; -use std::path::{Path, PathBuf}; -use std::pin::Pin; -use std::task::{Context, Poll}; -use std::time::{Duration, SystemTime}; -use tokio::fs::File; -use tokio::io::Result; -use tokio::prelude::*; -use tokio::timer::Interval; +use std::{ + path::{Path, PathBuf}, + pin::Pin, + task::{Context, Poll}, + time::{Duration, SystemTime}, +}; +use tokio::{fs::File, io::Result, prelude::*, timer::Interval}; pub struct Watch { path: PathBuf,