From b234914d8bc94a530a386982139ccb4d1d2357f4 Mon Sep 17 00:00:00 2001 From: nm17 Date: Sun, 2 Jun 2024 01:01:37 +0400 Subject: [PATCH] style: format with clippy --- src/ingest_protocol/error.rs | 9 ++++---- src/ingest_protocol/packet_types.rs | 10 ++++----- src/ingest_protocol/parser.rs | 3 +-- src/utils/hifitime_serde.rs | 8 +++---- src/utils/mod.rs | 11 +++++----- src/web_server/app_error.rs | 12 +++++------ src/web_server/mod.rs | 6 ++---- src/web_server/old_app_api/mod.rs | 5 +---- src/web_server/old_device_sensor_api/mod.rs | 5 ----- .../old_device_sensor_api/qs_parser.rs | 21 ++++++++++--------- 10 files changed, 38 insertions(+), 52 deletions(-) diff --git a/src/ingest_protocol/error.rs b/src/ingest_protocol/error.rs index b7e1d26..6d58732 100644 --- a/src/ingest_protocol/error.rs +++ b/src/ingest_protocol/error.rs @@ -1,20 +1,19 @@ - use nom::error::VerboseError; -use std::fmt::{Debug}; +use std::fmt::Debug; use std::num::ParseFloatError; use thiserror::Error as ThisError; +#[allow(dead_code)] #[derive(Debug, ThisError)] pub enum Error { #[error("Nom error: {0}")] - NomError(#[from] nom::Err>), + Nom(#[from] nom::Err>), #[error("Failed to parse a timestamp")] TimestampParseError(ParseFloatError), #[error("Unknown unit")] UnknownUnit(I), - #[error("Failed to parse a number")] - DecimalParseError(#[from] rust_decimal::Error), + DecimalParsing(#[from] rust_decimal::Error), } diff --git a/src/ingest_protocol/packet_types.rs b/src/ingest_protocol/packet_types.rs index 48e4d25..4898e5f 100644 --- a/src/ingest_protocol/packet_types.rs +++ b/src/ingest_protocol/packet_types.rs @@ -19,7 +19,7 @@ use serde::{Deserialize, Serialize}; use serde_with::serde_as; use ufmt::uwrite; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; /// Данные с одного датчика. @@ -118,8 +118,8 @@ impl NMDeviceDataPacket { let device_exists: Option = redis.hget(key.as_str(), "exists").await?; - if !device_exists.is_some_and(|v| v == true) { - return Err(AppError::DeviceNotFound(hex::encode(&self.mac))); + if !device_exists.is_some_and(|v| v) { + return Err(AppError::DeviceNotFound(hex::encode(self.mac))); } // devices_{device_id}_{tai_timestamp}_{sensor_id} @@ -150,7 +150,7 @@ impl NMDeviceDataPacket { } } - return Ok(()); + Ok(()) } } @@ -165,6 +165,6 @@ impl NMJsonPacket { device.save_to_db(redis).await?; } - return Ok(()); + Ok(()) } } diff --git a/src/ingest_protocol/parser.rs b/src/ingest_protocol/parser.rs index 81d557c..085cf1f 100644 --- a/src/ingest_protocol/parser.rs +++ b/src/ingest_protocol/parser.rs @@ -6,7 +6,6 @@ use nom::character::complete::hex_digit1; use std::str::FromStr; use crate::ingest_protocol::error::Error; -use crate::ingest_protocol::error::Error::TimestampParseError; use crate::ingest_protocol::{NMDeviceDataPacket, SensorValue}; use nom::combinator::{map_parser, opt}; use nom::error::context; @@ -85,7 +84,7 @@ pub fn parse_packet_body<'a>( let sensor_time = match sensor_time { Some(v) => Some(Epoch::from_unix_seconds( - v.parse().map_err(TimestampParseError)?, + v.parse().map_err(Error::TimestampParseError)?, )), None => None, }; diff --git a/src/utils/hifitime_serde.rs b/src/utils/hifitime_serde.rs index 8d33611..07119de 100644 --- a/src/utils/hifitime_serde.rs +++ b/src/utils/hifitime_serde.rs @@ -43,14 +43,14 @@ impl<'de> Deserialize<'de> for EpochUTC { where E: de::Error, { - return Ok(Epoch::from_unix_seconds(v as f64).into()); + Ok(Epoch::from_unix_seconds(v as f64).into()) } fn visit_f64(self, v: f64) -> Result where E: de::Error, { - return Ok(Epoch::from_unix_seconds(v).into()); + Ok(Epoch::from_unix_seconds(v).into()) } fn visit_str(self, value: &str) -> Result @@ -65,9 +65,9 @@ impl<'de> Deserialize<'de> for EpochUTC { ) as f64) .into()); } - return Ok( + Ok( Epoch::from_unix_seconds(value.parse().map_err(de::Error::custom)?).into(), - ); + ) } } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 9a91b6b..7edee90 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,7 +1,6 @@ //! Глобальный модуль для вспомогательных типов и утилит. //! - mod hifitime_serde; use phf::phf_map; @@ -10,11 +9,11 @@ use std::borrow::Cow; pub use hifitime_serde::EpochUTC; - /// Поддерживаемые типы. /// /// TODO: Решить необходимо ли к данным прикреплять единицы измерения. /// TODO: Сейчас вообще сомнительно оставлять ли это или нет. +#[allow(dead_code)] #[derive(Debug, Clone, Hash, PartialEq, Eq)] #[repr(u64)] pub enum SupportedUnit { @@ -35,8 +34,8 @@ pub enum SupportedUnit { impl Serialize for SupportedUnit { fn serialize(&self, serializer: S) -> Result - where - S: Serializer, + where + S: Serializer, { serializer.serialize_str(match self { SupportedUnit::Celsius => "C", @@ -58,8 +57,8 @@ impl Serialize for SupportedUnit { impl<'de> Deserialize<'de> for SupportedUnit { fn deserialize<'a, D>(deserializer: D) -> Result - where - D: Deserializer<'de>, + where + D: Deserializer<'de>, { let color_str = Cow::<'a, str>::deserialize(deserializer)?; match STR_TO_UNITS.get(color_str.as_ref()) { diff --git a/src/web_server/app_error.rs b/src/web_server/app_error.rs index 38bcad5..ebe4a28 100644 --- a/src/web_server/app_error.rs +++ b/src/web_server/app_error.rs @@ -13,7 +13,6 @@ use crate::web_server::old_device_sensor_api::qs_parser::QSParserError; use rust_decimal::Decimal; use serde_json::json; - /// Главный объект ошибки [std::error::Error] для всего Web API. /// /// В целом, все Result у Web сервера должны использовать этот Error. @@ -50,7 +49,7 @@ pub enum AppError { }, #[display(fmt = "IDK")] - DeviceNotFound(String) + DeviceNotFound(String), } impl web::error::WebResponseError for AppError { @@ -64,7 +63,7 @@ impl web::error::WebResponseError for AppError { AppError::ApiKeyInvalid { .. } => StatusCode::BAD_REQUEST, AppError::UnknownBody { .. } => StatusCode::BAD_REQUEST, AppError::QSError(..) => StatusCode::BAD_REQUEST, - AppError::DeviceNotFound(..) => StatusCode::BAD_REQUEST + AppError::DeviceNotFound(..) => StatusCode::BAD_REQUEST, } } @@ -118,16 +117,15 @@ impl web::error::WebResponseError for AppError { AppError::ApiKeyInvalid { reason } => { insert_header!(headers, "X-Error-Description", *reason); } - AppError::QSError(err) => match err { - QSParserError::ParsingError(desc) => { + AppError::QSError(err) => { + if let QSParserError::Parsing(desc) = err { insert_header!( headers, "X-Error-Description", desc.escape_default().to_string() ); } - _ => {} - }, + } _ => {} }; diff --git a/src/web_server/mod.rs b/src/web_server/mod.rs index 8e591d0..e8c4961 100644 --- a/src/web_server/mod.rs +++ b/src/web_server/mod.rs @@ -5,11 +5,9 @@ //! //! TODO: Начать работу над TCP/UDP и MQTT сервером -use old_app_api::old_api_handler; use fred::bytes_utils::Str; use fred::prelude::*; - - +use old_app_api::old_api_handler; pub mod app_error; pub mod old_app_api; @@ -32,7 +30,7 @@ pub async fn server_main() { let client = RedisClient::new(config, Some(perf), Some(policy)); // connect to the server, returning a handle to the task that drives the connection - let _ = client.connect(); + client.connect().await.unwrap().unwrap(); client.wait_for_connect().await.unwrap(); let asd: Str = client.ping().await.unwrap(); diff --git a/src/web_server/old_app_api/mod.rs b/src/web_server/old_app_api/mod.rs index 6abc3f3..fb24cc1 100644 --- a/src/web_server/old_app_api/mod.rs +++ b/src/web_server/old_app_api/mod.rs @@ -33,10 +33,7 @@ pub async fn old_api_handler( let mandatory_params: MandatoryParams<'_> = serde_json::from_slice(body_bytes)?; // TODO: Simd-JSON // Ignore clippy singlematch - match mandatory_params.cmd.as_ref() { - "version" => return version((), &app_state).await, - _ => {} - } + if mandatory_params.cmd.as_ref() == "version" { return version((), &app_state).await } is_api_key_valid(&app_state.redis_client, mandatory_params.api_key.as_ref()).await?; diff --git a/src/web_server/old_device_sensor_api/mod.rs b/src/web_server/old_device_sensor_api/mod.rs index f591fb7..ab8f1e9 100644 --- a/src/web_server/old_device_sensor_api/mod.rs +++ b/src/web_server/old_device_sensor_api/mod.rs @@ -4,19 +4,14 @@ pub mod qs_parser; use crate::ingest_protocol::{NMDeviceDataPacket, NMJsonPacket}; use crate::web_server::app_error::AppError; -use fred::bytes_utils::Str; -use fred::prelude::*; -use hifitime::Epoch; use ntex::http::{HttpMessage, StatusCode}; use ntex::util::Bytes; use ntex::web::types::State; use ntex::{http, web}; use qs_parser::QSParserError; use thiserror::Error; -use ufmt::uwrite; -use futures_util::stream::StreamExt; use super::NMAppState; diff --git a/src/web_server/old_device_sensor_api/qs_parser.rs b/src/web_server/old_device_sensor_api/qs_parser.rs index 193bee3..67208b9 100644 --- a/src/web_server/old_device_sensor_api/qs_parser.rs +++ b/src/web_server/old_device_sensor_api/qs_parser.rs @@ -11,18 +11,19 @@ use std::sync::Arc; use thiserror::Error; /// В иделае было бы хорошо сделать всё как у [serde_json::Error], но это слишком большая морока +#[allow(dead_code)] #[derive(Error, Clone, Debug)] pub enum QSParserError { #[error("asd")] - SerdeQSError(#[from] Arc), + SerdeQS(#[from] Arc), #[error("asd")] - ParsingError(String), + Parsing(String), #[error("asd")] - FloatParseError(#[from] ParseFloatError), + FloatParse(#[from] ParseFloatError), #[error("failed to parse into decimal")] - DecimalParseError(#[from] rust_decimal::Error), + DecimalParse(#[from] rust_decimal::Error), #[error("asd")] NoMAC, @@ -30,13 +31,13 @@ pub enum QSParserError { impl From> for QSParserError { fn from(value: Error<&str>) -> Self { - QSParserError::ParsingError(format!("{:?}", value)) + QSParserError::Parsing(format!("{:?}", value)) } } impl From for QSParserError { fn from(value: serde_qs::Error) -> Self { - QSParserError::SerdeQSError(Arc::new(value)) + QSParserError::SerdeQS(Arc::new(value)) } } @@ -68,22 +69,22 @@ pub fn parse_decimal_if_exists( parsed: &mut HashMap, key: &str, ) -> Result, QSParserError> { - return if let Some(unwrapped_value) = parsed.remove(key) { + if let Some(unwrapped_value) = parsed.remove(key) { Ok(Some(Decimal::from_str(unwrapped_value.as_str())?)) } else { Ok(None) - }; + } } pub fn parse_epoch_if_exists( parsed: &mut HashMap, key: &str, ) -> Result, QSParserError> { - return if let Some(unwrapped_value) = parsed.remove(key) { + if let Some(unwrapped_value) = parsed.remove(key) { Ok(Some(Epoch::from_unix_seconds(unwrapped_value.parse()?))) } else { Ok(None) - }; + } } pub async fn parse_nm_qs_format(input: &str) -> Result {