more clippy

This commit is contained in:
Christien Rioux
2023-09-18 15:22:40 -04:00
parent c7d4462e0e
commit f596b3ce05
32 changed files with 839 additions and 853 deletions

View File

@@ -263,7 +263,7 @@ impl VeilidAPI {
let rss = self.routing_table()?.route_spec_store();
let r = rss
.allocate_route(
&crypto_kinds,
crypto_kinds,
stability,
sequencing,
default_route_hop_count,
@@ -275,7 +275,7 @@ impl VeilidAPI {
apibail_generic!("unable to allocate route");
};
if !rss
.test_route(route_id.clone())
.test_route(route_id)
.await
.map_err(VeilidAPIError::no_connection)?
{

View File

@@ -61,9 +61,9 @@ fn get_string(text: &str) -> Option<String> {
}
fn get_data(text: &str) -> Option<Vec<u8>> {
if text.starts_with("#") {
hex::decode(&text[1..]).ok()
} else if text.starts_with("\"") || text.starts_with("'") {
if let Some(stripped_text) = text.strip_prefix('#') {
hex::decode(stripped_text).ok()
} else if text.starts_with('"') || text.starts_with('\'') {
json::parse(text)
.ok()?
.as_str()
@@ -86,7 +86,7 @@ fn get_route_id(
allow_allocated: bool,
allow_remote: bool,
) -> impl Fn(&str) -> Option<RouteId> {
return move |text: &str| {
move |text: &str| {
if text.is_empty() {
return None;
}
@@ -127,7 +127,7 @@ fn get_route_id(
}
}
None
};
}
}
fn get_dht_schema(text: &str) -> Option<DHTSchema> {
@@ -140,7 +140,7 @@ fn get_safety_selection(routing_table: RoutingTable) -> impl Fn(&str) -> Option<
let default_route_hop_count =
routing_table.with_config(|c| c.network.rpc.default_route_hop_count as usize);
if text.len() != 0 && &text[0..1] == "-" {
if !text.is_empty() && &text[0..1] == "-" {
// Unsafe
let text = &text[1..];
let seq = get_sequencing(text).unwrap_or_default();
@@ -151,7 +151,7 @@ fn get_safety_selection(routing_table: RoutingTable) -> impl Fn(&str) -> Option<
let mut hop_count = default_route_hop_count;
let mut stability = Stability::default();
let mut sequencing = Sequencing::default();
for x in text.split(",") {
for x in text.split(',') {
let x = x.trim();
if let Some(pr) = get_route_id(rss.clone(), true, false)(x) {
preferred_route = Some(pr)
@@ -179,7 +179,7 @@ fn get_safety_selection(routing_table: RoutingTable) -> impl Fn(&str) -> Option<
fn get_node_ref_modifiers(mut node_ref: NodeRef) -> impl FnOnce(&str) -> Option<NodeRef> {
move |text| {
for m in text.split("/") {
for m in text.split('/') {
if let Some(pt) = get_protocol_type(m) {
node_ref.merge_filter(NodeRefFilter::new().with_protocol_type(pt));
} else if let Some(at) = get_address_type(m) {
@@ -207,7 +207,7 @@ fn get_destination(
} else {
(text.as_str(), None)
};
if text.len() == 0 {
if text.is_empty() {
return None;
}
if &text[0..1] == "#" {
@@ -225,7 +225,7 @@ fn get_destination(
} else {
let mut dc = DEBUG_CACHE.lock();
let n = get_number(text)?;
let prid = dc.imported_routes.get(n)?.clone();
let prid = *dc.imported_routes.get(n)?;
let Some(private_route) = rss.best_remote_private_route(&prid) else {
// Remove imported route
dc.imported_routes.remove(n);
@@ -312,7 +312,7 @@ fn get_dht_key(
} else {
(text, None)
};
if text.len() == 0 {
if text.is_empty() {
return None;
}
@@ -528,13 +528,13 @@ pub fn print_data(data: &[u8], truncate_len: Option<usize>) -> String {
let (data, truncated) = if truncate_len.is_some() && data.len() > truncate_len.unwrap() {
(&data[0..64], true)
} else {
(&data[..], false)
(data, false)
};
let strdata = if printable {
format!("{}", String::from_utf8_lossy(&data).to_string())
String::from_utf8_lossy(data).to_string()
} else {
let sw = shell_words::quote(&String::from_utf8_lossy(&data).to_string()).to_string();
let sw = shell_words::quote(String::from_utf8_lossy(data).as_ref()).to_string();
let h = hex::encode(data);
if h.len() < sw.len() {
h
@@ -1019,8 +1019,8 @@ impl VeilidAPI {
let netman = self.network_manager()?;
let rpc = netman.rpc_processor();
let (call_id, data) = if args.starts_with("#") {
let (arg, rest) = args[1..].split_once(' ').unwrap_or((&args, ""));
let (call_id, data) = if let Some(stripped_args) = args.strip_prefix('#') {
let (arg, rest) = stripped_args.split_once(' ').unwrap_or((&args, ""));
let call_id =
OperationId::new(u64::from_str_radix(arg, 16).map_err(VeilidAPIError::generic)?);
let rest = rest.trim_start().to_owned();
@@ -1097,7 +1097,7 @@ impl VeilidAPI {
&[],
) {
Ok(Some(v)) => format!("{}", v),
Ok(None) => format!("<unavailable>"),
Ok(None) => "<unavailable>".to_string(),
Err(e) => {
format!("Route allocation failed: {}", e)
}
@@ -1270,7 +1270,7 @@ impl VeilidAPI {
let out = format!("Private route #{} imported: {}", n, route_id);
dc.imported_routes.push(route_id);
return Ok(out);
Ok(out)
}
async fn debug_route_test(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1298,7 +1298,7 @@ impl VeilidAPI {
"FAILED".to_owned()
};
return Ok(out);
Ok(out)
}
async fn debug_route(&self, args: String) -> VeilidAPIResult<String> {
@@ -1334,18 +1334,18 @@ impl VeilidAPI {
let scope = get_debug_argument_at(&args, 1, "debug_record_list", "scope", get_string)?;
let out = match scope.as_str() {
"local" => {
let mut out = format!("Local Records:\n");
let mut out = "Local Records:\n".to_string();
out += &storage_manager.debug_local_records().await;
out
}
"remote" => {
let mut out = format!("Remote Records:\n");
let mut out = "Remote Records:\n".to_string();
out += &storage_manager.debug_remote_records().await;
out
}
_ => "Invalid scope\n".to_owned(),
};
return Ok(out);
Ok(out)
}
async fn debug_record_purge(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1359,7 +1359,7 @@ impl VeilidAPI {
"remote" => storage_manager.purge_remote_records(bytes).await,
_ => "Invalid scope\n".to_owned(),
};
return Ok(out);
Ok(out)
}
async fn debug_record_create(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1397,11 +1397,10 @@ impl VeilidAPI {
// Get routing context with optional privacy
let rc = self.routing_context();
let rc = if let Some(ss) = ss {
let rcp = match rc.with_custom_privacy(ss) {
match rc.with_custom_privacy(ss) {
Err(e) => return Ok(format!("Can't use safety selection: {}", e)),
Ok(v) => v,
};
rcp
}
} else {
rc
};
@@ -1416,7 +1415,7 @@ impl VeilidAPI {
Ok(v) => v,
};
debug!("DHT Record Created:\n{:#?}", record);
return Ok(format!("{:?}", record));
Ok(format!("{:?}", record))
}
async fn debug_record_get(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1456,11 +1455,10 @@ impl VeilidAPI {
// Get routing context with optional privacy
let rc = self.routing_context();
let rc = if let Some(ss) = ss {
let rcp = match rc.with_custom_privacy(ss) {
match rc.with_custom_privacy(ss) {
Err(e) => return Ok(format!("Can't use safety selection: {}", e)),
Ok(v) => v,
};
rcp
}
} else {
rc
};
@@ -1497,7 +1495,7 @@ impl VeilidAPI {
Err(e) => return Ok(format!("Can't close DHT record: {}", e)),
Ok(v) => v,
};
return Ok(out);
Ok(out)
}
async fn debug_record_set(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1518,11 +1516,10 @@ impl VeilidAPI {
// Get routing context with optional privacy
let rc = self.routing_context();
let rc = if let Some(ss) = ss {
let rcp = match rc.with_custom_privacy(ss) {
match rc.with_custom_privacy(ss) {
Err(e) => return Ok(format!("Can't use safety selection: {}", e)),
Ok(v) => v,
};
rcp
}
} else {
rc
};
@@ -1556,7 +1553,7 @@ impl VeilidAPI {
Err(e) => return Ok(format!("Can't close DHT record: {}", e)),
Ok(v) => v,
};
return Ok(out);
Ok(out)
}
async fn debug_record_delete(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1568,7 +1565,7 @@ impl VeilidAPI {
Err(e) => return Ok(format!("Can't delete DHT record: {}", e)),
Ok(v) => v,
};
Ok(format!("DHT record deleted"))
Ok("DHT record deleted".to_string())
}
async fn debug_record_info(&self, args: Vec<String>) -> VeilidAPIResult<String> {
@@ -1595,7 +1592,7 @@ impl VeilidAPI {
let ri = storage_manager.debug_remote_record_info(key).await;
format!("Local Info:\n{}\n\nRemote Info:\n{}\n", li, ri)
};
return Ok(out);
Ok(out)
}
async fn debug_record(&self, args: String) -> VeilidAPIResult<String> {
@@ -1629,7 +1626,7 @@ impl VeilidAPI {
let address_filter = network_manager.address_filter();
let out = format!("Address Filter Punishments:\n{:#?}", address_filter);
return Ok(out);
Ok(out)
}
async fn debug_punish(&self, args: String) -> VeilidAPIResult<String> {

View File

@@ -140,7 +140,7 @@ pub enum ResponseOp {
},
GetState {
#[serde(flatten)]
result: ApiResult<VeilidState>,
result: ApiResult<Box<VeilidState>>,
},
Attach {
#[serde(flatten)]
@@ -175,7 +175,7 @@ pub enum ResponseOp {
NewRoutingContext {
value: u32,
},
RoutingContext(RoutingContextResponse),
RoutingContext(Box<RoutingContextResponse>),
// TableDb
OpenTableDb {
#[serde(flatten)]

View File

@@ -87,10 +87,10 @@ impl JsonRequestProcessor {
let Some(routing_context) = inner.routing_contexts.get(&rc_id).cloned() else {
return Err(Response {
id,
op: ResponseOp::RoutingContext(RoutingContextResponse {
op: ResponseOp::RoutingContext(Box::new(RoutingContextResponse {
rc_id,
rc_op: RoutingContextResponseOp::InvalidId
})
rc_op: RoutingContextResponseOp::InvalidId,
})),
});
};
Ok(routing_context)
@@ -100,7 +100,7 @@ impl JsonRequestProcessor {
if inner.routing_contexts.remove(&id).is_none() {
return 0;
}
return 1;
1
}
// TableDB
@@ -120,8 +120,8 @@ impl JsonRequestProcessor {
id,
op: ResponseOp::TableDb(TableDbResponse {
db_id,
db_op: TableDbResponseOp::InvalidId
})
db_op: TableDbResponseOp::InvalidId,
}),
});
};
Ok(table_db)
@@ -131,7 +131,7 @@ impl JsonRequestProcessor {
if inner.table_dbs.remove(&id).is_none() {
return 0;
}
return 1;
1
}
// TableDBTransaction
@@ -155,8 +155,8 @@ impl JsonRequestProcessor {
id,
op: ResponseOp::TableDbTransaction(TableDbTransactionResponse {
tx_id,
tx_op: TableDbTransactionResponseOp::InvalidId
})
tx_op: TableDbTransactionResponseOp::InvalidId,
}),
});
};
Ok(table_db_transaction)
@@ -166,7 +166,7 @@ impl JsonRequestProcessor {
if inner.table_db_transactions.remove(&id).is_none() {
return 0;
}
return 1;
1
}
// CryptoSystem
@@ -186,8 +186,8 @@ impl JsonRequestProcessor {
id,
op: ResponseOp::CryptoSystem(CryptoSystemResponse {
cs_id,
cs_op: CryptoSystemResponseOp::InvalidId
})
cs_op: CryptoSystemResponseOp::InvalidId,
}),
});
};
Ok(crypto_system)
@@ -197,7 +197,7 @@ impl JsonRequestProcessor {
if inner.crypto_systems.remove(&id).is_none() {
return 0;
}
return 1;
1
}
// Target
@@ -280,13 +280,21 @@ impl JsonRequestProcessor {
RoutingContextRequestOp::CreateDhtRecord { schema, kind } => {
RoutingContextResponseOp::CreateDhtRecord {
result: to_json_api_result(
routing_context.create_dht_record(schema, kind).await,
routing_context
.create_dht_record(schema, kind)
.await
.map(Box::new),
),
}
}
RoutingContextRequestOp::OpenDhtRecord { key, writer } => {
RoutingContextResponseOp::OpenDhtRecord {
result: to_json_api_result(routing_context.open_dht_record(key, writer).await),
result: to_json_api_result(
routing_context
.open_dht_record(key, writer)
.await
.map(Box::new),
),
}
}
RoutingContextRequestOp::CloseDhtRecord { key } => {
@@ -508,7 +516,7 @@ impl JsonRequestProcessor {
&body,
&nonce,
&shared_secret,
associated_data.as_ref().map(|ad| ad.as_slice()),
associated_data.as_deref(),
)),
},
CryptoSystemRequestOp::EncryptAead {
@@ -521,7 +529,7 @@ impl JsonRequestProcessor {
&body,
&nonce,
&shared_secret,
associated_data.as_ref().map(|ad| ad.as_slice()),
associated_data.as_deref(),
)),
},
CryptoSystemRequestOp::CryptNoAuth {
@@ -548,7 +556,7 @@ impl JsonRequestProcessor {
))),
},
RequestOp::GetState => ResponseOp::GetState {
result: to_json_api_result(self.api.get_state().await),
result: to_json_api_result(self.api.get_state().await.map(Box::new)),
},
RequestOp::Attach => ResponseOp::Attach {
result: to_json_api_result(self.api.attach().await),
@@ -596,10 +604,10 @@ impl JsonRequestProcessor {
Ok(v) => v,
Err(e) => return e,
};
ResponseOp::RoutingContext(
ResponseOp::RoutingContext(Box::new(
self.process_routing_context_request(routing_context, rcr)
.await,
)
))
}
RequestOp::OpenTableDb { name, column_count } => {
let table_store = match self.api.table_store() {

View File

@@ -110,11 +110,11 @@ pub enum RoutingContextResponseOp {
},
CreateDhtRecord {
#[serde(flatten)]
result: ApiResult<DHTRecordDescriptor>,
result: ApiResult<Box<DHTRecordDescriptor>>,
},
OpenDhtRecord {
#[serde(flatten)]
result: ApiResult<DHTRecordDescriptor>,
result: ApiResult<Box<DHTRecordDescriptor>>,
},
CloseDhtRecord {
#[serde(flatten)]

View File

@@ -19,5 +19,5 @@ pub fn decompress_size_prepended(
));
}
}
Ok(block::decompress(input, uncompressed_size).map_err(VeilidAPIError::generic)?)
block::decompress(input, uncompressed_size).map_err(VeilidAPIError::generic)
}

View File

@@ -93,7 +93,7 @@ pub mod as_human_base64 {
let base64 = String::deserialize(d)?;
BASE64URL_NOPAD
.decode(base64.as_bytes())
.map_err(|e| serde::de::Error::custom(e))
.map_err(serde::de::Error::custom)
} else {
Vec::<u8>::deserialize(d)
}
@@ -106,7 +106,7 @@ pub mod as_human_opt_base64 {
pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
let base64 = v.as_ref().map(|x| BASE64URL_NOPAD.encode(&x));
let base64 = v.as_ref().map(|x| BASE64URL_NOPAD.encode(x));
Option::<String>::serialize(&base64, s)
} else {
Option::<Vec<u8>>::serialize(v, s)
@@ -120,7 +120,7 @@ pub mod as_human_opt_base64 {
.map(|x| {
BASE64URL_NOPAD
.decode(x.as_bytes())
.map_err(|e| serde::de::Error::custom(e))
.map_err(serde::de::Error::custom)
})
.transpose()
} else {

View File

@@ -43,21 +43,21 @@ pub async fn test_fourcc() {
pub async fn test_sequencing() {
let orig = Sequencing::PreferOrdered;
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
let copy = deserialize_json(&serialize_json(orig)).unwrap();
assert_eq!(orig, copy);
}
pub async fn test_stability() {
let orig = Stability::Reliable;
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
let copy = deserialize_json(&serialize_json(orig)).unwrap();
assert_eq!(orig, copy);
}
pub async fn test_safetyselection() {
let orig = SafetySelection::Unsafe(Sequencing::EnsureOrdered);
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
let copy = deserialize_json(&serialize_json(orig)).unwrap();
assert_eq!(orig, copy);
}
@@ -178,7 +178,7 @@ pub async fn test_partialtunnel() {
pub async fn test_veilidloglevel() {
let orig = VeilidLogLevel::Info;
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
let copy = deserialize_json(&serialize_json(orig)).unwrap();
assert_eq!(orig, copy);
}
@@ -198,7 +198,7 @@ pub async fn test_veilidlog() {
pub async fn test_attachmentstate() {
let orig = AttachmentState::FullyAttached;
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
let copy = deserialize_json(&serialize_json(orig)).unwrap();
assert_eq!(orig, copy);
}
@@ -260,7 +260,7 @@ pub async fn test_veilidvaluechange() {
}
pub async fn test_veilidupdate() {
let orig = VeilidUpdate::ValueChange(fix_veilidvaluechange());
let orig = VeilidUpdate::ValueChange(Box::new(fix_veilidvaluechange()));
let copy = deserialize_json(&serialize_json(&orig)).unwrap();
assert_eq!(orig, copy);
@@ -268,20 +268,20 @@ pub async fn test_veilidupdate() {
pub async fn test_veilidstate() {
let orig = VeilidState {
attachment: VeilidStateAttachment {
attachment: Box::new(VeilidStateAttachment {
state: AttachmentState::OverAttached,
public_internet_ready: true,
local_network_ready: false,
},
network: VeilidStateNetwork {
}),
network: Box::new(VeilidStateNetwork {
started: true,
bps_down: AlignedU64::from(14_400),
bps_up: AlignedU64::from(1200),
peers: vec![fix_peertabledata()],
},
config: VeilidStateConfig {
}),
config: Box::new(VeilidStateConfig {
config: fix_veilidconfiginner(),
},
}),
};
let copy = deserialize_json(&serialize_json(&orig)).unwrap();

View File

@@ -61,7 +61,7 @@ impl TryFrom<&[u8]> for DHTSchemaDFLT {
if b.len() != Self::FIXED_SIZE {
apibail_generic!("invalid size");
}
if &b[0..4] != &Self::FCC {
if b[0..4] != Self::FCC {
apibail_generic!("wrong fourcc");
}

View File

@@ -101,7 +101,7 @@ impl TryFrom<&[u8]> for DHTSchemaSMPL {
if b.len() < Self::FIXED_SIZE {
apibail_generic!("invalid size");
}
if &b[0..4] != &Self::FCC {
if b[0..4] != Self::FCC {
apibail_generic!("wrong fourcc");
}
if (b.len() - Self::FIXED_SIZE) % (PUBLIC_KEY_LENGTH + 2) != 0 {

View File

@@ -32,10 +32,13 @@ impl FromStr for ValueSubkeyRangeSet {
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut data = RangeSetBlaze::<ValueSubkey>::new();
for r in value.split(",") {
for r in value.split(',') {
let r = r.trim();
let Some((ss, es)) = r.split_once("..=") else {
return Err(VeilidAPIError::parse_error("can not parse ValueSubkeyRangeSet", r));
return Err(VeilidAPIError::parse_error(
"can not parse ValueSubkeyRangeSet",
r,
));
};
let sn = ValueSubkey::from_str(ss)
.map_err(|e| VeilidAPIError::parse_error("could not parse ValueSubkey", e))?;

View File

@@ -108,14 +108,14 @@ pub struct VeilidValueChange {
#[cfg_attr(target_arch = "wasm32", derive(Tsify), tsify(into_wasm_abi))]
#[serde(tag = "kind")]
pub enum VeilidUpdate {
Log(VeilidLog),
AppMessage(VeilidAppMessage),
AppCall(VeilidAppCall),
Attachment(VeilidStateAttachment),
Network(VeilidStateNetwork),
Config(VeilidStateConfig),
RouteChange(VeilidRouteChange),
ValueChange(VeilidValueChange),
Log(Box<VeilidLog>),
AppMessage(Box<VeilidAppMessage>),
AppCall(Box<VeilidAppCall>),
Attachment(Box<VeilidStateAttachment>),
Network(Box<VeilidStateNetwork>),
Config(Box<VeilidStateConfig>),
RouteChange(Box<VeilidRouteChange>),
ValueChange(Box<VeilidValueChange>),
Shutdown,
}
from_impl_to_jsvalue!(VeilidUpdate);
@@ -123,8 +123,8 @@ from_impl_to_jsvalue!(VeilidUpdate);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(target_arch = "wasm32", derive(Tsify), tsify(into_wasm_abi))]
pub struct VeilidState {
pub attachment: VeilidStateAttachment,
pub network: VeilidStateNetwork,
pub config: VeilidStateConfig,
pub attachment: Box<VeilidStateAttachment>,
pub network: Box<VeilidStateNetwork>,
pub config: Box<VeilidStateConfig>,
}
from_impl_to_jsvalue!(VeilidState);