Skip to content

Commit

Permalink
fix clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
bdbai committed Jan 16, 2024
1 parent 4935347 commit 20d2156
Show file tree
Hide file tree
Showing 60 changed files with 213 additions and 190 deletions.
2 changes: 1 addition & 1 deletion ytflow-bin-shared/src/edit/views/new_proxy_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::edit;
use ytflow::data::proxy_group::{ProxyGroup, PROXY_GROUP_TYPE_MANUAL};

thread_local! {
static SHOULD_RETURN: Cell<bool> = Cell::new(false);
static SHOULD_RETURN: Cell<bool> = const { Cell::new(false) };
}

fn state_index_to_type(index: usize) -> Option<&'static str> {
Expand Down
2 changes: 1 addition & 1 deletion ytflow-bin-shared/src/edit/views/proxy_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ fn edit_proxy(ctx: &mut edit::AppContext, bytes: &[u8]) -> Result<Option<Vec<u8>
let val = EditProxy {
tcp_entry: proxy.tcp_entry,
udp_entry: proxy.udp_entry,
plugins: plugins,
plugins,
};

// Serialize cborium Value into bytes using cbor4ii and deserialize into cbor4ii Value
Expand Down
4 changes: 2 additions & 2 deletions ytflow-bin-shared/src/edit/views/proxy_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use crate::edit;
use ytflow::data::{Proxy, ProxyGroupId};

thread_local! {
static SHOULD_RETURN: Cell<bool> = Cell::new(false);
static LAST_NEW_PROXY_NAME: Cell<String> = Cell::new(String::new());
static SHOULD_RETURN: Cell<bool> = const { Cell::new(false) };
static LAST_NEW_PROXY_NAME: Cell<String> = const { Cell::new(String::new()) };
}

