From 6438a64fc734315d6fa2381991081a687a2378de Mon Sep 17 00:00:00 2001 From: Christien Rioux Date: Sun, 17 Sep 2023 19:37:02 -0400 Subject: [PATCH] clippy work --- veilid-cli/src/main.rs | 1 + veilid-cli/src/ui.rs | 8 +- veilid-core/build.rs | 36 ++++-- veilid-core/src/crypto/envelope.rs | 2 +- veilid-core/src/crypto/tests/mod.rs | 6 +- veilid-core/src/crypto/tests/test_types.rs | 12 +- .../src/crypto/types/byte_array_types.rs | 28 +---- .../src/crypto/types/crypto_typed_group.rs | 25 ++-- veilid-core/src/crypto/types/keypair.rs | 2 +- veilid-core/src/crypto/vld0/mod.rs | 10 +- veilid-core/src/intf/mod.rs | 2 +- .../intf/native/network_interfaces/apple.rs | 6 +- .../src/intf/native/network_interfaces/mod.rs | 2 +- veilid-core/src/lib.rs | 1 + .../src/network_manager/address_filter.rs | 12 +- .../src/network_manager/connection_handle.rs | 2 +- .../src/network_manager/connection_manager.rs | 7 +- .../src/network_manager/connection_table.rs | 20 +-- veilid-core/src/network_manager/mod.rs | 8 +- .../native/discovery_context.rs | 29 ++--- .../src/network_manager/native/igd_manager.rs | 24 ++-- veilid-core/src/network_manager/native/mod.rs | 14 +-- .../src/network_manager/native/network_udp.rs | 2 +- .../network_manager/native/protocol/mod.rs | 2 +- .../network_manager/native/protocol/tcp.rs | 7 +- .../network_manager/native/protocol/udp.rs | 8 +- .../src/network_manager/native/protocol/ws.rs | 9 +- .../network_manager/native/start_protocols.rs | 6 +- .../src/network_manager/network_connection.rs | 19 +-- veilid-core/src/network_manager/send_data.rs | 2 +- .../tasks/public_address_check.rs | 10 +- .../src/network_manager/types/address.rs | 8 +- .../src/network_manager/types/address_type.rs | 2 +- .../network_manager/types/dial_info/mod.rs | 48 +++---- .../types/low_level_protocol_type.rs | 2 +- .../src/network_manager/types/peer_address.rs | 11 +- .../network_manager/types/protocol_type.rs | 2 +- .../network_manager/types/socket_address.rs | 16 +-- veilid-core/src/routing_table/bucket_entry.rs | 6 +- veilid-core/src/routing_table/mod.rs | 8 +- .../routing_table/routing_domain_editor.rs | 8 +- .../src/routing_table/routing_domains.rs | 24 ++-- .../src/routing_table/routing_table_inner.rs | 7 +- .../src/routing_table/tasks/bootstrap.rs | 2 +- .../tasks/private_route_management.rs | 11 +- .../routing_table/types/dial_info_detail.rs | 2 + .../src/routing_table/types/direction.rs | 2 +- .../src/routing_table/types/peer_info.rs | 2 +- .../src/routing_table/types/routing_domain.rs | 2 +- .../types/signed_direct_node_info.rs | 2 +- .../routing_table/types/signed_node_info.rs | 4 +- .../types/signed_relayed_node_info.rs | 2 +- veilid-core/src/storage_manager/mod.rs | 16 +-- veilid-core/src/veilid_api/debug.rs | 14 +-- veilid-flutter/rust/src/lib.rs | 3 + veilid-server/src/main.rs | 1 + veilid-tools/src/assembly_buffer.rs | 6 + veilid-tools/src/async_tag_lock.rs | 14 +++ veilid-tools/src/lib.rs | 3 + veilid-tools/src/timestamp.rs | 47 +++---- veilid-tools/src/tools.rs | 10 +- veilid-wasm/src/lib.rs | 117 +++++++++++++++--- 62 files changed, 414 insertions(+), 310 deletions(-) diff --git a/veilid-cli/src/main.rs b/veilid-cli/src/main.rs index 9345daaa..4f46cfdd 100644 --- a/veilid-cli/src/main.rs +++ b/veilid-cli/src/main.rs @@ -1,4 +1,5 @@ #![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] #![deny(unused_must_use)] #![recursion_limit = "256"] diff --git a/veilid-cli/src/ui.rs b/veilid-cli/src/ui.rs index c1e4642d..0c401e38 100644 --- a/veilid-cli/src/ui.rs +++ b/veilid-cli/src/ui.rs @@ -482,7 +482,9 @@ impl UI { ) .as_bytes(), ) - .is_ok() && std::io::stdout().flush().is_ok() { + .is_ok() + && std::io::stdout().flush().is_ok() + { let color = *Self::inner_mut(s).log_colors.get(&Level::Info).unwrap(); cursive_flexi_logger_view::parse_lines_to_log( color.into(), @@ -938,10 +940,12 @@ impl UI { // } } +type CallbackSink = Box; + #[derive(Clone)] pub struct UISender { inner: Arc>, - cb_sink: Sender>, + cb_sink: Sender, } impl UISender { diff --git a/veilid-core/build.rs b/veilid-core/build.rs index c7ebbf9e..3eb93400 100644 --- a/veilid-core/build.rs +++ b/veilid-core/build.rs @@ -18,8 +18,7 @@ fn get_desired_capnp_version_string() -> String { let capnp_path = search_file(env!("CARGO_MANIFEST_DIR"), ".capnp_version") .expect("should find .capnp_version file"); std::fs::read_to_string(&capnp_path) - .unwrap_or_else(|_| panic!("can't read .capnp_version file here: {:?}", - capnp_path)) + .unwrap_or_else(|_| panic!("can't read .capnp_version file here: {:?}", capnp_path)) .trim() .to_owned() } @@ -45,8 +44,7 @@ fn get_desired_protoc_version_string() -> String { let protoc_path = search_file(env!("CARGO_MANIFEST_DIR"), ".protoc_version") .expect("should find .protoc_version file"); std::fs::read_to_string(&protoc_path) - .unwrap_or_else(|_| panic!("can't read .protoc_version file here: {:?}", - protoc_path)) + .unwrap_or_else(|_| panic!("can't read .protoc_version file here: {:?}", protoc_path)) .trim() .to_owned() } @@ -75,11 +73,18 @@ fn main() { let protoc_version_string = get_protoc_version_string(); // Check capnp version - let desired_capnp_major_version = - usize::from_str_radix(desired_capnp_version_string.split_once('.').unwrap().0, 10) - .expect("should be valid int"); + let desired_capnp_major_version = desired_capnp_version_string + .split_once('.') + .unwrap() + .0 + .parse::() + .expect("should be valid int"); - if usize::from_str_radix(capnp_version_string.split_once('.').unwrap().0, 10) + if capnp_version_string + .split_once('.') + .unwrap() + .0 + .parse::() .expect("should be valid int") != desired_capnp_major_version { @@ -95,10 +100,17 @@ fn main() { } // Check protoc version - let desired_protoc_major_version = - usize::from_str_radix(desired_protoc_version_string.split_once('.').unwrap().0, 10) - .expect("should be valid int"); - if usize::from_str_radix(protoc_version_string.split_once('.').unwrap().0, 10) + let desired_protoc_major_version = desired_protoc_version_string + .split_once('.') + .unwrap() + .0 + .parse::() + .expect("should be valid int"); + if protoc_version_string + .split_once('.') + .unwrap() + .0 + .parse::() .expect("should be valid int") < desired_protoc_major_version { diff --git a/veilid-core/src/crypto/envelope.rs b/veilid-core/src/crypto/envelope.rs index 86f1324e..dc92e317 100644 --- a/veilid-core/src/crypto/envelope.rs +++ b/veilid-core/src/crypto/envelope.rs @@ -236,7 +236,7 @@ impl Envelope { } // Compress body - let body = compress_prepend_size(&body); + let body = compress_prepend_size(body); // Ensure body isn't too long let envelope_size: usize = body.len() + MIN_ENVELOPE_SIZE; diff --git a/veilid-core/src/crypto/tests/mod.rs b/veilid-core/src/crypto/tests/mod.rs index 04a29d9f..33ec1eac 100644 --- a/veilid-core/src/crypto/tests/mod.rs +++ b/veilid-core/src/crypto/tests/mod.rs @@ -8,10 +8,10 @@ use crate::tests::common::test_veilid_config::*; async fn crypto_tests_startup() -> VeilidAPI { trace!("crypto_tests: starting"); let (update_callback, config_callback) = setup_veilid_core(); - let api = api_startup(update_callback, config_callback) + + api_startup(update_callback, config_callback) .await - .expect("startup failed"); - api + .expect("startup failed") } async fn crypto_tests_shutdown(api: VeilidAPI) { diff --git a/veilid-core/src/crypto/tests/test_types.rs b/veilid-core/src/crypto/tests/test_types.rs index 3a544186..b2f7a3bc 100644 --- a/veilid-core/src/crypto/tests/test_types.rs +++ b/veilid-core/src/crypto/tests/test_types.rs @@ -228,7 +228,7 @@ pub async fn test_encode_decode(vcrypto: CryptoSystemVersion) { pub async fn test_typed_convert(vcrypto: CryptoSystemVersion) { let tks1 = format!( "{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ", - vcrypto.kind().to_string() + vcrypto.kind() ); let tk1 = TypedKey::from_str(&tks1).expect("failed"); let tks1x = tk1.to_string(); @@ -236,22 +236,22 @@ pub async fn test_typed_convert(vcrypto: CryptoSystemVersion) { let tks2 = format!( "{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd", - vcrypto.kind().to_string() + vcrypto.kind() ); let _tk2 = TypedKey::from_str(&tks2).expect_err("succeeded when it shouldnt have"); - let tks3 = format!("XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",); + let tks3 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string(); let tk3 = TypedKey::from_str(&tks3).expect("failed"); let tks3x = tk3.to_string(); assert_eq!(tks3, tks3x); - let tks4 = format!("XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd",); + let tks4 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd".to_string(); let _tk4 = TypedKey::from_str(&tks4).expect_err("succeeded when it shouldnt have"); - let tks5 = format!("XXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",); + let tks5 = "XXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string(); let _tk5 = TypedKey::from_str(&tks5).expect_err("succeeded when it shouldnt have"); - let tks6 = format!("7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",); + let tks6 = "7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string(); let tk6 = TypedKey::from_str(&tks6).expect("failed"); let tks6x = tk6.to_string(); assert!(tks6x.ends_with(&tks6)); diff --git a/veilid-core/src/crypto/types/byte_array_types.rs b/veilid-core/src/crypto/types/byte_array_types.rs index d47a323a..4c989bab 100644 --- a/veilid-core/src/crypto/types/byte_array_types.rs +++ b/veilid-core/src/crypto/types/byte_array_types.rs @@ -77,7 +77,7 @@ where macro_rules! byte_array_type { ($name:ident, $size:expr, $encoded_size:expr) => { - #[derive(Clone, Copy, Hash)] + #[derive(Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)] #[cfg_attr(target_arch = "wasm32", derive(Tsify), tsify(into_wasm_abi))] pub struct $name { pub bytes: [u8; $size], @@ -114,32 +114,6 @@ macro_rules! byte_array_type { } } - impl PartialOrd for $name { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - - impl Ord for $name { - fn cmp(&self, other: &Self) -> core::cmp::Ordering { - for n in 0..$size { - let c = self.bytes[n].cmp(&other.bytes[n]); - if c != core::cmp::Ordering::Equal { - return c; - } - } - core::cmp::Ordering::Equal - } - } - - impl PartialEq for $name { - fn eq(&self, other: &Self) -> bool { - self.bytes == other.bytes - } - } - - impl Eq for $name {} - impl $name { pub fn new(bytes: [u8; $size]) -> Self { Self { bytes } diff --git a/veilid-core/src/crypto/types/crypto_typed_group.rs b/veilid-core/src/crypto/types/crypto_typed_group.rs index 80f717bc..fbdd855c 100644 --- a/veilid-core/src/crypto/types/crypto_typed_group.rs +++ b/veilid-core/src/crypto/types/crypto_typed_group.rs @@ -93,16 +93,13 @@ where } /// Return preferred typed key of our supported crypto kinds pub fn best(&self) -> Option> { - match self.items.first().copied() { - None => None, - Some(k) => { - if !VALID_CRYPTO_KINDS.contains(&k.kind) { - None - } else { - Some(k) - } - } - } + self.items + .first() + .copied() + .filter(|k| VALID_CRYPTO_KINDS.contains(&k.kind)) + } + pub fn is_empty(&self) -> bool { + self.items.is_empty() } pub fn len(&self) -> usize { self.items.len() @@ -204,7 +201,7 @@ where if &s[0..1] != "[" || &s[(s.len() - 1)..] != "]" { apibail_parse_error!("invalid format", s); } - for x in s[1..s.len() - 1].split(",") { + for x in s[1..s.len() - 1].split(',') { let tk = CryptoTyped::::from_str(x.trim())?; items.push(tk); } @@ -272,7 +269,7 @@ where tks } } -impl Into>> for CryptoTypedGroup +impl From> for Vec> where K: Clone + Copy @@ -286,7 +283,7 @@ where + Hash + Encodable, { - fn into(self) -> Vec> { - self.items + fn from(val: CryptoTypedGroup) -> Self { + val.items } } diff --git a/veilid-core/src/crypto/types/keypair.rs b/veilid-core/src/crypto/types/keypair.rs index 6530eefb..4fafd4ea 100644 --- a/veilid-core/src/crypto/types/keypair.rs +++ b/veilid-core/src/crypto/types/keypair.rs @@ -96,7 +96,7 @@ impl<'de> serde::Deserialize<'de> for KeyPair { D: serde::Deserializer<'de>, { let s = ::deserialize(deserializer)?; - if s == "" { + if s.is_empty() { return Ok(KeyPair::default()); } KeyPair::try_decode(s.as_str()).map_err(serde::de::Error::custom) diff --git a/veilid-core/src/crypto/vld0/mod.rs b/veilid-core/src/crypto/vld0/mod.rs index 5214f148..b2b2ce1c 100644 --- a/veilid-core/src/crypto/vld0/mod.rs +++ b/veilid-core/src/crypto/vld0/mod.rs @@ -134,8 +134,8 @@ impl CryptoSystem for CryptoSystemVLD0 { SharedSecret::new(s) } fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult { - let pk_xd = public_to_x25519_pk(&key)?; - let sk_xd = secret_to_x25519_sk(&secret)?; + let pk_xd = public_to_x25519_pk(key)?; + let sk_xd = secret_to_x25519_sk(secret)?; let dh_bytes = sk_xd.diffie_hellman(&pk_xd).to_bytes(); @@ -188,9 +188,9 @@ impl CryptoSystem for CryptoSystemVLD0 { fn distance(&self, key1: &PublicKey, key2: &PublicKey) -> CryptoKeyDistance { let mut bytes = [0u8; CRYPTO_KEY_LENGTH]; - for n in 0..CRYPTO_KEY_LENGTH { + (0..CRYPTO_KEY_LENGTH).for_each(|n| { bytes[n] = key1.bytes[n] ^ key2.bytes[n]; - } + }); CryptoKeyDistance::new(bytes) } @@ -219,7 +219,7 @@ impl CryptoSystem for CryptoSystemVLD0 { let sig = Signature::new(sig_bytes.to_bytes()); - self.verify(dht_key, &data, &sig)?; + self.verify(dht_key, data, &sig)?; Ok(sig) } diff --git a/veilid-core/src/intf/mod.rs b/veilid-core/src/intf/mod.rs index 81756b61..af238bee 100644 --- a/veilid-core/src/intf/mod.rs +++ b/veilid-core/src/intf/mod.rs @@ -9,4 +9,4 @@ mod native; #[cfg(not(target_arch = "wasm32"))] pub use native::*; -pub static KNOWN_PROTECTED_STORE_KEYS: [&'static str; 2] = ["device_encryption_key", "_test_key"]; +pub static KNOWN_PROTECTED_STORE_KEYS: [&str; 2] = ["device_encryption_key", "_test_key"]; diff --git a/veilid-core/src/intf/native/network_interfaces/apple.rs b/veilid-core/src/intf/native/network_interfaces/apple.rs index a34174fb..88422f60 100644 --- a/veilid-core/src/intf/native/network_interfaces/apple.rs +++ b/veilid-core/src/intf/native/network_interfaces/apple.rs @@ -324,7 +324,7 @@ impl PlatformSupportApple { let intf_index = unsafe { (*rt).rtm_index } as u32; // Fill in sockaddr table - for i in 0..(RTAX_MAX as usize) { + (0..(RTAX_MAX as usize)).for_each(|i| { if rtm_addrs & (1 << i) != 0 { sa_tab[i] = sa; sa = unsafe { @@ -333,7 +333,7 @@ impl PlatformSupportApple { sa }; } - } + }); // Look for gateways if rtm_addrs & (RTA_DST | RTA_GATEWAY) == (RTA_DST | RTA_GATEWAY) { @@ -373,7 +373,7 @@ impl PlatformSupportApple { } fn get_address_flags(ifname: &str, addr: sockaddr_in6) -> EyreResult { - let mut req = in6_ifreq::from_name(&ifname).unwrap(); + let mut req = in6_ifreq::from_name(ifname).unwrap(); req.set_addr(addr); let sock = unsafe { socket(AF_INET6, SOCK_DGRAM, 0) }; diff --git a/veilid-core/src/intf/native/network_interfaces/mod.rs b/veilid-core/src/intf/native/network_interfaces/mod.rs index 59f1ae49..4c53cab9 100644 --- a/veilid-core/src/intf/native/network_interfaces/mod.rs +++ b/veilid-core/src/intf/native/network_interfaces/mod.rs @@ -359,7 +359,7 @@ impl NetworkInterfaces { let old_best_addresses = inner.interface_address_cache.clone(); // redo the address cache - Self::cache_best_addresses(&mut *inner); + Self::cache_best_addresses(&mut inner); // See if our best addresses have changed if old_best_addresses != inner.interface_address_cache { diff --git a/veilid-core/src/lib.rs b/veilid-core/src/lib.rs index f2cb5df9..bea8cab5 100644 --- a/veilid-core/src/lib.rs +++ b/veilid-core/src/lib.rs @@ -22,6 +22,7 @@ //! #![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] #![deny(unused_must_use)] #![recursion_limit = "256"] diff --git a/veilid-core/src/network_manager/address_filter.rs b/veilid-core/src/network_manager/address_filter.rs index 5b17e3d0..ad869bfc 100644 --- a/veilid-core/src/network_manager/address_filter.rs +++ b/veilid-core/src/network_manager/address_filter.rs @@ -244,12 +244,12 @@ impl AddressFilter { self.unlocked_inner.max_connections_per_ip6_prefix_size, addr, ); - self.is_ip_addr_punished_inner(&*inner, ipblock) + self.is_ip_addr_punished_inner(&inner, ipblock) } pub fn get_dial_info_failed_ts(&self, dial_info: &DialInfo) -> Option { let inner = self.inner.lock(); - self.get_dial_info_failed_ts_inner(&*inner, dial_info) + self.get_dial_info_failed_ts_inner(&inner, dial_info) } pub fn set_dial_info_failed(&self, dial_info: DialInfo) { @@ -301,7 +301,7 @@ impl AddressFilter { pub fn is_node_id_punished(&self, node_id: TypedKey) -> bool { let inner = self.inner.lock(); - self.is_node_id_punished_inner(&*inner, node_id) + self.is_node_id_punished_inner(&inner, node_id) } pub fn punish_node_id(&self, node_id: TypedKey) { @@ -333,8 +333,8 @@ impl AddressFilter { ) -> EyreResult<()> { // let mut inner = self.inner.lock(); - self.purge_old_timestamps(&mut *inner, cur_ts); - self.purge_old_punishments(&mut *inner, cur_ts); + self.purge_old_timestamps(&mut inner, cur_ts); + self.purge_old_punishments(&mut inner, cur_ts); Ok(()) } @@ -411,7 +411,7 @@ impl AddressFilter { ); let ts = get_aligned_timestamp(); - self.purge_old_timestamps(&mut *inner, ts); + self.purge_old_timestamps(&mut inner, ts); match ipblock { IpAddr::V4(v4) => { diff --git a/veilid-core/src/network_manager/connection_handle.rs b/veilid-core/src/network_manager/connection_handle.rs index dbf53117..2f960f65 100644 --- a/veilid-core/src/network_manager/connection_handle.rs +++ b/veilid-core/src/network_manager/connection_handle.rs @@ -31,7 +31,7 @@ impl ConnectionHandle { } pub fn connection_descriptor(&self) -> ConnectionDescriptor { - self.descriptor.clone() + self.descriptor } #[cfg_attr(feature="verbose-tracing", instrument(level="trace", skip(self, message), fields(message.len = message.len())))] diff --git a/veilid-core/src/network_manager/connection_manager.rs b/veilid-core/src/network_manager/connection_manager.rs index 6f350a9f..d5ad429c 100644 --- a/veilid-core/src/network_manager/connection_manager.rs +++ b/veilid-core/src/network_manager/connection_manager.rs @@ -117,13 +117,12 @@ impl ConnectionManager { // Remove the inner from the lock let mut inner = { let mut inner_lock = self.arc.inner.lock(); - let inner = match inner_lock.take() { + match inner_lock.take() { Some(v) => v, None => { panic!("not started"); } - }; - inner + } }; // Stop all the connections and the async processor @@ -251,7 +250,7 @@ impl ConnectionManager { dial_info: DialInfo, ) -> EyreResult> { let peer_address = dial_info.to_peer_address(); - let remote_addr = peer_address.to_socket_addr(); + let remote_addr = peer_address.socket_addr(); let mut preferred_local_address = self .network_manager() .net() diff --git a/veilid-core/src/network_manager/connection_table.rs b/veilid-core/src/network_manager/connection_table.rs index 233c447e..c391246b 100644 --- a/veilid-core/src/network_manager/connection_table.rs +++ b/veilid-core/src/network_manager/connection_table.rs @@ -164,7 +164,7 @@ impl ConnectionTable { } // Filter by ip for connection limits - let ip_addr = descriptor.remote_address().to_ip_addr(); + let ip_addr = descriptor.remote_address().ip_addr(); match inner.address_filter.add_connection(ip_addr) { Ok(()) => {} Err(e) => { @@ -196,7 +196,7 @@ impl ConnectionTable { } log_net!(debug "== LRU Connection Killed: {} -> {}", lruk, lru_conn.debug_print(get_aligned_timestamp())); - out_conn = Some(Self::remove_connection_records(&mut *inner, lruk)); + out_conn = Some(Self::remove_connection_records(&mut inner, lruk)); break; } } @@ -237,11 +237,11 @@ impl ConnectionTable { best_port: Option, remote: PeerAddress, ) -> Option { - let mut inner = self.inner.lock(); + let inner = &mut *self.inner.lock(); let all_ids_by_remote = inner.ids_by_remote.get(&remote)?; let protocol_index = Self::protocol_to_index(remote.protocol_type()); - if all_ids_by_remote.len() == 0 { + if all_ids_by_remote.is_empty() { // no connections return None; } @@ -253,11 +253,11 @@ impl ConnectionTable { } // multiple connections, find the one that matches the best port, or the most recent if let Some(best_port) = best_port { - for id in all_ids_by_remote.iter().copied() { - let nc = inner.conn_by_id[protocol_index].peek(&id).unwrap(); + for id in all_ids_by_remote { + let nc = inner.conn_by_id[protocol_index].peek(id).unwrap(); if let Some(local_addr) = nc.connection_descriptor().local() { if local_addr.port() == best_port { - let nc = inner.conn_by_id[protocol_index].get(&id).unwrap(); + let nc = inner.conn_by_id[protocol_index].get(id).unwrap(); return Some(nc.get_handle()); } } @@ -331,7 +331,7 @@ impl ConnectionTable { } } // address_filter - let ip_addr = remote.to_socket_addr().ip(); + let ip_addr = remote.socket_addr().ip(); inner .address_filter .remove_connection(ip_addr) @@ -347,7 +347,7 @@ impl ConnectionTable { if !inner.conn_by_id[protocol_index].contains_key(&id) { return None; } - let conn = Self::remove_connection_records(&mut *inner, id); + let conn = Self::remove_connection_records(&mut inner, id); Some(conn) } @@ -358,7 +358,7 @@ impl ConnectionTable { for t in 0..inner.conn_by_id.len() { out += &format!( " {} Connections: ({}/{})\n", - Self::index_to_protocol(t).to_string(), + Self::index_to_protocol(t), inner.conn_by_id[t].len(), inner.max_connections[t] ); diff --git a/veilid-core/src/network_manager/mod.rs b/veilid-core/src/network_manager/mod.rs index d1b7bc74..d5708f9f 100644 --- a/veilid-core/src/network_manager/mod.rs +++ b/veilid-core/src/network_manager/mod.rs @@ -61,7 +61,7 @@ pub const PUBLIC_ADDRESS_CHECK_TASK_INTERVAL_SECS: u32 = 60; pub const PUBLIC_ADDRESS_INCONSISTENCY_TIMEOUT_US: TimestampDuration = TimestampDuration::new(300_000_000u64); // 5 minutes pub const PUBLIC_ADDRESS_INCONSISTENCY_PUNISHMENT_TIMEOUT_US: TimestampDuration = - TimestampDuration::new(3600_000_000u64); // 60 minutes + TimestampDuration::new(3_600_000_000_u64); // 60 minutes pub const ADDRESS_FILTER_TASK_INTERVAL_SECS: u32 = 60; pub const BOOT_MAGIC: &[u8; 4] = b"BOOT"; @@ -261,7 +261,7 @@ impl NetworkManager { where F: FnOnce(&VeilidConfigInner) -> R, { - f(&*self.unlocked_inner.config.get()) + f(&self.unlocked_inner.config.get()) } pub fn storage_manager(&self) -> StorageManager { self.unlocked_inner.storage_manager.clone() @@ -892,7 +892,7 @@ impl NetworkManager { data.len(), connection_descriptor ); - let remote_addr = connection_descriptor.remote_address().to_ip_addr(); + let remote_addr = connection_descriptor.remote_address().ip_addr(); // Network accounting self.stats_packet_rcvd(remote_addr, ByteCount::new(data.len() as u64)); @@ -900,7 +900,7 @@ impl NetworkManager { // If this is a zero length packet, just drop it, because these are used for hole punching // and possibly other low-level network connectivity tasks and will never require // more processing or forwarding - if data.len() == 0 { + if data.is_empty() { return Ok(true); } diff --git a/veilid-core/src/network_manager/native/discovery_context.rs b/veilid-core/src/network_manager/native/discovery_context.rs index 830dc28d..04101c70 100644 --- a/veilid-core/src/network_manager/native/discovery_context.rs +++ b/veilid-core/src/network_manager/native/discovery_context.rs @@ -141,10 +141,8 @@ impl DiscoveryContext { let dial_info_filter = DialInfoFilter::all() .with_protocol_type(protocol_type) .with_address_type(address_type); - let inbound_dial_info_entry_filter = RoutingTable::make_inbound_dial_info_entry_filter( - routing_domain, - dial_info_filter.clone(), - ); + let inbound_dial_info_entry_filter = + RoutingTable::make_inbound_dial_info_entry_filter(routing_domain, dial_info_filter); let disallow_relays_filter = Box::new( move |rti: &RoutingTableInner, v: Option>| { let v = v.unwrap(); @@ -199,7 +197,7 @@ impl DiscoveryContext { let node = node.filtered_clone( NodeRefFilter::new() .with_routing_domain(routing_domain) - .with_dial_info_filter(dial_info_filter.clone()), + .with_dial_info_filter(dial_info_filter), ); async move { if let Some(address) = this.request_public_address(node.clone()).await { @@ -219,9 +217,7 @@ impl DiscoveryContext { let mut external_address_infos = Vec::new(); - for ni in 0..nodes.len() - 1 { - let node = nodes[ni].clone(); - + for node in nodes.iter().take(nodes.len() - 1).cloned() { let gpa_future = get_public_address_func(node); unord.push(gpa_future); @@ -277,15 +273,15 @@ impl DiscoveryContext { node_ref.set_filter(None); // ask the node to send us a dial info validation receipt - let out = rpc_processor + + rpc_processor .rpc_call_validate_dial_info(node_ref.clone(), dial_info, redirect) .await .map_err(logthru_net!( "failed to send validate_dial_info to {:?}", node_ref )) - .unwrap_or(false); - out + .unwrap_or(false) } #[instrument(level = "trace", skip(self), ret)] @@ -307,9 +303,14 @@ impl DiscoveryContext { // Attempt a port mapping. If this doesn't succeed, it's not going to let Some(mapped_external_address) = igd_manager - .map_any_port(low_level_protocol_type, address_type, local_port, Some(external_1.address.to_ip_addr())) - .await else - { + .map_any_port( + low_level_protocol_type, + address_type, + local_port, + Some(external_1.address.ip_addr()), + ) + .await + else { return None; }; diff --git a/veilid-core/src/network_manager/native/igd_manager.rs b/veilid-core/src/network_manager/native/igd_manager.rs index ecf60618..32e3e3f2 100644 --- a/veilid-core/src/network_manager/native/igd_manager.rs +++ b/veilid-core/src/network_manager/native/igd_manager.rs @@ -184,7 +184,7 @@ impl IGDManager { let mut found = None; for (pmk, pmv) in &inner.port_maps { if pmk.llpt == llpt && pmk.at == at && pmv.mapped_port == mapped_port { - found = Some(pmk.clone()); + found = Some(*pmk); break; } } @@ -192,7 +192,7 @@ impl IGDManager { let _pmv = inner.port_maps.remove(&pmk).expect("key found but remove failed"); // Find gateway - let gw = Self::find_gateway(&mut *inner, at)?; + let gw = Self::find_gateway(&mut inner, at)?; // Unmap port match gw.remove_port(convert_llpt(llpt), mapped_port) { @@ -230,10 +230,10 @@ impl IGDManager { } // Get local ip address - let local_ip = Self::find_local_ip(&mut *inner, at)?; + let local_ip = Self::find_local_ip(&mut inner, at)?; // Find gateway - let gw = Self::find_gateway(&mut *inner, at)?; + let gw = Self::find_gateway(&mut inner, at)?; // Get external address let ext_ip = match gw.get_external_ip() { @@ -245,16 +245,12 @@ impl IGDManager { }; // Ensure external IP matches address type - if ext_ip.is_ipv4() { - if at != AddressType::IPV4 { - log_net!(debug "mismatched ip address type from igd, wanted v4, got v6"); - return None; - } - } else if ext_ip.is_ipv6() { - if at != AddressType::IPV6 { - log_net!(debug "mismatched ip address type from igd, wanted v6, got v4"); - return None; - } + if ext_ip.is_ipv4() && at != AddressType::IPV4 { + log_net!(debug "mismatched ip address type from igd, wanted v4, got v6"); + return None; + } else if ext_ip.is_ipv6() && at != AddressType::IPV6 { + log_net!(debug "mismatched ip address type from igd, wanted v6, got v4"); + return None; } if let Some(expected_external_address) = expected_external_address { diff --git a/veilid-core/src/network_manager/native/mod.rs b/veilid-core/src/network_manager/native/mod.rs index 02335a6a..389eebbd 100644 --- a/veilid-core/src/network_manager/native/mod.rs +++ b/veilid-core/src/network_manager/native/mod.rs @@ -421,7 +421,7 @@ impl Network { if self .network_manager() .address_filter() - .is_ip_addr_punished(dial_info.address().to_ip_addr()) + .is_ip_addr_punished(dial_info.address().ip_addr()) { return Ok(NetworkResult::no_connection_other("punished")); } @@ -491,7 +491,7 @@ impl Network { if self .network_manager() .address_filter() - .is_ip_addr_punished(dial_info.address().to_ip_addr()) + .is_ip_addr_punished(dial_info.address().ip_addr()) { return Ok(NetworkResult::no_connection_other("punished")); } @@ -519,7 +519,7 @@ impl Network { .into_network_result()) .wrap_err("recv_message failure")?; - let recv_socket_addr = recv_addr.remote_address().to_socket_addr(); + let recv_socket_addr = recv_addr.remote_address().socket_addr(); self.network_manager() .stats_packet_rcvd(recv_socket_addr.ip(), ByteCount::new(recv_len as u64)); @@ -583,10 +583,10 @@ impl Network { // Handle connectionless protocol if descriptor.protocol_type() == ProtocolType::UDP { // send over the best udp socket we have bound since UDP is not connection oriented - let peer_socket_addr = descriptor.remote().to_socket_addr(); + let peer_socket_addr = descriptor.remote().socket_addr(); if let Some(ph) = self.find_best_udp_protocol_handler( &peer_socket_addr, - &descriptor.local().map(|sa| sa.to_socket_addr()), + &descriptor.local().map(|sa| sa.socket_addr()), ) { network_result_value_or_log!(ph.clone() .send_message(data.clone(), peer_socket_addr) @@ -612,7 +612,7 @@ impl Network { ConnectionHandleSendResult::Sent => { // Network accounting self.network_manager().stats_packet_sent( - descriptor.remote().to_socket_addr().ip(), + descriptor.remote().socket_addr().ip(), ByteCount::new(data_len as u64), ); @@ -701,7 +701,7 @@ impl Network { .with_interfaces(|interfaces| { trace!("interfaces: {:#?}", interfaces); - for (_name, intf) in interfaces { + for intf in interfaces.values() { // Skip networks that we should never encounter if intf.is_loopback() || !intf.is_running() { continue; diff --git a/veilid-core/src/network_manager/native/network_udp.rs b/veilid-core/src/network_manager/native/network_udp.rs index 3a0e6c17..2c06a378 100644 --- a/veilid-core/src/network_manager/native/network_udp.rs +++ b/veilid-core/src/network_manager/native/network_udp.rs @@ -68,7 +68,7 @@ impl Network { Ok(Ok((size, descriptor))) => { // Network accounting network_manager.stats_packet_rcvd( - descriptor.remote_address().to_ip_addr(), + descriptor.remote_address().ip_addr(), ByteCount::new(size as u64), ); diff --git a/veilid-core/src/network_manager/native/protocol/mod.rs b/veilid-core/src/network_manager/native/protocol/mod.rs index 6cbd79e9..e2fe457c 100644 --- a/veilid-core/src/network_manager/native/protocol/mod.rs +++ b/veilid-core/src/network_manager/native/protocol/mod.rs @@ -24,7 +24,7 @@ impl ProtocolNetworkConnection { timeout_ms: u32, address_filter: AddressFilter, ) -> io::Result> { - if address_filter.is_ip_addr_punished(dial_info.address().to_ip_addr()) { + if address_filter.is_ip_addr_punished(dial_info.address().ip_addr()) { return Ok(NetworkResult::no_connection_other("punished")); } match dial_info.protocol_type() { diff --git a/veilid-core/src/network_manager/native/protocol/tcp.rs b/veilid-core/src/network_manager/native/protocol/tcp.rs index edd2a6c9..653033fe 100644 --- a/veilid-core/src/network_manager/native/protocol/tcp.rs +++ b/veilid-core/src/network_manager/native/protocol/tcp.rs @@ -19,7 +19,7 @@ impl RawTcpNetworkConnection { } pub fn descriptor(&self) -> ConnectionDescriptor { - self.descriptor.clone() + self.descriptor } // #[instrument(level = "trace", err, skip(self))] @@ -132,11 +132,12 @@ impl RawTcpProtocolHandler { ) -> io::Result> { log_net!("TCP: on_accept_async: enter"); let mut peekbuf: [u8; PEEK_DETECT_LEN] = [0u8; PEEK_DETECT_LEN]; - if let Err(_) = timeout( + if (timeout( self.connection_initial_timeout_ms, ps.peek_exact(&mut peekbuf), ) - .await + .await) + .is_err() { return Ok(None); } diff --git a/veilid-core/src/network_manager/native/protocol/udp.rs b/veilid-core/src/network_manager/native/protocol/udp.rs index 53e793a3..f63a53f8 100644 --- a/veilid-core/src/network_manager/native/protocol/udp.rs +++ b/veilid-core/src/network_manager/native/protocol/udp.rs @@ -79,9 +79,9 @@ impl RawUdpProtocolHandler { }; #[cfg(feature = "verbose-tracing")] - tracing::Span::current().record("ret.len", &message_len); + tracing::Span::current().record("ret.len", message_len); #[cfg(feature = "verbose-tracing")] - tracing::Span::current().record("ret.descriptor", &format!("{:?}", descriptor).as_str()); + tracing::Span::current().record("ret.descriptor", format!("{:?}", descriptor).as_str()); Ok((message_len, descriptor)) } @@ -134,7 +134,7 @@ impl RawUdpProtocolHandler { ); #[cfg(feature = "verbose-tracing")] - tracing::Span::current().record("ret.descriptor", &format!("{:?}", descriptor).as_str()); + tracing::Span::current().record("ret.descriptor", format!("{:?}", descriptor).as_str()); Ok(NetworkResult::value(descriptor)) } @@ -143,7 +143,7 @@ impl RawUdpProtocolHandler { socket_addr: &SocketAddr, ) -> io::Result { // get local wildcard address for bind - let local_socket_addr = compatible_unspecified_socket_addr(&socket_addr); + let local_socket_addr = compatible_unspecified_socket_addr(socket_addr); let socket = UdpSocket::bind(local_socket_addr).await?; Ok(RawUdpProtocolHandler::new(Arc::new(socket), None)) } diff --git a/veilid-core/src/network_manager/native/protocol/ws.rs b/veilid-core/src/network_manager/native/protocol/ws.rs index 80153ba4..4a3d09c6 100644 --- a/veilid-core/src/network_manager/native/protocol/ws.rs +++ b/veilid-core/src/network_manager/native/protocol/ws.rs @@ -20,7 +20,7 @@ const MAX_WS_BEFORE_BODY: usize = 2048; cfg_if! { if #[cfg(feature="rt-async-std")] { pub type WebsocketNetworkConnectionWSS = - WebsocketNetworkConnection>; + DialInfo::WS { field1: _ }ketNetworkConnection>; pub type WebsocketNetworkConnectionWS = WebsocketNetworkConnection; } else if #[cfg(feature="rt-tokio")] { pub type WebsocketNetworkConnectionWSS = @@ -74,7 +74,7 @@ where } pub fn descriptor(&self) -> ConnectionDescriptor { - self.descriptor.clone() + self.descriptor } // #[instrument(level = "trace", err, skip(self))] @@ -232,7 +232,7 @@ impl WebsocketProtocolHandler { // This check could be loosened if necessary, but until we have a reason to do so // a stricter interpretation of HTTP is possible and desirable to reduce attack surface - if peek_buf.windows(4).position(|w| w == b"\r\n\r\n").is_none() { + if !peek_buf.windows(4).any(|w| w == b"\r\n\r\n") { return Ok(None); } @@ -339,8 +339,7 @@ impl Callback for WebsocketProtocolHandler { || request .headers() .iter() - .find(|h| (h.0.as_str().len() + h.1.as_bytes().len()) > MAX_WS_HEADER_LENGTH) - .is_some() + .any(|h| (h.0.as_str().len() + h.1.as_bytes().len()) > MAX_WS_HEADER_LENGTH) { let mut error_response = ErrorResponse::new(None); *error_response.status_mut() = StatusCode::NOT_FOUND; diff --git a/veilid-core/src/network_manager/native/start_protocols.rs b/veilid-core/src/network_manager/native/start_protocols.rs index 416225c4..c5511563 100644 --- a/veilid-core/src/network_manager/native/start_protocols.rs +++ b/veilid-core/src/network_manager/native/start_protocols.rs @@ -312,7 +312,7 @@ impl Network { // if no other public address is specified if !detect_address_changes && public_address.is_none() - && routing_table.ensure_dial_info_is_valid(RoutingDomain::PublicInternet, &di) + && routing_table.ensure_dial_info_is_valid(RoutingDomain::PublicInternet, di) { editor_public_internet.register_dial_info(di.clone(), DialInfoClass::Direct)?; static_public = true; @@ -449,7 +449,7 @@ impl Network { for socket_address in socket_addresses { // Skip addresses we already did - if registered_addresses.contains(&socket_address.to_ip_addr()) { + if registered_addresses.contains(&socket_address.ip_addr()) { continue; } // Build dial info request url @@ -628,7 +628,7 @@ impl Network { } // Register interface dial info editor_local_network.register_dial_info(di.clone(), DialInfoClass::Direct)?; - registered_addresses.insert(socket_address.to_ip_addr()); + registered_addresses.insert(socket_address.ip_addr()); } // Add static public dialinfo if it's configured diff --git a/veilid-core/src/network_manager/network_connection.rs b/veilid-core/src/network_manager/network_connection.rs index 59f1a018..247866f0 100644 --- a/veilid-core/src/network_manager/network_connection.rs +++ b/veilid-core/src/network_manager/network_connection.rs @@ -52,7 +52,7 @@ pub struct DummyNetworkConnection { impl DummyNetworkConnection { pub fn descriptor(&self) -> ConnectionDescriptor { - self.descriptor.clone() + self.descriptor } // pub fn close(&self) -> io::Result<()> { // Ok(()) @@ -144,7 +144,7 @@ impl NetworkConnection { local_stop_token, manager_stop_token, connection_id, - descriptor.clone(), + descriptor, receiver, protocol_connection, stats.clone(), @@ -168,11 +168,11 @@ impl NetworkConnection { } pub fn connection_descriptor(&self) -> ConnectionDescriptor { - self.descriptor.clone() + self.descriptor } pub fn get_handle(&self) -> ConnectionHandle { - ConnectionHandle::new(self.connection_id, self.descriptor.clone(), self.sender.clone()) + ConnectionHandle::new(self.connection_id, self.descriptor, self.sender.clone()) } pub fn is_protected(&self) -> bool { @@ -197,12 +197,12 @@ impl NetworkConnection { message: Vec, ) -> io::Result> { let ts = get_aligned_timestamp(); - let out = network_result_try!(protocol_connection.send(message).await?); + network_result_try!(protocol_connection.send(message).await?); let mut stats = stats.lock(); stats.last_message_sent_time.max_assign(Some(ts)); - Ok(NetworkResult::Value(out)) + Ok(NetworkResult::Value(())) } #[cfg_attr(feature="verbose-tracing", instrument(level="trace", skip(stats), fields(ret.len)))] @@ -234,6 +234,7 @@ impl NetworkConnection { } // Connection receiver loop + #[allow(clippy::too_many_arguments)] fn process_connection( connection_manager: ConnectionManager, local_stop_token: StopToken, @@ -316,19 +317,19 @@ impl NetworkConnection { let peer_address = protocol_connection.descriptor().remote(); // Check to see if it is punished - if address_filter.is_ip_addr_punished(peer_address.to_socket_addr().ip()) { + if address_filter.is_ip_addr_punished(peer_address.socket_addr().ip()) { return RecvLoopAction::Finish; } // Check for connection close if v.is_no_connection() { - log_net!(debug "Connection closed from: {} ({})", peer_address.to_socket_addr(), peer_address.protocol_type()); + log_net!(debug "Connection closed from: {} ({})", peer_address.socket_addr(), peer_address.protocol_type()); return RecvLoopAction::Finish; } // Punish invalid framing (tcp framing or websocket framing) if v.is_invalid_message() { - address_filter.punish_ip_addr(peer_address.to_socket_addr().ip()); + address_filter.punish_ip_addr(peer_address.socket_addr().ip()); return RecvLoopAction::Finish; } diff --git a/veilid-core/src/network_manager/send_data.rs b/veilid-core/src/network_manager/send_data.rs index beecf26b..bfa95c93 100644 --- a/veilid-core/src/network_manager/send_data.rs +++ b/veilid-core/src/network_manager/send_data.rs @@ -338,7 +338,7 @@ impl NetworkManager { let routing_table = self.routing_table(); // If a node is punished, then don't try to contact it - if target_node_ref.node_ids().iter().find(|nid| self.address_filter().is_node_id_punished(**nid)).is_some() { + if target_node_ref.node_ids().iter().any(|nid| self.address_filter().is_node_id_punished(*nid)) { return Ok(NodeContactMethod::Unreachable); } diff --git a/veilid-core/src/network_manager/tasks/public_address_check.rs b/veilid-core/src/network_manager/tasks/public_address_check.rs index e106af9f..b227dabd 100644 --- a/veilid-core/src/network_manager/tasks/public_address_check.rs +++ b/veilid-core/src/network_manager/tasks/public_address_check.rs @@ -11,7 +11,7 @@ impl NetworkManager { ) -> EyreResult<()> { // go through public_address_inconsistencies_table and time out things that have expired let mut inner = self.inner.lock(); - for (_, pait_v) in &mut inner.public_address_inconsistencies_table { + for pait_v in inner.public_address_inconsistencies_table.values_mut() { let mut expired = Vec::new(); for (addr, exp_ts) in pait_v.iter() { if *exp_ts <= cur_ts { @@ -79,7 +79,7 @@ impl NetworkManager { // Get the ip(block) this report is coming from let reporting_ipblock = ip_to_ipblock( ip6_prefix_size, - connection_descriptor.remote_address().to_ip_addr(), + connection_descriptor.remote_address().ip_addr(), ); // Reject public address reports from nodes that we know are behind symmetric nat or @@ -94,7 +94,7 @@ impl NetworkManager { // If the socket address reported is the same as the reporter, then this is coming through a relay // or it should be ignored due to local proximity (nodes on the same network block should not be trusted as // public ip address reporters, only disinterested parties) - if reporting_ipblock == ip_to_ipblock(ip6_prefix_size, socket_address.to_ip_addr()) { + if reporting_ipblock == ip_to_ipblock(ip6_prefix_size, socket_address.ip_addr()) { return; } @@ -192,7 +192,7 @@ impl NetworkManager { let pait = inner .public_address_inconsistencies_table .entry(addr_proto_type_key) - .or_insert_with(|| HashMap::new()); + .or_insert_with(HashMap::new); for i in &inconsistencies { pait.insert(*i, exp_ts); } @@ -204,7 +204,7 @@ impl NetworkManager { let pait = inner .public_address_inconsistencies_table .entry(addr_proto_type_key) - .or_insert_with(|| HashMap::new()); + .or_insert_with(HashMap::new); let exp_ts = get_aligned_timestamp() + PUBLIC_ADDRESS_INCONSISTENCY_PUNISHMENT_TIMEOUT_US; for i in inconsistencies { diff --git a/veilid-core/src/network_manager/types/address.rs b/veilid-core/src/network_manager/types/address.rs index e89ed185..6b0f510a 100644 --- a/veilid-core/src/network_manager/types/address.rs +++ b/veilid-core/src/network_manager/types/address.rs @@ -71,16 +71,16 @@ impl Address { } } } - pub fn to_ip_addr(&self) -> IpAddr { + pub fn ip_addr(&self) -> IpAddr { match self { Self::IPV4(a) => IpAddr::V4(*a), Self::IPV6(a) => IpAddr::V6(*a), } } - pub fn to_socket_addr(&self, port: u16) -> SocketAddr { - SocketAddr::new(self.to_ip_addr(), port) + pub fn socket_addr(&self, port: u16) -> SocketAddr { + SocketAddr::new(self.ip_addr(), port) } - pub fn to_canonical(&self) -> Address { + pub fn canonical(&self) -> Address { match self { Address::IPV4(v4) => Address::IPV4(*v4), Address::IPV6(v6) => match v6.to_ipv4() { diff --git a/veilid-core/src/network_manager/types/address_type.rs b/veilid-core/src/network_manager/types/address_type.rs index 53ddcb4f..4c7033d6 100644 --- a/veilid-core/src/network_manager/types/address_type.rs +++ b/veilid-core/src/network_manager/types/address_type.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use super::*; -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] #[derive(Debug, PartialOrd, Ord, Hash, Serialize, Deserialize, EnumSetType)] #[enumset(repr = "u8")] pub enum AddressType { diff --git a/veilid-core/src/network_manager/types/dial_info/mod.rs b/veilid-core/src/network_manager/types/dial_info/mod.rs index 1450b3b3..c90dcc97 100644 --- a/veilid-core/src/network_manager/types/dial_info/mod.rs +++ b/veilid-core/src/network_manager/types/dial_info/mod.rs @@ -36,10 +36,10 @@ impl fmt::Display for DialInfo { let split_url = SplitUrl::from_str(&url).unwrap(); match split_url.host { SplitUrlHost::Hostname(_) => { - write!(f, "ws|{}|{}", di.socket_address.to_ip_addr(), di.request) + write!(f, "ws|{}|{}", di.socket_address.ip_addr(), di.request) } SplitUrlHost::IpAddr(a) => { - if di.socket_address.to_ip_addr() == a { + if di.socket_address.ip_addr() == a { write!(f, "ws|{}", di.request) } else { panic!("resolved address does not match url: {}", di.request); @@ -52,7 +52,7 @@ impl fmt::Display for DialInfo { let split_url = SplitUrl::from_str(&url).unwrap(); match split_url.host { SplitUrlHost::Hostname(_) => { - write!(f, "wss|{}|{}", di.socket_address.to_ip_addr(), di.request) + write!(f, "wss|{}|{}", di.socket_address.ip_addr(), di.request) } SplitUrlHost::IpAddr(_) => { panic!( @@ -143,22 +143,22 @@ impl FromStr for DialInfo { impl DialInfo { pub fn udp_from_socketaddr(socket_addr: SocketAddr) -> Self { Self::UDP(DialInfoUDP { - socket_address: SocketAddress::from_socket_addr(socket_addr).to_canonical(), + socket_address: SocketAddress::from_socket_addr(socket_addr).canonical(), }) } pub fn tcp_from_socketaddr(socket_addr: SocketAddr) -> Self { Self::TCP(DialInfoTCP { - socket_address: SocketAddress::from_socket_addr(socket_addr).to_canonical(), + socket_address: SocketAddress::from_socket_addr(socket_addr).canonical(), }) } pub fn udp(socket_address: SocketAddress) -> Self { Self::UDP(DialInfoUDP { - socket_address: socket_address.to_canonical(), + socket_address: socket_address.canonical(), }) } pub fn tcp(socket_address: SocketAddress) -> Self { Self::TCP(DialInfoTCP { - socket_address: socket_address.to_canonical(), + socket_address: socket_address.canonical(), }) } pub fn try_ws(socket_address: SocketAddress, url: String) -> VeilidAPIResult { @@ -173,7 +173,7 @@ impl DialInfo { apibail_parse_error!("socket address port doesn't match url port", url); } if let SplitUrlHost::IpAddr(a) = split_url.host { - if socket_address.to_ip_addr() != a { + if socket_address.ip_addr() != a { apibail_parse_error!( format!("request address does not match socket address: {}", a), socket_address @@ -181,7 +181,7 @@ impl DialInfo { } } Ok(Self::WS(DialInfoWS { - socket_address: socket_address.to_canonical(), + socket_address: socket_address.canonical(), request: url[5..].to_string(), })) } @@ -203,7 +203,7 @@ impl DialInfo { ); } Ok(Self::WSS(DialInfoWSS { - socket_address: socket_address.to_canonical(), + socket_address: socket_address.canonical(), request: url[6..].to_string(), })) } @@ -244,10 +244,10 @@ impl DialInfo { } pub fn to_ip_addr(&self) -> IpAddr { match self { - Self::UDP(di) => di.socket_address.to_ip_addr(), - Self::TCP(di) => di.socket_address.to_ip_addr(), - Self::WS(di) => di.socket_address.to_ip_addr(), - Self::WSS(di) => di.socket_address.to_ip_addr(), + Self::UDP(di) => di.socket_address.ip_addr(), + Self::TCP(di) => di.socket_address.ip_addr(), + Self::WS(di) => di.socket_address.ip_addr(), + Self::WSS(di) => di.socket_address.ip_addr(), } } pub fn port(&self) -> u16 { @@ -268,10 +268,10 @@ impl DialInfo { } pub fn to_socket_addr(&self) -> SocketAddr { match self { - Self::UDP(di) => di.socket_address.to_socket_addr(), - Self::TCP(di) => di.socket_address.to_socket_addr(), - Self::WS(di) => di.socket_address.to_socket_addr(), - Self::WSS(di) => di.socket_address.to_socket_addr(), + Self::UDP(di) => di.socket_address.socket_addr(), + Self::TCP(di) => di.socket_address.socket_addr(), + Self::WS(di) => di.socket_address.socket_addr(), + Self::WSS(di) => di.socket_address.socket_addr(), } } pub fn to_peer_address(&self) -> PeerAddress { @@ -376,11 +376,11 @@ impl DialInfo { "udp" => Self::udp_from_socketaddr(sa), "tcp" => Self::tcp_from_socketaddr(sa), "ws" => Self::try_ws( - SocketAddress::from_socket_addr(sa).to_canonical(), + SocketAddress::from_socket_addr(sa).canonical(), url.to_string(), )?, "wss" => Self::try_wss( - SocketAddress::from_socket_addr(sa).to_canonical(), + SocketAddress::from_socket_addr(sa).canonical(), url.to_string(), )?, _ => { @@ -395,13 +395,13 @@ impl DialInfo { match self { DialInfo::UDP(di) => ( format!("U{}", di.socket_address.port()), - intf::ptr_lookup(di.socket_address.to_ip_addr()) + intf::ptr_lookup(di.socket_address.ip_addr()) .await .unwrap_or_else(|_| di.socket_address.to_string()), ), DialInfo::TCP(di) => ( format!("T{}", di.socket_address.port()), - intf::ptr_lookup(di.socket_address.to_ip_addr()) + intf::ptr_lookup(di.socket_address.ip_addr()) .await .unwrap_or_else(|_| di.socket_address.to_string()), ), @@ -447,11 +447,11 @@ impl DialInfo { } pub async fn to_url(&self) -> String { match self { - DialInfo::UDP(di) => intf::ptr_lookup(di.socket_address.to_ip_addr()) + DialInfo::UDP(di) => intf::ptr_lookup(di.socket_address.ip_addr()) .await .map(|h| format!("udp://{}:{}", h, di.socket_address.port())) .unwrap_or_else(|_| format!("udp://{}", di.socket_address)), - DialInfo::TCP(di) => intf::ptr_lookup(di.socket_address.to_ip_addr()) + DialInfo::TCP(di) => intf::ptr_lookup(di.socket_address.ip_addr()) .await .map(|h| format!("tcp://{}:{}", h, di.socket_address.port())) .unwrap_or_else(|_| format!("tcp://{}", di.socket_address)), diff --git a/veilid-core/src/network_manager/types/low_level_protocol_type.rs b/veilid-core/src/network_manager/types/low_level_protocol_type.rs index be552282..c9e96d3b 100644 --- a/veilid-core/src/network_manager/types/low_level_protocol_type.rs +++ b/veilid-core/src/network_manager/types/low_level_protocol_type.rs @@ -4,7 +4,7 @@ use super::*; // Keep member order appropriate for sorting < preference // Must match DialInfo order -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] #[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)] #[enumset(repr = "u8")] pub enum LowLevelProtocolType { diff --git a/veilid-core/src/network_manager/types/peer_address.rs b/veilid-core/src/network_manager/types/peer_address.rs index e505aa1c..1e56bd9b 100644 --- a/veilid-core/src/network_manager/types/peer_address.rs +++ b/veilid-core/src/network_manager/types/peer_address.rs @@ -10,7 +10,7 @@ pub struct PeerAddress { impl PeerAddress { pub fn new(socket_address: SocketAddress, protocol_type: ProtocolType) -> Self { Self { - socket_address: socket_address.to_canonical(), + socket_address: socket_address.canonical(), protocol_type, } } @@ -23,8 +23,8 @@ impl PeerAddress { self.protocol_type } - pub fn to_socket_addr(&self) -> SocketAddr { - self.socket_address.to_socket_addr() + pub fn socket_addr(&self) -> SocketAddr { + self.socket_address.socket_addr() } pub fn address_type(&self) -> AddressType { @@ -42,7 +42,10 @@ impl FromStr for PeerAddress { type Err = VeilidAPIError; fn from_str(s: &str) -> VeilidAPIResult { let Some((first, second)) = s.split_once(':') else { - return Err(VeilidAPIError::parse_error("PeerAddress is missing a colon: {}", s)); + return Err(VeilidAPIError::parse_error( + "PeerAddress is missing a colon: {}", + s, + )); }; let protocol_type = ProtocolType::from_str(first)?; let socket_address = SocketAddress::from_str(second)?; diff --git a/veilid-core/src/network_manager/types/protocol_type.rs b/veilid-core/src/network_manager/types/protocol_type.rs index 54319322..0279d307 100644 --- a/veilid-core/src/network_manager/types/protocol_type.rs +++ b/veilid-core/src/network_manager/types/protocol_type.rs @@ -3,7 +3,7 @@ use super::*; // Keep member order appropriate for sorting < preference // Must match DialInfo order -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] #[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)] #[enumset(repr = "u8")] pub enum ProtocolType { diff --git a/veilid-core/src/network_manager/types/socket_address.rs b/veilid-core/src/network_manager/types/socket_address.rs index 23700543..ad30bbdf 100644 --- a/veilid-core/src/network_manager/types/socket_address.rs +++ b/veilid-core/src/network_manager/types/socket_address.rs @@ -34,27 +34,27 @@ impl SocketAddress { self.port = port } pub fn with_port(&self, port: u16) -> Self { - let mut sa = self.clone(); + let mut sa = *self; sa.port = port; sa } - pub fn to_canonical(&self) -> SocketAddress { + pub fn canonical(&self) -> SocketAddress { SocketAddress { - address: self.address.to_canonical(), + address: self.address.canonical(), port: self.port, } } - pub fn to_ip_addr(&self) -> IpAddr { - self.address.to_ip_addr() + pub fn ip_addr(&self) -> IpAddr { + self.address.ip_addr() } - pub fn to_socket_addr(&self) -> SocketAddr { - self.address.to_socket_addr(self.port) + pub fn socket_addr(&self) -> SocketAddr { + self.address.socket_addr(self.port) } } impl fmt::Display for SocketAddress { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!(f, "{}", self.to_socket_addr()) + write!(f, "{}", self.socket_addr()) } } diff --git a/veilid-core/src/routing_table/bucket_entry.rs b/veilid-core/src/routing_table/bucket_entry.rs index 0d6fd71b..ebacfe3e 100644 --- a/veilid-core/src/routing_table/bucket_entry.rs +++ b/veilid-core/src/routing_table/bucket_entry.rs @@ -223,7 +223,7 @@ impl BucketEntryInner { // Lower timestamp to the front, recent or no timestamp is at the end if let Some(e1_ts) = &e1.peer_stats.rpc_stats.first_consecutive_seen_ts { if let Some(e2_ts) = &e2.peer_stats.rpc_stats.first_consecutive_seen_ts { - e1_ts.cmp(&e2_ts) + e1_ts.cmp(e2_ts) } else { std::cmp::Ordering::Less } @@ -437,7 +437,7 @@ impl BucketEntryInner { // Clears the table of last connections except the most recent one pub fn clear_last_connections_except_latest(&mut self) { - if self.last_connections.len() == 0 { + if self.last_connections.is_empty() { // No last_connections return; } @@ -454,7 +454,7 @@ impl BucketEntryInner { let Some(most_recent_connection) = most_recent_connection else { return; }; - for (k, _) in &self.last_connections { + for k in self.last_connections.keys() { if k != most_recent_connection { dead_keys.push(k.clone()); } diff --git a/veilid-core/src/routing_table/mod.rs b/veilid-core/src/routing_table/mod.rs index 38b89504..8808d757 100644 --- a/veilid-core/src/routing_table/mod.rs +++ b/veilid-core/src/routing_table/mod.rs @@ -388,11 +388,15 @@ impl RoutingTable { } // Caches valid, load saved routing table - let Some(serialized_bucket_map): Option = db.load_json(0, SERIALIZED_BUCKET_MAP).await? else { + let Some(serialized_bucket_map): Option = + db.load_json(0, SERIALIZED_BUCKET_MAP).await? + else { log_rtab!(debug "no bucket map in saved routing table"); return Ok(()); }; - let Some(all_entry_bytes): Option = db.load_json(0, ALL_ENTRY_BYTES).await? else { + let Some(all_entry_bytes): Option = + db.load_json(0, ALL_ENTRY_BYTES).await? + else { log_rtab!(debug "no all_entry_bytes in saved routing table"); return Ok(()); }; diff --git a/veilid-core/src/routing_table/routing_domain_editor.rs b/veilid-core/src/routing_table/routing_domain_editor.rs index 385fe4b5..6e015fe4 100644 --- a/veilid-core/src/routing_table/routing_domain_editor.rs +++ b/veilid-core/src/routing_table/routing_domain_editor.rs @@ -258,11 +258,9 @@ impl RoutingDomainEditor { } } // Clear the routespecstore cache if our PublicInternet dial info has changed - if changed { - if self.routing_domain == RoutingDomain::PublicInternet { - let rss = self.routing_table.route_spec_store(); - rss.reset(); - } + if changed && self.routing_domain == RoutingDomain::PublicInternet { + let rss = self.routing_table.route_spec_store(); + rss.reset(); } } } diff --git a/veilid-core/src/routing_table/routing_domains.rs b/veilid-core/src/routing_table/routing_domains.rs index ba120369..df7c7036 100644 --- a/veilid-core/src/routing_table/routing_domains.rs +++ b/veilid-core/src/routing_table/routing_domains.rs @@ -250,7 +250,7 @@ pub trait RoutingDomainDetail { peer_b: &PeerInfo, dial_info_filter: DialInfoFilter, sequencing: Sequencing, - dif_sort: Option core::cmp::Ordering>>, + dif_sort: Option>, ) -> ContactMethod; } @@ -301,12 +301,10 @@ fn first_filtered_dial_info_detail_between_nodes( } else { Some(Box::new(move |a,b| { DialInfoDetail::ordered_sequencing_sort(a,b) })) } + } else if let Some(dif_sort) = dif_sort { + Some(Box::new(move |a,b| { dif_sort(a,b) })) } else { - if let Some(dif_sort) = dif_sort { - Some(Box::new(move |a,b| { dif_sort(a,b) })) - } else { - None - } + None }; // If the filter is dead then we won't be able to connect @@ -336,7 +334,7 @@ impl RoutingDomainDetail for PublicInternetRoutingDomainDetail { peer_b: &PeerInfo, dial_info_filter: DialInfoFilter, sequencing: Sequencing, - dif_sort: Option core::cmp::Ordering>>, + dif_sort: Option>, ) -> ContactMethod { // Get the nodeinfos for convenience let node_a = peer_a.signed_node_info().node_info(); @@ -554,7 +552,7 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail { &mut self.common } fn can_contain_address(&self, address: Address) -> bool { - let ip = address.to_ip_addr(); + let ip = address.ip_addr(); for localnet in &self.local_networks { if ipaddr_in_network(ip, localnet.0, localnet.1) { return true; @@ -570,7 +568,7 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail { peer_b: &PeerInfo, dial_info_filter: DialInfoFilter, sequencing: Sequencing, - dif_sort: Option core::cmp::Ordering>>, + dif_sort: Option>, ) -> ContactMethod { // Scope the filter down to protocols node A can do outbound let dial_info_filter = dial_info_filter.filtered( @@ -596,12 +594,10 @@ impl RoutingDomainDetail for LocalNetworkRoutingDomainDetail { } else { Some(Box::new(move |a,b| { DialInfoDetail::ordered_sequencing_sort(a,b) })) } + } else if let Some(dif_sort) = dif_sort { + Some(Box::new(move |a,b| { dif_sort(a,b) })) } else { - if let Some(dif_sort) = dif_sort { - Some(Box::new(move |a,b| { dif_sort(a,b) })) - } else { - None - } + None }; // If the filter is dead then we won't be able to connect diff --git a/veilid-core/src/routing_table/routing_table_inner.rs b/veilid-core/src/routing_table/routing_table_inner.rs index c2cfc291..36460be9 100644 --- a/veilid-core/src/routing_table/routing_table_inner.rs +++ b/veilid-core/src/routing_table/routing_table_inner.rs @@ -550,10 +550,9 @@ impl RoutingTableInner { } // If we don't have node status for this node, then we should ping it to get some node status - if e.has_node_info(routing_domain.into()) { - if e.node_status(routing_domain).is_none() { - return true; - } + if e.has_node_info(routing_domain.into()) && e.node_status(routing_domain).is_none() + { + return true; } // If this entry needs a ping because this node hasn't seen our latest node info, then do it diff --git a/veilid-core/src/routing_table/tasks/bootstrap.rs b/veilid-core/src/routing_table/tasks/bootstrap.rs index f48a6011..0f89655e 100644 --- a/veilid-core/src/routing_table/tasks/bootstrap.rs +++ b/veilid-core/src/routing_table/tasks/bootstrap.rs @@ -327,7 +327,7 @@ impl RoutingTable { } } } - if bootstrap_dialinfos.len() > 0 { + if !bootstrap_dialinfos.is_empty() { return self .direct_bootstrap_task_routine(stop_token, bootstrap_dialinfos) .await; diff --git a/veilid-core/src/routing_table/tasks/private_route_management.rs b/veilid-core/src/routing_table/tasks/private_route_management.rs index dcf9fee1..2bab77de 100644 --- a/veilid-core/src/routing_table/tasks/private_route_management.rs +++ b/veilid-core/src/routing_table/tasks/private_route_management.rs @@ -78,8 +78,11 @@ impl RoutingTable { // Save up to N unpublished routes and test them let background_safety_route_count = self.get_background_safety_route_count(); - for x in 0..(usize::min(background_safety_route_count, unpublished_routes.len())) { - must_test_routes.push(unpublished_routes[x].0); + for unpublished_route in unpublished_routes.iter().take(usize::min( + background_safety_route_count, + unpublished_routes.len(), + )) { + must_test_routes.push(unpublished_route.0); } // Kill off all but N unpublished routes rather than testing them @@ -225,9 +228,9 @@ impl RoutingTable { let remote_routes_needing_testing = rss.list_remote_routes(|k, v| { let stats = v.get_stats(); if stats.needs_testing(cur_ts) { - return Some(*k); + Some(*k) } else { - return None; + None } }); if !remote_routes_needing_testing.is_empty() { diff --git a/veilid-core/src/routing_table/types/dial_info_detail.rs b/veilid-core/src/routing_table/types/dial_info_detail.rs index 4e59b1af..dc7db216 100644 --- a/veilid-core/src/routing_table/types/dial_info_detail.rs +++ b/veilid-core/src/routing_table/types/dial_info_detail.rs @@ -13,6 +13,8 @@ impl MatchesDialInfoFilter for DialInfoDetail { } } +pub type DialInfoDetailSort = dyn Fn(&DialInfoDetail, &DialInfoDetail) -> core::cmp::Ordering; + impl DialInfoDetail { pub fn ordered_sequencing_sort(a: &DialInfoDetail, b: &DialInfoDetail) -> core::cmp::Ordering { let c = DialInfo::ordered_sequencing_sort(&a.dial_info, &b.dial_info); diff --git a/veilid-core/src/routing_table/types/direction.rs b/veilid-core/src/routing_table/types/direction.rs index 76187032..9702d3ca 100644 --- a/veilid-core/src/routing_table/types/direction.rs +++ b/veilid-core/src/routing_table/types/direction.rs @@ -2,7 +2,7 @@ use super::*; -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] #[derive(Debug, PartialOrd, Ord, Hash, EnumSetType, Serialize, Deserialize)] #[enumset(repr = "u8")] pub enum Direction { diff --git a/veilid-core/src/routing_table/types/peer_info.rs b/veilid-core/src/routing_table/types/peer_info.rs index 60e83430..7a143790 100644 --- a/veilid-core/src/routing_table/types/peer_info.rs +++ b/veilid-core/src/routing_table/types/peer_info.rs @@ -8,7 +8,7 @@ pub struct PeerInfo { impl PeerInfo { pub fn new(node_ids: TypedKeyGroup, signed_node_info: SignedNodeInfo) -> Self { - assert!(node_ids.len() > 0 && node_ids.len() <= MAX_CRYPTO_KINDS); + assert!(!node_ids.is_empty() && node_ids.len() <= MAX_CRYPTO_KINDS); Self { node_ids, signed_node_info, diff --git a/veilid-core/src/routing_table/types/routing_domain.rs b/veilid-core/src/routing_table/types/routing_domain.rs index 8947fd82..75edaca8 100644 --- a/veilid-core/src/routing_table/types/routing_domain.rs +++ b/veilid-core/src/routing_table/types/routing_domain.rs @@ -3,7 +3,7 @@ use super::*; // Routing domain here is listed in order of preference, keep in order -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] #[derive(Debug, Ord, PartialOrd, Hash, EnumSetType, Serialize, Deserialize)] #[enumset(repr = "u8")] pub enum RoutingDomain { diff --git a/veilid-core/src/routing_table/types/signed_direct_node_info.rs b/veilid-core/src/routing_table/types/signed_direct_node_info.rs index 521b1bbe..ddc8198b 100644 --- a/veilid-core/src/routing_table/types/signed_direct_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_direct_node_info.rs @@ -29,7 +29,7 @@ impl SignedDirectNodeInfo { // Verify the signatures that we can let validated_node_ids = crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?; - if validated_node_ids.len() == 0 { + if validated_node_ids.is_empty() { apibail_generic!("no valid node ids in direct node info"); } diff --git a/veilid-core/src/routing_table/types/signed_node_info.rs b/veilid-core/src/routing_table/types/signed_node_info.rs index 801de847..d56597ea 100644 --- a/veilid-core/src/routing_table/types/signed_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_node_info.rs @@ -33,8 +33,8 @@ impl SignedNodeInfo { } pub fn node_info(&self) -> &NodeInfo { match self { - SignedNodeInfo::Direct(d) => &d.node_info(), - SignedNodeInfo::Relayed(r) => &r.node_info(), + SignedNodeInfo::Direct(d) => d.node_info(), + SignedNodeInfo::Relayed(r) => r.node_info(), } } pub fn relay_ids(&self) -> TypedKeyGroup { diff --git a/veilid-core/src/routing_table/types/signed_relayed_node_info.rs b/veilid-core/src/routing_table/types/signed_relayed_node_info.rs index 462ebb31..bed33ba0 100644 --- a/veilid-core/src/routing_table/types/signed_relayed_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_relayed_node_info.rs @@ -55,7 +55,7 @@ impl SignedRelayedNodeInfo { )?; let validated_node_ids = crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?; - if validated_node_ids.len() == 0 { + if validated_node_ids.is_empty() { apibail_generic!("no valid node ids in relayed node info"); } Ok(validated_node_ids) diff --git a/veilid-core/src/storage_manager/mod.rs b/veilid-core/src/storage_manager/mod.rs index fe80c4ad..05ef39c1 100644 --- a/veilid-core/src/storage_manager/mod.rs +++ b/veilid-core/src/storage_manager/mod.rs @@ -474,21 +474,21 @@ impl StorageManager { pub async fn watch_values( &self, - key: TypedKey, - subkeys: ValueSubkeyRangeSet, - expiration: Timestamp, - count: u32, + _key: TypedKey, + _subkeys: ValueSubkeyRangeSet, + _expiration: Timestamp, + _count: u32, ) -> VeilidAPIResult { - let inner = self.lock().await?; + let _inner = self.lock().await?; unimplemented!(); } pub async fn cancel_watch_values( &self, - key: TypedKey, - subkeys: ValueSubkeyRangeSet, + _key: TypedKey, + _subkeys: ValueSubkeyRangeSet, ) -> VeilidAPIResult { - let inner = self.lock().await?; + let _inner = self.lock().await?; unimplemented!(); } } diff --git a/veilid-core/src/veilid_api/debug.rs b/veilid-core/src/veilid_api/debug.rs index 5d633868..3801e4cd 100644 --- a/veilid-core/src/veilid_api/debug.rs +++ b/veilid-core/src/veilid_api/debug.rs @@ -219,19 +219,19 @@ fn get_destination( let private_route = if let Some(prid) = get_route_id(rss.clone(), false, true)(text) { let Some(private_route) = rss.best_remote_private_route(&prid) else { - return None; - }; + return None; + }; private_route } else { let mut dc = DEBUG_CACHE.lock(); let n = get_number(text)?; let prid = dc.imported_routes.get(n)?.clone(); let Some(private_route) = rss.best_remote_private_route(&prid) else { - // Remove imported route - dc.imported_routes.remove(n); - info!("removed dead imported route {}", n); - return None; - }; + // Remove imported route + dc.imported_routes.remove(n); + info!("removed dead imported route {}", n); + return None; + }; private_route }; diff --git a/veilid-flutter/rust/src/lib.rs b/veilid-flutter/rust/src/lib.rs index 2121c5ce..b844dd3a 100644 --- a/veilid-flutter/rust/src/lib.rs +++ b/veilid-flutter/rust/src/lib.rs @@ -1,3 +1,6 @@ +#![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] +#![deny(unused_must_use)] #![recursion_limit = "256"] mod dart_ffi; diff --git a/veilid-server/src/main.rs b/veilid-server/src/main.rs index 2c789bbc..a555f2ee 100644 --- a/veilid-server/src/main.rs +++ b/veilid-server/src/main.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] #![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] #![deny(unused_must_use)] #![recursion_limit = "256"] diff --git a/veilid-tools/src/assembly_buffer.rs b/veilid-tools/src/assembly_buffer.rs index 75ea4143..316f86b8 100644 --- a/veilid-tools/src/assembly_buffer.rs +++ b/veilid-tools/src/assembly_buffer.rs @@ -430,3 +430,9 @@ impl AssemblyBuffer { Ok(NetworkResult::value(())) } } + +impl Default for AssemblyBuffer { + fn default() -> Self { + Self::new() + } +} diff --git a/veilid-tools/src/async_tag_lock.rs b/veilid-tools/src/async_tag_lock.rs index ec9e8ec3..4375b7ee 100644 --- a/veilid-tools/src/async_tag_lock.rs +++ b/veilid-tools/src/async_tag_lock.rs @@ -91,6 +91,11 @@ where } } + pub fn is_empty(&self) -> bool { + let inner = self.inner.lock(); + inner.table.is_empty() + } + pub fn len(&self) -> usize { let inner = self.inner.lock(); inner.table.len() @@ -154,3 +159,12 @@ where Some(AsyncTagLockGuard::new(self.clone(), tag, guard)) } } + +impl Default for AsyncTagLockTable +where + T: Hash + Eq + Clone + Debug, +{ + fn default() -> Self { + Self::new() + } +} diff --git a/veilid-tools/src/lib.rs b/veilid-tools/src/lib.rs index c824f696..e9cb44b1 100644 --- a/veilid-tools/src/lib.rs +++ b/veilid-tools/src/lib.rs @@ -20,6 +20,9 @@ //! * `rt-async-std` - Uses `async-std` as the async runtime //! * `rt-wasm-bindgen` - When building for the `wasm32` architecture, use this to enable `wasm-bindgen-futures` as the async runtime //! +#![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] +#![deny(unused_must_use)] // pub mod bump_port; pub mod assembly_buffer; diff --git a/veilid-tools/src/timestamp.rs b/veilid-tools/src/timestamp.rs index 94f9871e..fb290966 100644 --- a/veilid-tools/src/timestamp.rs +++ b/veilid-tools/src/timestamp.rs @@ -68,29 +68,32 @@ cfg_if! { let show_month = show_year || now.month() != date.month(); let show_date = show_month || now.day() != date.day(); + let s_year = if show_year { + format!("{:04}/",date.year()) + } else { + "".to_owned() + }; + let s_month = if show_month { + format!("{:02}/",date.month()) + } else { + "".to_owned() + }; + let s_date = if show_date { + format!("{:02}-",date.day()) + } else { + "".to_owned() + }; + let s_time = format!("{:02}:{:02}:{:02}.{:04}", + date.hour(), + date.minute(), + date.second(), + date.nanosecond()/1_000_000 + ); format!("{}{}{}{}", - if show_year { - format!("{:04}/",date.year()) - } else { - "".to_owned() - }, - if show_month { - format!("{:02}/",date.month()) - } else { - "".to_owned() - }, - if show_date { - format!("{:02}-",date.day()) - } else { - "".to_owned() - }, - format!("{:02}:{:02}:{:02}.{:04}", - date.hour(), - date.minute(), - date.second(), - date.nanosecond()/1_000_000 - )) - + s_year, + s_month, + s_date, + s_time) } } } diff --git a/veilid-tools/src/tools.rs b/veilid-tools/src/tools.rs index d26f87b1..9543f9aa 100644 --- a/veilid-tools/src/tools.rs +++ b/veilid-tools/src/tools.rs @@ -242,8 +242,10 @@ pub fn compatible_unspecified_socket_addr(socket_addr: &SocketAddr) -> SocketAdd pub fn listen_address_to_socket_addrs(listen_address: &str) -> Result, String> { // If no address is specified, but the port is, use ipv4 and ipv6 unspecified // If the address is specified, only use the specified port and fail otherwise - let ip_addrs = [IpAddr::V4(Ipv4Addr::UNSPECIFIED), - IpAddr::V6(Ipv6Addr::UNSPECIFIED)]; + let ip_addrs = [ + IpAddr::V4(Ipv4Addr::UNSPECIFIED), + IpAddr::V6(Ipv6Addr::UNSPECIFIED), + ]; Ok(if let Some(portstr) = listen_address.strip_prefix(':') { let port = portstr @@ -333,6 +335,8 @@ cfg_if::cfg_if! { #[repr(C, align(8))] struct AlignToEight([u8; 8]); +/// # Safety +/// Ensure you immediately initialize this vector as it could contain sensitive data pub unsafe fn aligned_8_u8_vec_uninit(n_bytes: usize) -> Vec { let n_units = (n_bytes + mem::size_of::() - 1) / mem::size_of::(); let mut aligned: Vec = Vec::with_capacity(n_units); @@ -347,6 +351,8 @@ pub unsafe fn aligned_8_u8_vec_uninit(n_bytes: usize) -> Vec { ) } +/// # Safety +/// Ensure you immediately initialize this vector as it could contain sensitive data pub unsafe fn unaligned_u8_vec_uninit(n_bytes: usize) -> Vec { let mut unaligned: Vec = Vec::with_capacity(n_bytes); let ptr = unaligned.as_mut_ptr(); diff --git a/veilid-wasm/src/lib.rs b/veilid-wasm/src/lib.rs index fa87391c..d28eeb0f 100644 --- a/veilid-wasm/src/lib.rs +++ b/veilid-wasm/src/lib.rs @@ -1,5 +1,7 @@ // wasm-bindgen and clippy don't play well together yet -#![allow(clippy::all)] +#![deny(clippy::all)] +#![allow(clippy::comparison_chain, clippy::upper_case_acronyms)] +#![deny(unused_must_use)] #![cfg(target_arch = "wasm32")] #![no_std] @@ -363,7 +365,10 @@ pub fn routing_context_with_custom_privacy(id: u32, safety_selection: String) -> let Some(routing_context) = rc.get(&id) else { return 0; }; - let Ok(routing_context) = routing_context.clone().with_custom_privacy(safety_selection) else { + let Ok(routing_context) = routing_context + .clone() + .with_custom_privacy(safety_selection) + else { return 0; }; let new_id = add_routing_context(routing_context); @@ -392,7 +397,11 @@ pub fn routing_context_app_call(id: u32, target_string: String, request: String) let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_app_call", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_app_call", + "id", + id, + )); }; routing_context.clone() }; @@ -414,7 +423,11 @@ pub fn routing_context_app_message(id: u32, target_string: String, message: Stri let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_app_message", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_app_message", + "id", + id, + )); }; routing_context.clone() }; @@ -439,7 +452,11 @@ pub fn routing_context_create_dht_record(id: u32, schema: String, kind: u32) -> let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_create_dht_record", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_create_dht_record", + "id", + id, + )); }; routing_context.clone() }; @@ -460,7 +477,11 @@ pub fn routing_context_open_dht_record(id: u32, key: String, writer: Option Promise { let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_close_dht_record", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_close_dht_record", + "id", + id, + )); }; routing_context.clone() }; @@ -492,7 +517,11 @@ pub fn routing_context_delete_dht_record(id: u32, key: String) -> Promise { let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_delete_dht_record", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_delete_dht_record", + "id", + id, + )); }; routing_context.clone() }; @@ -513,7 +542,11 @@ pub fn routing_context_get_dht_value( let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_get_dht_value", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_get_dht_value", + "id", + id, + )); }; routing_context.clone() }; @@ -535,7 +568,11 @@ pub fn routing_context_set_dht_value(id: u32, key: String, subkey: u32, data: St let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_set_dht_value", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_set_dht_value", + "id", + id, + )); }; routing_context.clone() }; @@ -561,7 +598,11 @@ pub fn routing_context_watch_dht_values( let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_watch_dht_values", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_watch_dht_values", + "id", + id, + )); }; routing_context.clone() }; @@ -582,7 +623,11 @@ pub fn routing_context_cancel_dht_watch(id: u32, key: String, subkeys: String) - let routing_context = { let rc = (*ROUTING_CONTEXTS).borrow(); let Some(routing_context) = rc.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("routing_context_cancel_dht_watch", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "routing_context_cancel_dht_watch", + "id", + id, + )); }; routing_context.clone() }; @@ -730,7 +775,11 @@ pub fn table_db_get_keys(id: u32, col: u32) -> Promise { let table_db = { let table_dbs = (*TABLE_DBS).borrow(); let Some(table_db) = table_dbs.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_store", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_store", + "id", + id, + )); }; table_db.clone() }; @@ -780,7 +829,11 @@ pub fn table_db_transaction_commit(id: u32) -> Promise { let tdbt = { let tdbts = (*TABLE_DB_TRANSACTIONS).borrow(); let Some(tdbt) = tdbts.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_transaction_commit", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_transaction_commit", + "id", + id, + )); }; tdbt.clone() }; @@ -796,7 +849,11 @@ pub fn table_db_transaction_rollback(id: u32) -> Promise { let tdbt = { let tdbts = (*TABLE_DB_TRANSACTIONS).borrow(); let Some(tdbt) = tdbts.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_transaction_rollback", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_transaction_rollback", + "id", + id, + )); }; tdbt.clone() }; @@ -818,7 +875,11 @@ pub fn table_db_transaction_store(id: u32, col: u32, key: String, value: String) let tdbt = { let tdbts = (*TABLE_DB_TRANSACTIONS).borrow(); let Some(tdbt) = tdbts.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_transaction_store", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_transaction_store", + "id", + id, + )); }; tdbt.clone() }; @@ -837,7 +898,11 @@ pub fn table_db_transaction_delete(id: u32, col: u32, key: String) -> Promise { let tdbt = { let tdbts = (*TABLE_DB_TRANSACTIONS).borrow(); let Some(tdbt) = tdbts.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_transaction_delete", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_transaction_delete", + "id", + id, + )); }; tdbt.clone() }; @@ -859,7 +924,11 @@ pub fn table_db_store(id: u32, col: u32, key: String, value: String) -> Promise let table_db = { let table_dbs = (*TABLE_DBS).borrow(); let Some(table_db) = table_dbs.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_store", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_store", + "id", + id, + )); }; table_db.clone() }; @@ -878,7 +947,11 @@ pub fn table_db_load(id: u32, col: u32, key: String) -> Promise { let table_db = { let table_dbs = (*TABLE_DBS).borrow(); let Some(table_db) = table_dbs.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_load", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_load", + "id", + id, + )); }; table_db.clone() }; @@ -898,7 +971,11 @@ pub fn table_db_delete(id: u32, col: u32, key: String) -> Promise { let table_db = { let table_dbs = (*TABLE_DBS).borrow(); let Some(table_db) = table_dbs.get(&id) else { - return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument("table_db_delete", "id", id)); + return APIResult::Err(veilid_core::VeilidAPIError::invalid_argument( + "table_db_delete", + "id", + id, + )); }; table_db.clone() };