reference clippy optimization

This commit is contained in:
wyhaya
2019-11-15 16:49:14 +08:00
parent b606da2012
commit b1c0cf82c2
5 changed files with 55 additions and 49 deletions

View File

@@ -1,6 +1,6 @@
FROM rustlang/rust:nightly as builder FROM rust as builder
WORKDIR /root WORKDIR /root
COPY . /root COPY . /root
RUN cargo build --release RUN cargo build --release

View File

@@ -1,11 +1,15 @@
use futures::future::{BoxFuture, FutureExt}; use futures::future::{BoxFuture, FutureExt};
use regex::Regex; use regex::Regex;
use std::net::{IpAddr, SocketAddr}; use std::{
use std::path::{Path, PathBuf}; net::{IpAddr, SocketAddr},
use std::result; path::{Path, PathBuf},
use std::slice::Iter; result,
use tokio::fs::{create_dir_all, File, OpenOptions}; slice::Iter,
use tokio::io::{AsyncReadExt, AsyncWriteExt, Result}; };
use tokio::{
fs::{create_dir_all, File, OpenOptions},
io::{AsyncReadExt, AsyncWriteExt, Result},
};
lazy_static! { lazy_static! {
static ref REG_IGNORE: Regex = Regex::new(r#"^\s*(#.*)?$"#).unwrap(); static ref REG_IGNORE: Regex = Regex::new(r#"^\s*(#.*)?$"#).unwrap();
@@ -65,7 +69,7 @@ fn cap_ip_addr(text: &str) -> Option<result::Result<(Regex, IpAddr), InvalidType
Err(_) => return Some(Err(InvalidType::Regex)), Err(_) => return Some(Err(InvalidType::Regex)),
}; };
return Some(Ok((reg, ip))); Some(Ok((reg, ip)))
} }
#[derive(Debug)] #[derive(Debug)]
@@ -192,7 +196,7 @@ impl Config {
} }
pub async fn add(&mut self, domain: &str, ip: &str) -> Result<usize> { pub async fn add(&mut self, domain: &str, ip: &str) -> Result<usize> {
if self.read_to_string().await?.ends_with("\n") { if self.read_to_string().await?.ends_with('\n') {
self.file self.file
.write(format!("{} {}", domain, ip).as_bytes()) .write(format!("{} {}", domain, ip).as_bytes())
.await .await

View File

@@ -1,6 +1,7 @@
// From : EmilHernvall/dnsguide // From : EmilHernvall/dnsguide
// GitHub : https://github.com/EmilHernvall/dnsguide // GitHub : https://github.com/EmilHernvall/dnsguide
#![allow(clippy::all)]
#![allow(dead_code)] #![allow(dead_code)]
use std::io::{Error, ErrorKind, Result}; use std::io::{Error, ErrorKind, Result};

View File

@@ -10,21 +10,25 @@ use config::{Config, Hosts, Invalid, ParseConfig};
use dirs; use dirs;
use lib::*; use lib::*;
use regex::Regex; use regex::Regex;
use std::env::current_exe; use std::{
use std::net::{IpAddr, SocketAddr}; env,
use std::path::PathBuf; net::{IpAddr, SocketAddr},
use std::process::Command; path::PathBuf,
use std::time::Duration; process::Command,
use tokio::io::{Error, ErrorKind, Result}; time::Duration,
use tokio::net::UdpSocket; };
use tokio::prelude::*; use tokio::{
use tokio::timer::Timeout; io::{Error, ErrorKind, Result},
net::UdpSocket,
prelude::*,
timer::Timeout,
};
use watch::Watch; 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_BIND: &str = "0.0.0.0:53";
const DEFAULT_PROXY: [&'static str; 2] = ["8.8.8.8:53", "1.1.1.1:53"]; const DEFAULT_PROXY: [&str; 2] = ["8.8.8.8:53", "1.1.1.1:53"];
const DEFAULT_TIMEOUT: u64 = 2000; const DEFAULT_TIMEOUT: u64 = 2000;
static mut PROXY: Vec<SocketAddr> = Vec::new(); static mut PROXY: Vec<SocketAddr> = Vec::new();
@@ -91,8 +95,8 @@ async fn main() {
if values.is_empty() { if values.is_empty() {
exit!("'-w' value: [ms]"); exit!("'-w' value: [ms]");
} }
match &values[0].parse::<u64>() { match values[0].parse::<u64>() {
Ok(t) => *t, Ok(t) => t,
Err(_) => exit!("Cannot resolve '{}' to number", &values[0]), Err(_) => exit!("Cannot resolve '{}' to number", &values[0]),
} }
} }
@@ -102,7 +106,7 @@ async fn main() {
if let Some(cmd) = app.command() { if let Some(cmd) = app.command() {
match cmd.as_str() { match cmd.as_str() {
"add" => { "add" => {
let values = app.value("add").unwrap_or(vec![]); let values = app.value("add").unwrap_or_default();
if values.len() != 2 { if values.len() != 2 {
exit!("'add' value: [DOMAIN] [IP]"); exit!("'add' value: [DOMAIN] [IP]");
} }
@@ -114,7 +118,7 @@ async fn main() {
err err
); );
} }
if let Err(_) = values[1].parse::<IpAddr>() { if values[1].parse::<IpAddr>().is_err() {
exit!("Cannot resolve '{}' to ip address", values[1]); exit!("Cannot resolve '{}' to ip address", values[1]);
} }
@@ -122,18 +126,19 @@ async fn main() {
Ok(c) => c, Ok(c) => c,
Err(err) => exit!("Failed to read config file {:?}\n{:?}", &config_path, err), 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); exit!("Add record failed\n{:?}", err);
} }
} }
"ls" => { "ls" => {
let mut config = config_parse(&config_path).await; let mut config = config_parse(&config_path).await;
let mut n = 0;
for (reg, _) in config.hosts.iter() { let n = config
if reg.as_str().len() > n { .hosts
n = reg.as_str().len(); .iter()
} .map(|(r, _)| r.as_str().len())
} .fold(0, |a, b| a.max(b));
for (domain, ip) in config.hosts.iter() { for (domain, ip) in config.hosts.iter() {
println!("{:domain$} {}", domain.as_str(), ip, domain = n); println!("{:domain$} {}", domain.as_str(), ip, domain = n);
} }
@@ -152,7 +157,7 @@ async fn main() {
} }
} }
"path" => { "path" => {
let binary = match current_exe() { let binary = match env::current_exe() {
Ok(p) => p.display().to_string(), Ok(p) => p.display().to_string(),
Err(err) => exit!("Failed to get directory\n{:?}", err), Err(err) => exit!("Failed to get directory\n{:?}", err),
}; };
@@ -185,7 +190,7 @@ async fn main() {
// Run server // Run server
for addr in parse.bind { for addr in parse.bind {
tokio::spawn(run_server(addr.clone())); tokio::spawn(run_server(addr));
} }
// watch config // watch config
watch_config(config_path, watch_interval).await; watch_config(config_path, watch_interval).await;
@@ -201,10 +206,7 @@ fn update_config(mut proxy: Vec<SocketAddr>, hosts: Hosts, timeout: Option<u64>)
unsafe { unsafe {
PROXY = proxy; PROXY = proxy;
HOSTS = Some(hosts); HOSTS = Some(hosts);
TIMEOUT = match timeout { TIMEOUT = timeout.unwrap_or(DEFAULT_TIMEOUT);
Some(t) => t,
None => DEFAULT_TIMEOUT,
};
}; };
} }
@@ -223,7 +225,7 @@ async fn config_parse(file: &PathBuf) -> ParseConfig {
parse parse
} }
fn output_invalid(errors: &Vec<Invalid>) { fn output_invalid(errors: &[Invalid]) {
for invalid in errors { for invalid in errors {
error!( error!(
"[line:{}] {} `{}`", "[line:{}] {} `{}`",
@@ -319,7 +321,7 @@ fn get_answer(domain: &str, query: QueryType) -> Option<DnsRecord> {
if let IpAddr::V4(addr) = ip { if let IpAddr::V4(addr) = ip {
return Some(DnsRecord::A { return Some(DnsRecord::A {
domain: domain.to_string(), domain: domain.to_string(),
addr: addr.clone(), addr: *addr,
ttl: 3600, ttl: 3600,
}); });
} }
@@ -328,7 +330,7 @@ fn get_answer(domain: &str, query: QueryType) -> Option<DnsRecord> {
if let IpAddr::V6(addr) = ip { if let IpAddr::V6(addr) = ip {
return Some(DnsRecord::AAAA { return Some(DnsRecord::AAAA {
domain: domain.to_string(), domain: domain.to_string(),
addr: addr.clone(), addr: *addr,
ttl: 3600, ttl: 3600,
}); });
} }

View File

@@ -1,12 +1,11 @@
use futures::ready; use futures::ready;
use std::path::{Path, PathBuf}; use std::{
use std::pin::Pin; path::{Path, PathBuf},
use std::task::{Context, Poll}; pin::Pin,
use std::time::{Duration, SystemTime}; task::{Context, Poll},
use tokio::fs::File; time::{Duration, SystemTime},
use tokio::io::Result; };
use tokio::prelude::*; use tokio::{fs::File, io::Result, prelude::*, timer::Interval};
use tokio::timer::Interval;
pub struct Watch { pub struct Watch {
path: PathBuf, path: PathBuf,