pub fn run_proxy_type_view(
Expand Down
4 changes: 2 additions & 2 deletions ytflow-uwp-plugin/src/storage_resource_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ unsafe impl Send for StorageResourceLoader {}
unsafe impl Sync for StorageResourceLoader {}

fn hresult_to_resource(r: windows::core::Error) -> ResourceError {
ResourceError::IoError(io::Error::from_raw_os_error(r.code().0 as i32))
ResourceError::IoError(io::Error::from_raw_os_error(r.code().0))
}

impl FileResourceLoader for StorageResourceLoader {
Expand All @@ -36,7 +36,7 @@ impl FileResourceLoader for StorageResourceLoader {
let handle_access: IStorageItemHandleAccess = storage_file.cast().unwrap();
unsafe {
let handle = handle_access
.Create(HAO_READ.into(), HSO_SHARE_READ.into(), HO_NONE.into(), None)
.Create(HAO_READ, HSO_SHARE_READ, HO_NONE, None)
.map_err(hresult_to_resource)?;
let file = fs::File::from_raw_handle(handle.0 as _);
Ok(file)
Expand Down
19 changes: 9 additions & 10 deletions ytflow-uwp-plugin/src/vpn_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ async fn run_rpc(control_hub: ytflow::control::ControlHub) -> std::io::Result<()
let s = TcpSocket::new_v4()?;
s.set_reuseaddr(true)?;
s.bind(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0))?;
let port = HSTRING::try_from(s.local_addr()?.port().to_string()).unwrap();
let port = HSTRING::from(s.local_addr()?.port().to_string());
let _ = APP_SETTINGS.get().unwrap().Values()?.Insert(
h!("YTFLOW_CORE_RPC_PORT"),
&IInspectable::try_from(port).unwrap(),
Expand Down Expand Up @@ -166,7 +166,7 @@ impl Drop for Runtime {
fn drop(&mut self) {
let _enter_guard = self.rt.enter();
unsafe {
let _ = self.rpc_task.abort();
self.rpc_task.abort();
let _rx_buf_tx = ManuallyDrop::take(&mut self.rx_buf_tx);
let _plugin_set = ManuallyDrop::take(&mut self.plugin_set);
}
Expand Down Expand Up @@ -252,7 +252,7 @@ impl VpnPlugIn {
.as_wide(),
)
.into();
let db = match ytflow::data::Database::open(&db_path) {
let db = match ytflow::data::Database::open(db_path) {
Ok(db) => db,
Err(e) => return Err(format!("Cannot open database: {}", e).into()),
};
Expand All @@ -268,7 +268,7 @@ impl VpnPlugIn {
std::result::Result<(Vec<ytflow::config::Plugin>, Vec<ytflow::config::Plugin>), String>,
> {
use ytflow::data::{Plugin, Profile};
let profile_id = match Profile::query_by_id(profile_id, &conn)? {
let profile_id = match Profile::query_by_id(profile_id, conn)? {
Some(p) => p.id,
None => return Ok(Err(format!("Profile {} not found", profile_id))),
};
Expand Down Expand Up @@ -361,7 +361,7 @@ impl VpnPlugIn {
.collect::<std::result::Result<Vec<_>, _>>();
res.map(|_| loader)
})?;
factory.load_all(&rt_handle, Box::new(loader), Some(&db))
factory.load_all(rt_handle, Box::new(loader), Some(&db))
};
let mut error_str = if errors.is_empty() {
String::from("There must be exactly one vpn-tun entry plugin in a profile")
Expand All @@ -374,10 +374,10 @@ impl VpnPlugIn {
loop {
if let (Some(vpn_items), []) = (vpn_items_cell.borrow_mut().take(), &*errors) {
let (tx_buf_rx, rx_buf_tx, vpn_tun_factory) = vpn_items;
match connect_with_factory(&transport, &vpn_tun_factory, &channel) {
match connect_with_factory(&transport, &vpn_tun_factory, channel) {
Ok(()) => {
*inner = VpnPlugInInner::Running {
tx_buf_rx: tx_buf_rx,
tx_buf_rx,
runtime: Runtime {
rx_buf_tx: ManuallyDrop::new(rx_buf_tx),
plugin_set: ManuallyDrop::new(set),
Expand Down Expand Up @@ -408,8 +408,7 @@ impl VpnPlugIn {
impl IVpnPlugIn_Impl for VpnPlugIn {
fn Connect(&self, channel: Option<&VpnChannel>) -> Result<()> {
let channel = channel.unwrap();
if let Err(crate::error::ConnectError(e)) = self.connect_core(channel) {
let err_msg = format!("{}", e);
if let Err(crate::error::ConnectError(err_msg)) = self.connect_core(channel) {
APP_SETTINGS.get().unwrap().Values()?.Insert(
h!("YTFLOW_CORE_ERROR_LOAD"),
&IInspectable::try_from(HSTRING::from(&err_msg))?,
Expand Down Expand Up @@ -458,7 +457,7 @@ impl IVpnPlugIn_Impl for VpnPlugIn {
std::ptr::copy_nonoverlapping(slice.as_mut_ptr(), buf.as_mut_ptr(), len);
buf.set_len(len);
}
if let Err(_) = rx_buf_tx.send(buf) {
if rx_buf_tx.send(buf).is_err() {
return Ok(());
}
packets.Append(&vpn_buffer)?;
Expand Down
8 changes: 4 additions & 4 deletions ytflow/src/config/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ pub(super) trait Factory {
fn load(&mut self, plugin_name: String, set: &mut PartialPluginSet<'_>) -> LoadResult<()>;
}

impl<'de, 'f> Factory for Box<dyn Factory + 'f> {
impl<'f> Factory for Box<dyn Factory + 'f> {
#[cfg(feature = "plugins")]
fn load(&mut self, plugin_name: String, set: &mut PartialPluginSet) -> LoadResult<()> {
(&mut **self).load(plugin_name, set)
(**self).load(plugin_name, set)
}
}

Expand Down Expand Up @@ -184,7 +184,7 @@ impl<'de> AccessPointResolver<'de> {
descriptor: ap.to_owned(),
});
}
self.demanding_aps.entry(ap).or_insert(vec![]).push(demand);
self.demanding_aps.entry(ap).or_default().push(demand);
Ok(())
}
fn process_plugin(
Expand All @@ -207,7 +207,7 @@ impl<'de> AccessPointResolver<'de> {
.errors
.extend(requires.into_iter().filter_map(|d| {
self.insert_demand(
&*d.descriptor,
d.descriptor,
Demand {
initiator: &plugin.name,
ap_type: d.r#type,
Expand Down
2 changes: 1 addition & 1 deletion ytflow/src/config/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod null;
mod redirect;
mod reject;
mod resolve_dest;
pub(self) mod rule_dispatcher;
mod rule_dispatcher;
mod shadowsocks;
mod simple_dispatcher;
mod socket;
Expand Down
1 change: 0 additions & 1 deletion ytflow/src/config/plugin/dyn_outbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ impl<'de> Factory for DynOutboundFactory<'de> {

let db = set
.db
.as_deref()
.ok_or_else(|| LoadError::DatabaseRequired {
plugin: plugin_name.clone(),
})?
Expand Down
2 changes: 1 addition & 1 deletion ytflow/src/config/plugin/host_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl<'de> Factory for HostResolverFactory<'de> {
let udp = self
.udp
.iter()
.map(|c| set.get_or_create_datagram_outbound(plugin_name.clone(), *c))
.map(|c| set.get_or_create_datagram_outbound(plugin_name.clone(), c))
.filter_map(|d| match d {
Ok(d) => Some(d),
Err(e) => {
Expand Down
3 changes: 1 addition & 2 deletions ytflow/src/config/plugin/list_dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn load_rule_set(
};
match metadata.r#type.as_str() {
RESOURCE_TYPE_SURGE_DOMAINSET => {
let text = validate_text(&bytes, &plugin_name, set);
let text = validate_text(&bytes, plugin_name, set);
match rd::RuleSet::build_surge_domainset(text.lines(), action) {
Some(ruleset) => return ruleset,
// TODO: log ruleset build error
Expand Down Expand Up @@ -197,7 +197,6 @@ impl<'de> Factory for ListDispatcherFactory<'de> {
let resolver = self
.config
.resolver
.clone()
.map(|resolver| load_resolver(resolver, set, &plugin_name));
let me = weak.clone();
builder.set_resolver(resolver);
Expand Down
23 changes: 10 additions & 13 deletions ytflow/src/config/plugin/rule_dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,11 @@ impl<'de> RuleDispatcherFactory<'de> {
}
}

if let Some(geoip_source) = &config.geoip {
if let ResourceSource::Literal { .. } = geoip_source {
return Err(ConfigError::InvalidParam {
plugin: name.to_string(),
field: "geoip",
});
}
if let Some(ResourceSource::Literal { .. }) = &config.geoip {
return Err(ConfigError::InvalidParam {
plugin: name.to_string(),
field: "geoip",
});
}

if config.actions.len() > rd::ACTION_LIMIT {
Expand Down Expand Up @@ -292,8 +290,8 @@ fn load_rule_set(
set: &mut PartialPluginSet,
) -> rd::RuleSet {
let rule_action_map = rules
.into_iter()
.map(|(rule, action)| (*rule, action_map[*action].clone()))
.iter()
.map(|(rule, action)| (*rule, action_map[*action]))
.collect();
let resource_key;
let resource_type;
Expand Down Expand Up @@ -325,8 +323,8 @@ fn load_rule_set(
RESOURCE_TYPE_GEOIP_COUNTRY => {
match rd::RuleSet::build_dst_geoip_rule(
rules
.into_iter()
.map(|(rule, action)| (rule.to_string(), action_map[action].clone())),
.iter()
.map(|(rule, action)| (rule.to_string(), action_map[action])),
bytes,
) {
Some(ruleset) => return ruleset,
Expand All @@ -341,7 +339,7 @@ fn load_rule_set(
}
}
RESOURCE_TYPE_QUANX_FILTER => {
let text = validate_text(&bytes, &plugin_name, set);
let text = validate_text(&bytes, plugin_name, set);
match rd::RuleSet::load_quanx_filter(
text.lines(),
&rule_action_map,
Expand Down Expand Up @@ -442,7 +440,6 @@ impl<'de> Factory for RuleDispatcherFactory<'de> {
let resolver = self
.config
.resolver
.clone()
.map(|resolver| load_resolver(resolver, set, &plugin_name));
let fallback = load_action(&self.config.fallback, set, &plugin_name);
let me = weak.clone();
Expand Down
4 changes: 2 additions & 2 deletions ytflow/src/config/plugin/socket_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ impl<'de> SocketListenerFactory<'de> {
let config: Self = parse_param(name, param)?;
Ok(ParsedPlugin {
requires: (!config.tcp_listen.is_empty())
.then(|| Descriptor {
.then_some(Descriptor {
descriptor: config.tcp_next,
r#type: AccessPointType::STREAM_HANDLER,
})
.into_iter()
.chain((!config.udp_listen.is_empty()).then(|| Descriptor {
.chain((!config.udp_listen.is_empty()).then_some(Descriptor {
descriptor: config.udp_next,
r#type: AccessPointType::DATAGRAM_SESSION_HANDLER,
}))
Expand Down
1 change: 0 additions & 1 deletion ytflow/src/config/plugin/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ impl<'de> Factory for SwitchFactory<'de> {

let db = set
.db
.as_deref()
.ok_or_else(|| LoadError::DatabaseRequired {
plugin: plugin_name.clone(),
})?
Expand Down
2 changes: 1 addition & 1 deletion ytflow/src/config/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ fn lookup<T: ?Sized>(
strong_map
.get(descriptor)
.map(Arc::downgrade)
.or_else(|| weak_map.get(descriptor).map(Weak::clone))
.or_else(|| weak_map.get(descriptor).cloned())
}

macro_rules! impl_get_or_create {
Expand Down
2 changes: 1 addition & 1 deletion ytflow/src/control/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl PluginController {
.map(|info| PluginInfo {
id: self.id,
name: Cow::Borrowed(&self.name),
plugin: Cow::Borrowed(&self.plugin),
plugin: Cow::Borrowed(self.plugin),
info: ByteBuf::from(info),
hashcode,
})
Expand Down
12 changes: 6 additions & 6 deletions ytflow/src/control/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,16 @@ impl<'h> ControlHubService<'h> {
let req: ControlHubRequest = match from_slice(req) {
Ok(req) => req,
Err(e) => {
return Ok(to_writer(
return to_writer(
res,
&ControlHubResponse::<(), _>::Err {
error: e.to_string(),
},
)?);
);
}
};

Ok(match req {
match req {
ControlHubRequest::CollectAllPluginInfo { hashcodes } => {
let data = self.collect_all_plugin_info(hashcodes);
to_writer(res, &ControlHubResponse::<_, ()>::Ok { data })
Expand All @@ -84,7 +84,7 @@ impl<'h> ControlHubService<'h> {
.into();
to_writer(res, &response)
}
}?)
}
}

fn collect_all_plugin_info(&mut self, hashcodes: BTreeMap<u32, u32>) -> Vec<super::PluginInfo> {
Expand All @@ -106,7 +106,7 @@ impl<'h> ControlHubService<'h> {
.iter()
.find(|p| p.id == id)
.ok_or(plugin::PluginRequestError::NoSuchPlugin)
.and_then(|p| p.responder.on_request(&func, &params))
.and_then(|p| p.responder.on_request(func, params))
}
}

Expand Down Expand Up @@ -143,7 +143,7 @@ where
D: Sink<Vec<u8>, Error = E> + TryStream<Ok = Vec<u8>, Error = E> + Unpin,
{
while let Some(req) = io.try_next().await? {
if req.len() == 0 {
if req.is_empty() {
continue;
}
let mut res = Vec::with_capacity(128);
Expand Down
4 changes: 2 additions & 2 deletions ytflow/src/data/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub struct Database {
fn connect(path: impl AsRef<Path>) -> DataResult<Connection> {
setup_temp();
let db = Connection::open(&path)?;
db.pragma_update(None, "foreign_keys", &"ON")?;
db.pragma_update(None, "foreign_keys", "ON")?;
Ok(db)
}

Expand All @@ -72,7 +72,7 @@ impl Database {
pub fn connect_temp() -> DataResult<Connection> {
setup_temp();
let mut db = Connection::open_in_memory()?;
db.pragma_update(None, "foreign_keys", &"ON")?;
db.pragma_update(None, "foreign_keys", "ON")?;
embedded_migrations::migrations::runner().run(&mut db)?;
Ok(db)
}
Expand Down
16 changes: 14 additions & 2 deletions ytflow/src/data/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,26 @@ use thiserror::Error;
#[derive(Debug, Error)]
pub enum DataError {
#[error("cannot migrate")]
Migration(#[from] refinery::Error),
Migration(Box<refinery::Error>),
#[error("error performing sqlite operations")]
Database(#[from] rusqlite::Error),
Database(Box<rusqlite::Error>),
#[error("field \"{field:?}\" for \"{domain:?}\" is not valid")]
InvalidData {
domain: &'static str,
field: &'static str,
},
}

impl From<refinery::Error> for DataError {
fn from(e: refinery::Error) -> Self {
DataError::Migration(Box::new(e))
}
}

impl From<rusqlite::Error> for DataError {
fn from(e: rusqlite::Error) -> Self {
DataError::Database(Box::new(e))
}
}

pub type DataResult<T> = Result<T, DataError>;
2 changes: 1 addition & 1 deletion ytflow/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct Id<T>(pub u32, PhantomData<T>);

impl<T> Clone for Id<T> {
fn clone(&self) -> Id<T> {
Self(self.0, PhantomData)
*self
}
}
impl<T> Copy for Id<T> {}
Expand Down
Loading

0 comments on commit 20d2156

Please sign in to comment.