From a65cf9630420c40fccf3ccabb5fdcef4bce9a209 Mon Sep 17 00:00:00 2001 From: Daniel Egger Date: Fri, 6 Sep 2024 17:34:26 +0200 Subject: [PATCH] Apply a number of clippy automagic fixes Signed-off-by: Daniel Egger --- src/main.rs | 161 +++++++++---------- src/usp_builder/add.rs | 42 ++--- src/usp_builder/delete.rs | 20 +-- src/usp_builder/deregister.rs | 20 +-- src/usp_builder/error.rs | 6 +- src/usp_builder/get.rs | 24 +-- src/usp_builder/getinstances.rs | 24 +-- src/usp_builder/getsupporteddm.rs | 108 ++++++------- src/usp_builder/getsupportedprotocol.rs | 4 +- src/usp_builder/msg.rs | 14 +- src/usp_builder/notify.rs | 32 ++-- src/usp_builder/operate.rs | 22 +-- src/usp_builder/record.rs | 36 ++--- src/usp_builder/register.rs | 18 +-- src/usp_builder/set.rs | 46 +++--- src/usp_decoder.rs | 16 +- src/usp_errors.rs | 2 +- src/usp_generator.rs | 198 ++++++++++++------------ src/usp_json.rs | 52 +++---- src/usp_record.rs | 50 +++--- src/usp_types.rs | 22 +-- 21 files changed, 454 insertions(+), 463 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6b6b27c..b564304 100644 --- a/src/main.rs +++ b/src/main.rs @@ -218,7 +218,7 @@ enum RuspAction { }, } -/// Parse a JSON object into a Rust HashMap +/// Parse a JSON object into a Rust `HashMap` fn parse_key_val_json(s: &str) -> Result, String> { serde_json::from_str::>(s).map_err(|e| e.to_string()) } @@ -238,7 +238,7 @@ impl Default for OperateResponse { #[derive(Parser, PartialEq, Eq)] enum NotifyType { - /// USP OnBoardRequest notification + /// USP `OnBoardRequest` notification OnBoardRequest { /// The OUI associated with the manufacturer of the device oui: String, @@ -252,7 +252,7 @@ enum NotifyType { /// A comma separated list of supported USP versions agent_supported_protocol_versions: String, }, - /// USP ValueChange notification + /// USP `ValueChange` notification ValueChange { /// The path of the changed parameter param_path: String, @@ -269,21 +269,21 @@ enum NotifyType { #[arg(value_parser = parse_key_val_json)] params: HashMap, }, - /// USP ObjectCreation notification + /// USP `ObjectCreation` notification ObjectCreation { /// The path of the created object obj_path: String, - /// A stringified JSON object containing the unique_keys and values of the created Object + /// A stringified JSON object containing the `unique_keys` and values of the created Object #[arg(value_parser = parse_key_val_json)] unique_keys: HashMap, }, - /// USP ObjectDeletion notification + /// USP `ObjectDeletion` notification ObjectDeletion { /// The path of the deleted object obj_path: String, }, - /// USP OperationComplete notification + /// USP `OperationComplete` notification OperationComplete { /// The path of the operation object obj_path: String, @@ -307,7 +307,7 @@ impl TryFrom for RuspNotifyType { product_class, serial_number, agent_supported_protocol_versions, - } => RuspNotifyType::OnBoardRequest { + } => Self::OnBoardRequest { oui, product_class, serial_number, @@ -316,7 +316,7 @@ impl TryFrom for RuspNotifyType { NotifyType::ValueChange { param_path, param_value, - } => RuspNotifyType::ValueChange { + } => Self::ValueChange { param_path, param_value, }, @@ -324,7 +324,7 @@ impl TryFrom for RuspNotifyType { obj_path, event_name, params, - } => RuspNotifyType::Event { + } => Self::Event { obj_path, event_name, params, @@ -332,17 +332,17 @@ impl TryFrom for RuspNotifyType { NotifyType::ObjectCreation { obj_path, unique_keys, - } => RuspNotifyType::ObjectCreation { + } => Self::ObjectCreation { obj_path, unique_keys, }, - NotifyType::ObjectDeletion { obj_path } => RuspNotifyType::ObjectDeletion { obj_path }, + NotifyType::ObjectDeletion { obj_path } => Self::ObjectDeletion { obj_path }, NotifyType::OperationComplete { obj_path, command_name, command_key, operation_resp, - } => RuspNotifyType::OperationComplete { + } => Self::OperationComplete { obj_path, command_name, command_key, @@ -402,14 +402,14 @@ enum MsgType { #[arg(long = "max_depth")] max_depth: Option, }, - /// Generate an USP GetResp response message + /// Generate an USP `GetResp` response message #[command(name = "GetResp")] USPGetResp { - /// A JSON array of Strings resembling the result data for the GetResp operation + /// A JSON array of Strings resembling the result data for the `GetResp` operation #[arg(num_args(1..))] result: Vec, }, - /// Generate an USP GetInstances request message + /// Generate an USP `GetInstances` request message #[command(name = "GetInstances")] USPGetInstances { /// Only return the first level of recursive structures? @@ -421,7 +421,7 @@ enum MsgType { #[arg(num_args(1..))] obj_paths: Vec, }, - /// Generate an USP GetSupportedDM request message + /// Generate an USP `GetSupportedDM` request message #[command(name = "GetSupportedDM")] USPGetSupportedDM { /// Only return the first level of recursive structures? @@ -445,7 +445,7 @@ enum MsgType { #[arg(num_args(1..))] paths: Vec, }, - /// Generate an USP GetSupportedProtocol request message + /// Generate an USP `GetSupportedProtocol` request message #[command(name = "GetSupportedProtocol")] USPGetSupportedProtocol { /// Controller Supported Protocol Version @@ -563,7 +563,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { } => { let args = args.join(" "); let v = serde_json::from_str::)>>(&args) - .with_context(|| format!("Expected JSON data in the form \"[[, [[, , ], ...]], ...]\", got {}", args))?; + .with_context(|| format!("Expected JSON data in the form \"[[, [[, , ], ...]], ...]\", got {args}"))?; let builder = usp_builder::AddBuilder::new().with_allow_partial(allow_partial); @@ -579,7 +579,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { } => { let obj_paths = obj_paths.join(" "); let obj_paths = serde_json::from_str::>(&obj_paths) - .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {}", obj_paths))?; + .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {obj_paths}"))?; serialize_into_vec(&usp_builder::DeleteBuilder::new().with_allow_partial(allow_partial).with_obj_paths(obj_paths).build()?) } MsgType::USPError { code, message } => { @@ -589,7 +589,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { MsgType::USPGet { paths, max_depth } => { let paths = paths.join(" "); let v = serde_json::from_str::>(&paths) - .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {}", paths))?; + .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {paths}"))?; serialize_into_vec(&usp_builder::GetBuilder::new().with_max_depth(max_depth.unwrap_or(0)).with_params(v).build()?) } MsgType::USPGetInstances { @@ -598,7 +598,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { } => { let obj_paths = obj_paths.join(" "); let v = serde_json::from_str::>(&obj_paths) - .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {}", obj_paths))?; + .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {obj_paths}"))?; serialize_into_vec(&usp_builder::GetInstancesBuilder::new().with_first_level_only(first_level_only).with_obj_paths(v).build()? )} MsgType::USPGetSupportedDM { @@ -610,7 +610,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { paths, } => { let v = serde_json::from_str::>(&paths.join(" ")) - .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {:?}", paths))?; + .with_context(|| format!("Expected JSON data in the form \"[, ...]\", got {paths:?}"))?; let msg = usp_builder::GetSupportedDMBuilder::new() .with_first_level_only(first_level_only) .with_return_commands(return_commands) @@ -631,17 +631,17 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { let getresp_json: Vec<(String, u32, String, Vec<(String, HashMap)>)> = serde_json::from_str(&result)?; let mut getrespb = usp_builder::GetRespBuilder::new(); - for req_path_result in getresp_json.into_iter() { + for req_path_result in getresp_json { let mut reqpathbuilder = usp_builder::GetReqPathResultBuilder::new(req_path_result.0); if req_path_result.1 != 0 { reqpathbuilder.err_code = req_path_result.1; } - for res_path_result in req_path_result.3.into_iter() { + for res_path_result in req_path_result.3 { let respathbuilder = usp_builder::ResolvedPathResultBuilder::new(res_path_result.0).with_result_params(res_path_result.1.into_iter().collect()); reqpathbuilder = reqpathbuilder.with_res_path_results(vec![respathbuilder]); } - getrespb = getrespb.with_req_path_results(vec![reqpathbuilder]) + getrespb = getrespb.with_req_path_results(vec![reqpathbuilder]); } serialize_into_vec(&getrespb.build()?) @@ -680,7 +680,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { let args = args.join(" "); let v = if !args.is_empty() { serde_json::from_str::>(&args) - .with_context(|| format!("Expected JSON data in the form \"[[, ], ...]\", got {}", args))? + .with_context(|| format!("Expected JSON data in the form \"[[, ], ...]\", got {args}"))? } else { Vec::new() }; @@ -692,7 +692,7 @@ fn encode_msg_body_buf(typ: MsgType) -> Result> { } => { let args = args.join(" "); let v = serde_json::from_str::)>>(&args) - .with_context(|| format!("Expected JSON data in the form \"[[, [[, , ], ...]], ...]\", got {}", args))?; + .with_context(|| format!("Expected JSON data in the form \"[[, [[, , ], ...]], ...]\", got {args}"))?; let msg = usp_builder::SetBuilder::new() .with_allow_partial(allow_partial) .with_update_objs(v.into_iter().map(|(path, par)| usp_builder::UpdateObjectBuilder::new(path.into()).with_param_settings(par)).collect()) @@ -714,7 +714,7 @@ fn write_c_array(mut out: W, buf: &[u8]) -> Result<()> where W: Write, { - fn check_printable(c: u8) -> bool { + const fn check_printable(c: u8) -> bool { match c as char { ' ' | '.' | '!' | '(' | ')' | '\'' | '"' | ',' | '*' | '[' | ']' | '=' | '<' | '>' | '-' | '_' => true, @@ -729,7 +729,7 @@ where for chunk in buf.chunks(CHUNK_LEN) { write!(out, " ")?; for i in chunk { - write!(out, "0x{:02x}, ", i)?; + write!(out, "0x{i:02x}, ")?; } for _ in chunk.len()..CHUNK_LEN { @@ -754,7 +754,7 @@ where } fn write_c_str(mut out: W, buf: &[u8]) -> Result<()> { - fn check_printable(c: u8) -> bool { + const fn check_printable(c: u8) -> bool { match c as char { ' ' | '.' | '!' | '(' | ')' | '\'' | ',' | '*' | '[' | ']' | '=' | '<' | '>' | '-' | '_' => true, @@ -768,7 +768,7 @@ fn write_c_str(mut out: W, buf: &[u8]) -> Result<()> { if check_printable(*i) { write!(out, "{}", char::from(*i))?; } else { - write!(out, "\\x{:02x}", i)?; + write!(out, "\\x{i:02x}")?; } } @@ -823,25 +823,22 @@ fn write_record( mut out: W, format: &OutputFormat, ) -> Result<()> { - match format { - OutputFormat::Json => { - writeln!( - out, - "{}", - serde_json::to_string_pretty(&record).context("Failed to serialize JSON")? - )?; - } - _ => { - use quick_protobuf::{message::MessageWrite, Writer}; - - let mut buf = Vec::new(); - let mut writer = Writer::new(&mut buf); - record - .write_message(&mut writer) - .context("Failed encoding USP Record")?; - - write_buf(buf, out, format)? - } + if format == &OutputFormat::Json { + writeln!( + out, + "{}", + serde_json::to_string_pretty(&record).context("Failed to serialize JSON")? + )?; + } else { + use quick_protobuf::{message::MessageWrite, Writer}; + + let mut buf = Vec::new(); + let mut writer = Writer::new(&mut buf); + record + .write_message(&mut writer) + .context("Failed encoding USP Record")?; + + write_buf(buf, out, format)?; } Ok(()) @@ -849,24 +846,21 @@ fn write_record( /// Write the given USP Msg Body to the output stream in the specified format fn write_body(msg: rusp::usp::Body, mut out: W, format: &OutputFormat) -> Result<()> { - match format { - OutputFormat::Json => { - writeln!( - out, - "{}", - serde_json::to_string_pretty(&msg).context("Failed to serialize JSON")? - )?; - } - _ => { - use quick_protobuf::{message::MessageWrite, Writer}; - - let mut buf = Vec::new(); - let mut writer = Writer::new(&mut buf); - msg.write_message(&mut writer) - .context("Failed encoding USP Msg Body")?; - - write_buf(buf, out, format)? - } + if format == &OutputFormat::Json { + writeln!( + out, + "{}", + serde_json::to_string_pretty(&msg).context("Failed to serialize JSON")? + )?; + } else { + use quick_protobuf::{message::MessageWrite, Writer}; + + let mut buf = Vec::new(); + let mut writer = Writer::new(&mut buf); + msg.write_message(&mut writer) + .context("Failed encoding USP Msg Body")?; + + write_buf(buf, out, format)?; } Ok(()) @@ -882,25 +876,22 @@ fn encode_msg_body(filename: Option, typ: MsgType, format: &OutputForma let body: rusp::usp::Body = deserialize_from_slice(&encoded_body).context("Failed trying to deserialise Msg body")?; - match format { - OutputFormat::Json => { - writeln!( - out, - "{}", - serde_json::to_string_pretty(&body).context("Failed to serialize JSON")? - )?; - } - _ => { - use quick_protobuf::message::MessageWrite; + if format == &OutputFormat::Json { + writeln!( + out, + "{}", + serde_json::to_string_pretty(&body).context("Failed to serialize JSON")? + )?; + } else { + use quick_protobuf::message::MessageWrite; - let mut buf = Vec::new(); - let mut writer = Writer::new(&mut buf); + let mut buf = Vec::new(); + let mut writer = Writer::new(&mut buf); - body.write_message(&mut writer) - .context("Failed encoding USP Msg Body")?; + body.write_message(&mut writer) + .context("Failed encoding USP Msg Body")?; - write_buf(buf, out, format)? - } + write_buf(buf, out, format)?; } Ok(()) diff --git a/src/usp_builder/add.rs b/src/usp_builder/add.rs index 83c21a2..5fd1c9f 100644 --- a/src/usp_builder/add.rs +++ b/src/usp_builder/add.rs @@ -14,14 +14,14 @@ pub struct CreateObjectBuilder { } impl CreateObjectBuilder { - pub const fn new(obj_path: String) -> Self { + #[must_use] pub const fn new(obj_path: String) -> Self { Self { obj_path, param_settings: vec![], } } - pub fn with_param_settings(mut self, param_settings: Vec<(String, String, bool)>) -> Self { + #[must_use] pub fn with_param_settings(mut self, param_settings: Vec<(String, String, bool)>) -> Self { self.param_settings = param_settings; self } @@ -51,31 +51,31 @@ pub struct AddBuilder { } impl AddBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { allow_partial: false, create_objs: vec![], } } - pub fn with_allow_partial(mut self, allow_partial: bool) -> Self { + #[must_use] pub const fn with_allow_partial(mut self, allow_partial: bool) -> Self { self.allow_partial = allow_partial; self } - pub fn with_create_objs(mut self, create_objs: Vec) -> Self { + #[must_use] pub fn with_create_objs(mut self, create_objs: Vec) -> Self { self.create_objs = create_objs; self } pub fn build(self) -> Result> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::add; let create_objs = self .create_objs .into_iter() - .map(|b| b.build()) + .map(CreateObjectBuilder::build) .collect::>>()?; Ok(Body { @@ -121,18 +121,18 @@ pub enum AddOperationStatus { } impl AddOperationStatus { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self::None } - pub fn set_failure(self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_failure(self, err_code: u32, err_msg: Option) -> Self { Self::Failure(AddOperationFailureBuilder { err_code, err_msg: err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string()), }) } - pub fn set_success( + #[must_use] pub fn set_success( self, instantiated_path: String, param_errs: Vec, @@ -147,17 +147,17 @@ impl AddOperationStatus { pub fn build(self) -> Result> { use crate::usp::mod_AddResp::mod_CreatedObjectResult::mod_OperationStatus::{ - OneOfoper_status::*, OperationFailure, OperationSuccess, + OneOfoper_status::{oper_failure, oper_success}, OperationFailure, OperationSuccess, }; use crate::usp::mod_AddResp::ParameterError; match self { - AddOperationStatus::Failure(f) => Ok(OperationStatus { + Self::Failure(f) => Ok(OperationStatus { oper_status: oper_failure(OperationFailure { err_code: f.err_code, err_msg: f.err_msg.into(), }), }), - AddOperationStatus::Success(s) => Ok(OperationStatus { + Self::Success(s) => Ok(OperationStatus { oper_status: oper_success(OperationSuccess { instantiated_path: s.instantiated_path.into(), param_errs: s @@ -180,7 +180,7 @@ impl AddOperationStatus { .collect(), }), }), - AddOperationStatus::None => Err(anyhow::anyhow!("")), + Self::None => Err(anyhow::anyhow!("")), } } } @@ -192,7 +192,7 @@ pub struct CreatedObjectResultsBuilder { } impl CreatedObjectResultsBuilder { - pub const fn new(requested_path: String, oper_status: AddOperationStatus) -> Self { + #[must_use] pub const fn new(requested_path: String, oper_status: AddOperationStatus) -> Self { Self { requested_path, oper_status, @@ -213,13 +213,13 @@ pub struct AddRespBuilder { } impl AddRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { created_obj_results: vec![], } } - pub fn with_created_obj_results( + #[must_use] pub fn with_created_obj_results( mut self, created_obj_results: Vec, ) -> Self { @@ -228,13 +228,13 @@ impl AddRespBuilder { } pub fn build(self) -> Result> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::add_resp; let created_obj_results = self .created_obj_results .into_iter() - .map(|b| b.build()) + .map(CreatedObjectResultsBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/delete.rs b/src/usp_builder/delete.rs index 6928cfa..fc9f5c6 100644 --- a/src/usp_builder/delete.rs +++ b/src/usp_builder/delete.rs @@ -1,6 +1,6 @@ use crate::usp::mod_Body::OneOfmsg_body::{request, response}; use crate::usp::mod_DeleteResp::mod_DeletedObjectResult::mod_OperationStatus::{ - OneOfoper_status::*, OperationFailure, OperationSuccess, + OneOfoper_status::{oper_failure, oper_success}, OperationFailure, OperationSuccess, }; use crate::usp::mod_DeleteResp::UnaffectedPathError; use crate::usp::mod_DeleteResp::{mod_DeletedObjectResult::OperationStatus, DeletedObjectResult}; @@ -18,19 +18,19 @@ pub struct DeleteBuilder { } impl DeleteBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { allow_partial: false, obj_paths: vec![], } } - pub fn with_allow_partial(mut self, allow_partial: bool) -> Self { + #[must_use] pub const fn with_allow_partial(mut self, allow_partial: bool) -> Self { self.allow_partial = allow_partial; self } - pub fn with_obj_paths(mut self, params: Vec) -> Self { + #[must_use] pub fn with_obj_paths(mut self, params: Vec) -> Self { self.obj_paths = params; self } @@ -78,14 +78,14 @@ pub struct DeletedObjectResultsBuilder { } impl DeletedObjectResultsBuilder { - pub const fn new(requested_path: String) -> Self { + #[must_use] pub const fn new(requested_path: String) -> Self { Self { requested_path, oper_status: DeleteRespOperationStatus::None, } } - pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { self.oper_status = DeleteRespOperationStatus::Failure { err_code, err_msg: err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string()), @@ -93,7 +93,7 @@ impl DeletedObjectResultsBuilder { self } - pub fn set_success( + #[must_use] pub fn set_success( mut self, affected_paths: Vec, unaffected_path_errs: Vec, @@ -145,13 +145,13 @@ pub struct DeleteRespBuilder { } impl DeleteRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { deleted_obj_results: vec![], } } - pub fn with_deleted_obj_results( + #[must_use] pub fn with_deleted_obj_results( mut self, deleted_obj_results: Vec, ) -> Self { @@ -168,7 +168,7 @@ impl DeleteRespBuilder { deleted_obj_results: self .deleted_obj_results .into_iter() - .map(|r| r.build()) + .map(DeletedObjectResultsBuilder::build) .collect::>>()?, } }), diff --git a/src/usp_builder/deregister.rs b/src/usp_builder/deregister.rs index 7bacbf3..f2cc963 100644 --- a/src/usp_builder/deregister.rs +++ b/src/usp_builder/deregister.rs @@ -18,11 +18,11 @@ pub struct DeregisterBuilder { } impl DeregisterBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { paths: vec![] } } - pub fn with_paths(mut self, paths: Vec) -> Self { + #[must_use] pub fn with_paths(mut self, paths: Vec) -> Self { self.paths = paths; self } @@ -33,7 +33,7 @@ impl DeregisterBuilder { Request { req_type: deregister({ Deregister { - paths: self.paths.into_iter().map(|p| p.into()).collect(), + paths: self.paths.into_iter().map(std::convert::Into::into).collect(), } }), } @@ -56,14 +56,14 @@ pub struct DeregisteredPathResultBuilder { } impl DeregisteredPathResultBuilder { - pub const fn new(requested_path: String) -> Self { + #[must_use] pub const fn new(requested_path: String) -> Self { Self { requested_path, oper_status: DeregisterOperationStatus::None, } } - pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { self.oper_status = DeregisterOperationStatus::Failure { err_code, err_msg: err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string()), @@ -71,7 +71,7 @@ impl DeregisteredPathResultBuilder { self } - pub fn set_success(mut self, deregistered_path: Vec) -> Self { + #[must_use] pub fn set_success(mut self, deregistered_path: Vec) -> Self { self.oper_status = DeregisterOperationStatus::Success(deregistered_path); self } @@ -88,7 +88,7 @@ impl DeregisteredPathResultBuilder { }), DeregisterOperationStatus::Success(s) => Ok(OperationStatus { oper_status: OneOfoper_status::oper_success(OperationSuccess { - deregistered_path: s.into_iter().map(|r| r.into()).collect::>(), + deregistered_path: s.into_iter().map(std::convert::Into::into).collect::>(), }), }), DeregisterOperationStatus::None => Err(anyhow::anyhow!("")), @@ -103,13 +103,13 @@ pub struct DeregisterRespBuilder { } impl DeregisterRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { deregistered_path_results: vec![], } } - pub fn with_deregistered_path_results( + #[must_use] pub fn with_deregistered_path_results( mut self, deregistered_path_results: Vec, ) -> Self { @@ -121,7 +121,7 @@ impl DeregisterRespBuilder { let deregistered_path_results = self .deregistered_path_results .into_iter() - .map(|r| r.build()) + .map(DeregisteredPathResultBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/error.rs b/src/usp_builder/error.rs index 6e8051c..1abc738 100644 --- a/src/usp_builder/error.rs +++ b/src/usp_builder/error.rs @@ -15,7 +15,7 @@ pub struct ErrorBuilder { } impl ErrorBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { code: 0, message: None, @@ -23,13 +23,13 @@ impl ErrorBuilder { } } - pub fn set_err(mut self, code: u32, message: Option) -> Self { + #[must_use] pub fn set_err(mut self, code: u32, message: Option) -> Self { self.code = code; self.message = message; self } - pub fn with_param_errs(mut self, errs: Vec<(String, u32, String)>) -> Self { + #[must_use] pub fn with_param_errs(mut self, errs: Vec<(String, u32, String)>) -> Self { self.param_errs = errs; self } diff --git a/src/usp_builder/get.rs b/src/usp_builder/get.rs index 873e9e1..3b59e95 100644 --- a/src/usp_builder/get.rs +++ b/src/usp_builder/get.rs @@ -15,19 +15,19 @@ pub struct GetBuilder { } impl GetBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { max_depth: 0, params: vec![], } } - pub fn with_max_depth(mut self, max_depth: u32) -> Self { + #[must_use] pub const fn with_max_depth(mut self, max_depth: u32) -> Self { self.max_depth = max_depth; self } - pub fn with_params(mut self, params: Vec) -> Self { + #[must_use] pub fn with_params(mut self, params: Vec) -> Self { self.params = params; self } @@ -55,14 +55,14 @@ pub struct ResolvedPathResultBuilder { } impl ResolvedPathResultBuilder { - pub const fn new(resolved_path: String) -> Self { + #[must_use] pub const fn new(resolved_path: String) -> Self { Self { resolved_path, result_params: vec![], } } - pub fn with_result_params(mut self, result_params: Vec<(String, String)>) -> Self { + #[must_use] pub fn with_result_params(mut self, result_params: Vec<(String, String)>) -> Self { self.result_params = result_params; self } @@ -90,7 +90,7 @@ pub struct ReqPathResultBuilder { } impl ReqPathResultBuilder { - pub const fn new(requested_path: String) -> Self { + #[must_use] pub const fn new(requested_path: String) -> Self { Self { requested_path, err_code: 0, @@ -99,13 +99,13 @@ impl ReqPathResultBuilder { } } - pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { self.err_code = err_code; self.err_msg = err_msg; self } - pub fn with_res_path_results( + #[must_use] pub fn with_res_path_results( mut self, resolved_path_results: Vec, ) -> Self { @@ -122,7 +122,7 @@ impl ReqPathResultBuilder { let resolved_path_results = self .resolved_path_results .into_iter() - .map(|path| path.build()) + .map(ResolvedPathResultBuilder::build) .collect::>>()?; Ok(RequestedPathResult { @@ -140,13 +140,13 @@ pub struct GetRespBuilder { } impl GetRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { req_path_results: vec![], } } - pub fn with_req_path_results(mut self, req_path_results: Vec) -> Self { + #[must_use] pub fn with_req_path_results(mut self, req_path_results: Vec) -> Self { self.req_path_results = req_path_results; self } @@ -155,7 +155,7 @@ impl GetRespBuilder { let req_path_results = self .req_path_results .into_iter() - .map(|r| r.build()) + .map(ReqPathResultBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/getinstances.rs b/src/usp_builder/getinstances.rs index f336a10..419f47e 100644 --- a/src/usp_builder/getinstances.rs +++ b/src/usp_builder/getinstances.rs @@ -15,19 +15,19 @@ pub struct GetInstancesBuilder { } impl GetInstancesBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { obj_paths: vec![], first_level_only: false, } } - pub fn with_first_level_only(mut self, first_level_only: bool) -> Self { + #[must_use] pub const fn with_first_level_only(mut self, first_level_only: bool) -> Self { self.first_level_only = first_level_only; self } - pub fn with_obj_paths(mut self, obj_paths: Vec) -> Self { + #[must_use] pub fn with_obj_paths(mut self, obj_paths: Vec) -> Self { self.obj_paths = obj_paths; self } @@ -55,14 +55,14 @@ pub struct CurrInstanceBuilder { } impl CurrInstanceBuilder { - pub const fn new(instantiated_obj_path: String) -> Self { + #[must_use] pub const fn new(instantiated_obj_path: String) -> Self { Self { instantiated_obj_path, unique_keys: vec![], } } - pub fn with_unique_keys(mut self, unique_keys: Vec<(String, String)>) -> Self { + #[must_use] pub fn with_unique_keys(mut self, unique_keys: Vec<(String, String)>) -> Self { self.unique_keys = unique_keys; self } @@ -90,7 +90,7 @@ pub struct ReqPathResultBuilder { } impl ReqPathResultBuilder { - pub const fn new(requested_path: String) -> Self { + #[must_use] pub const fn new(requested_path: String) -> Self { Self { requested_path, err_code: 0, @@ -99,13 +99,13 @@ impl ReqPathResultBuilder { } } - pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { self.err_code = err_code; self.err_msg = err_msg; self } - pub fn with_curr_insts(mut self, curr_insts: Vec) -> Self { + #[must_use] pub fn with_curr_insts(mut self, curr_insts: Vec) -> Self { self.curr_insts = curr_insts; self } @@ -119,7 +119,7 @@ impl ReqPathResultBuilder { let curr_insts = self .curr_insts .into_iter() - .map(|c| c.build()) + .map(CurrInstanceBuilder::build) .collect::>>()?; Ok(RequestedPathResult { @@ -137,13 +137,13 @@ pub struct GetInstancesRespBuilder { } impl GetInstancesRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { req_path_results: vec![], } } - pub fn with_req_path_results(mut self, req_path_results: Vec) -> Self { + #[must_use] pub fn with_req_path_results(mut self, req_path_results: Vec) -> Self { self.req_path_results = req_path_results; self } @@ -152,7 +152,7 @@ impl GetInstancesRespBuilder { let req_path_results = self .req_path_results .into_iter() - .map(|r| r.build()) + .map(ReqPathResultBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/getsupporteddm.rs b/src/usp_builder/getsupporteddm.rs index 03b958b..15ab064 100644 --- a/src/usp_builder/getsupporteddm.rs +++ b/src/usp_builder/getsupporteddm.rs @@ -2,7 +2,7 @@ use crate::usp::mod_Body::OneOfmsg_body::{request, response}; use crate::usp::mod_GetSupportedDMResp::SupportedUniqueKeySet; use crate::usp::mod_GetSupportedDMResp::{ CmdType, - ObjAccessType::{self, *}, + ObjAccessType::{self, OBJ_ADD_ONLY}, ParamAccessType, ParamValueType, RequestedObjectResult, SupportedCommandResult, SupportedEventResult, SupportedObjectResult, SupportedParamResult, ValueChangeType, }; @@ -24,7 +24,7 @@ pub struct GetSupportedDMBuilder { } impl GetSupportedDMBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { obj_paths: vec![], first_level_only: false, @@ -35,32 +35,32 @@ impl GetSupportedDMBuilder { } } - pub fn with_obj_paths(mut self, obj_paths: Vec) -> Self { + #[must_use] pub fn with_obj_paths(mut self, obj_paths: Vec) -> Self { self.obj_paths = obj_paths; self } - pub fn with_first_level_only(mut self, first_level_only: bool) -> Self { + #[must_use] pub const fn with_first_level_only(mut self, first_level_only: bool) -> Self { self.first_level_only = first_level_only; self } - pub fn with_return_commands(mut self, return_commands: bool) -> Self { + #[must_use] pub const fn with_return_commands(mut self, return_commands: bool) -> Self { self.return_commands = return_commands; self } - pub fn with_return_events(mut self, return_events: bool) -> Self { + #[must_use] pub const fn with_return_events(mut self, return_events: bool) -> Self { self.return_events = return_events; self } - pub fn with_return_params(mut self, return_params: bool) -> Self { + #[must_use] pub const fn with_return_params(mut self, return_params: bool) -> Self { self.return_params = return_params; self } - pub fn with_return_unique_key_sets(mut self, return_unique_key_sets: bool) -> Self { + #[must_use] pub const fn with_return_unique_key_sets(mut self, return_unique_key_sets: bool) -> Self { self.return_unique_key_sets = return_unique_key_sets; self } @@ -71,7 +71,7 @@ impl GetSupportedDMBuilder { Request { req_type: get_supported_dm({ GetSupportedDM { - obj_paths: self.obj_paths.into_iter().map(|e| e.into()).collect(), + obj_paths: self.obj_paths.into_iter().map(std::convert::Into::into).collect(), first_level_only: self.first_level_only, return_commands: self.return_commands, return_events: self.return_events, @@ -94,7 +94,7 @@ pub struct GSDMCommandResult { } impl GSDMCommandResult { - pub const fn new(command_name: String) -> Self { + #[must_use] pub const fn new(command_name: String) -> Self { Self { command_name, input_arg_names: vec![], @@ -103,22 +103,22 @@ impl GSDMCommandResult { } } - pub fn with_input_arg_names(mut self, input_arg_names: Vec) -> Self { + #[must_use] pub fn with_input_arg_names(mut self, input_arg_names: Vec) -> Self { self.input_arg_names = input_arg_names; self } - pub fn with_output_arg_names(mut self, output_arg_names: Vec) -> Self { + #[must_use] pub fn with_output_arg_names(mut self, output_arg_names: Vec) -> Self { self.output_arg_names = output_arg_names; self } - pub fn set_sync(mut self) -> Self { + #[must_use] pub const fn set_sync(mut self) -> Self { self.command_type = CmdType::CMD_SYNC; self } - pub fn set_async(mut self) -> Self { + #[must_use] pub const fn set_async(mut self) -> Self { self.command_type = CmdType::CMD_ASYNC; self } @@ -131,11 +131,11 @@ impl GSDMCommandResult { } Ok(SupportedCommandResult { command_name: self.command_name.into(), - input_arg_names: self.input_arg_names.into_iter().map(|e| e.into()).collect(), + input_arg_names: self.input_arg_names.into_iter().map(std::convert::Into::into).collect(), output_arg_names: self .output_arg_names .into_iter() - .map(|e| e.into()) + .map(std::convert::Into::into) .collect(), command_type: self.command_type, }) @@ -149,14 +149,14 @@ pub struct GSDMEventResult { } impl GSDMEventResult { - pub const fn new(event_name: String) -> Self { + #[must_use] pub const fn new(event_name: String) -> Self { Self { event_name, arg_names: vec![], } } - pub fn with_arg_names(mut self, arg_names: Vec) -> Self { + #[must_use] pub fn with_arg_names(mut self, arg_names: Vec) -> Self { self.arg_names = arg_names; self } @@ -164,7 +164,7 @@ impl GSDMEventResult { pub fn build(self) -> Result> { Ok(SupportedEventResult { event_name: self.event_name.into(), - arg_names: self.arg_names.into_iter().map(|e| e.into()).collect(), + arg_names: self.arg_names.into_iter().map(std::convert::Into::into).collect(), }) } } @@ -178,7 +178,7 @@ pub struct GSDMParamResult { } impl GSDMParamResult { - pub const fn new(param_name: String) -> Self { + #[must_use] pub const fn new(param_name: String) -> Self { Self { param_name, access: ParamAccessType::PARAM_READ_ONLY, @@ -187,77 +187,77 @@ impl GSDMParamResult { } } - pub fn set_access_read_only(mut self) -> Self { + #[must_use] pub const fn set_access_read_only(mut self) -> Self { self.access = ParamAccessType::PARAM_READ_ONLY; self } - pub fn set_access_write_only(mut self) -> Self { + #[must_use] pub const fn set_access_write_only(mut self) -> Self { self.access = ParamAccessType::PARAM_WRITE_ONLY; self } - pub fn set_access_read_write(mut self) -> Self { + #[must_use] pub const fn set_access_read_write(mut self) -> Self { self.access = ParamAccessType::PARAM_READ_WRITE; self } - pub fn set_type_int(mut self) -> Self { + #[must_use] pub const fn set_type_int(mut self) -> Self { self.value_type = ParamValueType::PARAM_INT; self } - pub fn set_type_unsigned_int(mut self) -> Self { + #[must_use] pub const fn set_type_unsigned_int(mut self) -> Self { self.value_type = ParamValueType::PARAM_UNSIGNED_INT; self } - pub fn set_type_long(mut self) -> Self { + #[must_use] pub const fn set_type_long(mut self) -> Self { self.value_type = ParamValueType::PARAM_LONG; self } - pub fn set_type_unsigned_long(mut self) -> Self { + #[must_use] pub const fn set_type_unsigned_long(mut self) -> Self { self.value_type = ParamValueType::PARAM_UNSIGNED_LONG; self } - pub fn set_type_string(mut self) -> Self { + #[must_use] pub const fn set_type_string(mut self) -> Self { self.value_type = ParamValueType::PARAM_STRING; self } - pub fn set_type_base64(mut self) -> Self { + #[must_use] pub const fn set_type_base64(mut self) -> Self { self.value_type = ParamValueType::PARAM_BASE_64; self } - pub fn set_type_hexbinary(mut self) -> Self { + #[must_use] pub const fn set_type_hexbinary(mut self) -> Self { self.value_type = ParamValueType::PARAM_HEX_BINARY; self } - pub fn set_type_datetime(mut self) -> Self { + #[must_use] pub const fn set_type_datetime(mut self) -> Self { self.value_type = ParamValueType::PARAM_DATE_TIME; self } - pub fn set_type_decimal(mut self) -> Self { + #[must_use] pub const fn set_type_decimal(mut self) -> Self { self.value_type = ParamValueType::PARAM_DECIMAL; self } - pub fn set_type_boolean(mut self) -> Self { + #[must_use] pub const fn set_type_boolean(mut self) -> Self { self.value_type = ParamValueType::PARAM_BOOLEAN; self } - pub fn set_value_change_allowed(mut self) -> Self { + #[must_use] pub const fn set_value_change_allowed(mut self) -> Self { self.value_change = ValueChangeType::VALUE_CHANGE_ALLOWED; self } - pub fn set_value_change_will_ignore(mut self) -> Self { + #[must_use] pub const fn set_value_change_will_ignore(mut self) -> Self { self.value_change = ValueChangeType::VALUE_CHANGE_WILL_IGNORE; self } @@ -293,7 +293,7 @@ pub struct GSDMSupportedObjectResult { } impl GSDMSupportedObjectResult { - pub const fn new(supported_obj_path: String) -> Self { + #[must_use] pub const fn new(supported_obj_path: String) -> Self { Self { supported_obj_path, access: OBJ_ADD_ONLY, @@ -306,32 +306,32 @@ impl GSDMSupportedObjectResult { } } - pub fn with_is_multi_instance(mut self, is_multi_instance: bool) -> Self { + #[must_use] pub const fn with_is_multi_instance(mut self, is_multi_instance: bool) -> Self { self.is_multi_instance = is_multi_instance; self } - pub fn with_supported_commands(mut self, supported_commands: Vec) -> Self { + #[must_use] pub fn with_supported_commands(mut self, supported_commands: Vec) -> Self { self.supported_commands = supported_commands; self } - pub fn with_supported_events(mut self, supported_events: Vec) -> Self { + #[must_use] pub fn with_supported_events(mut self, supported_events: Vec) -> Self { self.supported_events = supported_events; self } - pub fn with_supported_params(mut self, supported_params: Vec) -> Self { + #[must_use] pub fn with_supported_params(mut self, supported_params: Vec) -> Self { self.supported_params = supported_params; self } - pub fn with_divergent_paths(mut self, divergent_paths: Vec) -> Self { + #[must_use] pub fn with_divergent_paths(mut self, divergent_paths: Vec) -> Self { self.divergent_paths = divergent_paths; self } - pub fn with_unique_key_sets(mut self, unique_key_sets: Vec>) -> Self { + #[must_use] pub fn with_unique_key_sets(mut self, unique_key_sets: Vec>) -> Self { self.unique_key_sets = unique_key_sets; self } @@ -340,19 +340,19 @@ impl GSDMSupportedObjectResult { let supported_commands = self .supported_commands .into_iter() - .map(|i| i.build()) + .map(GSDMCommandResult::build) .collect::>>()?; let supported_events = self .supported_events .into_iter() - .map(|i| i.build()) + .map(GSDMEventResult::build) .collect::>>()?; let supported_params = self .supported_params .into_iter() - .map(|i| i.build()) + .map(GSDMParamResult::build) .collect::>>()?; let unique_key_sets: Vec> = self @@ -370,7 +370,7 @@ impl GSDMSupportedObjectResult { supported_commands, supported_events, supported_params, - divergent_paths: self.divergent_paths.into_iter().map(|e| e.into()).collect(), + divergent_paths: self.divergent_paths.into_iter().map(std::convert::Into::into).collect(), unique_key_sets, }) } @@ -386,7 +386,7 @@ pub struct GSDMReqObjectResultBuilder { } impl GSDMReqObjectResultBuilder { - pub const fn new(req_obj_path: String) -> Self { + #[must_use] pub const fn new(req_obj_path: String) -> Self { Self { req_obj_path, err_code: 0, @@ -396,19 +396,19 @@ impl GSDMReqObjectResultBuilder { } } - pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_err(mut self, err_code: u32, err_msg: Option) -> Self { self.err_code = err_code; self.err_msg = Some(err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string())); self } - pub fn with_data_model_inst_uri(mut self, data_model_inst_uri: String) -> Self { + #[must_use] pub fn with_data_model_inst_uri(mut self, data_model_inst_uri: String) -> Self { self.data_model_inst_uri = data_model_inst_uri; self } - pub fn with_supported_objs(mut self, supported_objs: Vec) -> Self { + #[must_use] pub fn with_supported_objs(mut self, supported_objs: Vec) -> Self { self.supported_objs = supported_objs; self } @@ -422,7 +422,7 @@ impl GSDMReqObjectResultBuilder { let supported_objs = self .supported_objs .into_iter() - .map(|c| c.build()) + .map(GSDMSupportedObjectResult::build) .collect::>>()?; Ok(RequestedObjectResult { @@ -441,13 +441,13 @@ pub struct GetSupportedDMRespBuilder { } impl GetSupportedDMRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { req_obj_results: vec![], } } - pub fn with_req_obj_results( + #[must_use] pub fn with_req_obj_results( mut self, req_obj_results: Vec, ) -> Self { @@ -459,7 +459,7 @@ impl GetSupportedDMRespBuilder { let req_obj_results = self .req_obj_results .into_iter() - .map(|r| r.build()) + .map(GSDMReqObjectResultBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/getsupportedprotocol.rs b/src/usp_builder/getsupportedprotocol.rs index 837185c..e270d9f 100644 --- a/src/usp_builder/getsupportedprotocol.rs +++ b/src/usp_builder/getsupportedprotocol.rs @@ -11,7 +11,7 @@ pub struct GetSupportedProtocolBuilder { } impl GetSupportedProtocolBuilder { - pub const fn new(controller_supported_protocol_versions: String) -> Self { + #[must_use] pub const fn new(controller_supported_protocol_versions: String) -> Self { Self { controller_supported_protocol_versions, } @@ -40,7 +40,7 @@ pub struct GetSupportedProtocolRespBuilder { } impl GetSupportedProtocolRespBuilder { - pub const fn new(agent_supported_protocol_versions: String) -> Self { + #[must_use] pub const fn new(agent_supported_protocol_versions: String) -> Self { Self { agent_supported_protocol_versions, } diff --git a/src/usp_builder/msg.rs b/src/usp_builder/msg.rs index 5e53c83..7eda4bb 100644 --- a/src/usp_builder/msg.rs +++ b/src/usp_builder/msg.rs @@ -14,28 +14,28 @@ pub struct MsgBuilder<'a> { } impl<'a> MsgBuilder<'a> { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { msg_id: None, body: None, } } - pub fn with_msg_id(mut self, msg_id: String) -> Self { + #[must_use] pub fn with_msg_id(mut self, msg_id: String) -> Self { self.msg_id = Some(msg_id); self } - pub fn with_body(mut self, body: Body<'a>) -> Self { + #[must_use] pub fn with_body(mut self, body: Body<'a>) -> Self { self.body = Some(body); self } pub fn build(self) -> Result> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Header::MsgType::*; - use crate::usp::mod_Request::OneOfreq_type::*; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Body::OneOfmsg_body::{error, request, response}; + use crate::usp::mod_Header::MsgType::{ADD, ADD_RESP, DELETE, DELETE_RESP, DEREGISTER, ERROR, GET, GET_INSTANCES, GET_INSTANCES_RESP, GET_RESP, GET_SUPPORTED_DM, GET_SUPPORTED_DM_RESP, GET_SUPPORTED_PROTO, GET_SUPPORTED_PROTO_RESP, NOTIFY, NOTIFY_RESP, OPERATE, OPERATE_RESP, REGISTER, REGISTER_RESP, SET, SET_RESP}; + use crate::usp::mod_Request::OneOfreq_type::{add, delete, deregister, get, get_instances, get_supported_dm, get_supported_protocol, notify, operate, register, set}; + use crate::usp::mod_Response::OneOfresp_type::{add_resp, delete_resp, deregister_resp, get_instances_resp, get_resp, get_supported_dm_resp, get_supported_protocol_resp, notify_resp, operate_resp, register_resp, set_resp}; let msg_id = self .msg_id diff --git a/src/usp_builder/notify.rs b/src/usp_builder/notify.rs index c6b9275..c193550 100644 --- a/src/usp_builder/notify.rs +++ b/src/usp_builder/notify.rs @@ -23,7 +23,7 @@ pub enum OperationCompleteType { #[derive(Clone)] pub enum NotifyType { - /// USP OnBoardRequest notification + /// USP `OnBoardRequest` notification OnBoardRequest { /// The OUI associated with the manufacturer of the device oui: String, @@ -37,7 +37,7 @@ pub enum NotifyType { /// A comma separated list of supported USP versions agent_supported_protocol_versions: String, }, - /// USP ValueChange notification + /// USP `ValueChange` notification ValueChange { /// The path of the changed parameter param_path: String, @@ -53,20 +53,20 @@ pub enum NotifyType { /// A stringified JSON object containing the output arguments of the USP Event params: HashMap, }, - /// USP ObjectCreation notification + /// USP `ObjectCreation` notification ObjectCreation { /// The path of the created object obj_path: String, - /// A stringified JSON object containing the unique_keys and values of the created Object + /// A stringified JSON object containing the `unique_keys` and values of the created Object unique_keys: HashMap, }, - /// USP ObjectDeletion notification + /// USP `ObjectDeletion` notification ObjectDeletion { /// The path of the deleted object obj_path: String, }, - /// USP OperationComplete notification + /// USP `OperationComplete` notification OperationComplete { /// The path of the operation object obj_path: String, @@ -87,7 +87,7 @@ pub struct NotifyBuilder { } impl NotifyBuilder { - pub const fn new(subscription_id: String) -> Self { + #[must_use] pub const fn new(subscription_id: String) -> Self { Self { subscription_id, send_resp: false, @@ -95,12 +95,12 @@ impl NotifyBuilder { } } - pub fn with_send_resp(mut self, send_resp: bool) -> Self { + #[must_use] pub const fn with_send_resp(mut self, send_resp: bool) -> Self { self.send_resp = send_resp; self } - pub fn with_onboard_request( + #[must_use] pub fn with_onboard_request( mut self, oui: String, product_class: String, @@ -116,7 +116,7 @@ impl NotifyBuilder { self } - pub fn with_value_change(mut self, param_path: String, param_value: String) -> Self { + #[must_use] pub fn with_value_change(mut self, param_path: String, param_value: String) -> Self { self.notify_type = Some(NotifyType::ValueChange { param_path, param_value, @@ -124,7 +124,7 @@ impl NotifyBuilder { self } - pub fn with_event( + #[must_use] pub fn with_event( mut self, obj_path: String, event_name: String, @@ -138,7 +138,7 @@ impl NotifyBuilder { self } - pub fn with_object_creation( + #[must_use] pub fn with_object_creation( mut self, obj_path: String, unique_keys: HashMap, @@ -150,12 +150,12 @@ impl NotifyBuilder { self } - pub fn with_object_deletion(mut self, obj_path: String) -> Self { + #[must_use] pub fn with_object_deletion(mut self, obj_path: String) -> Self { self.notify_type = Some(NotifyType::ObjectDeletion { obj_path }); self } - pub fn with_operation_complete_output_args( + #[must_use] pub fn with_operation_complete_output_args( mut self, obj_path: String, command_name: String, @@ -171,7 +171,7 @@ impl NotifyBuilder { self } - pub fn with_operation_complete_cmd_failure( + #[must_use] pub fn with_operation_complete_cmd_failure( mut self, obj_path: String, command_name: String, @@ -289,7 +289,7 @@ pub struct NotifyRespBuilder { } impl NotifyRespBuilder { - pub const fn new(subscription_id: String) -> Self { + #[must_use] pub const fn new(subscription_id: String) -> Self { Self { subscription_id } } diff --git a/src/usp_builder/operate.rs b/src/usp_builder/operate.rs index b33e808..8646108 100644 --- a/src/usp_builder/operate.rs +++ b/src/usp_builder/operate.rs @@ -22,7 +22,7 @@ pub struct OperateBuilder { } impl OperateBuilder { - pub const fn new(command: String) -> Self { + #[must_use] pub const fn new(command: String) -> Self { Self { command, command_key: String::new(), @@ -31,17 +31,17 @@ impl OperateBuilder { } } - pub fn with_command_key(mut self, command_key: String) -> Self { + #[must_use] pub fn with_command_key(mut self, command_key: String) -> Self { self.command_key = command_key; self } - pub fn with_send_resp(mut self, send_resp: bool) -> Self { + #[must_use] pub const fn with_send_resp(mut self, send_resp: bool) -> Self { self.send_resp = send_resp; self } - pub fn with_input_args(mut self, input_args: Vec<(String, String)>) -> Self { + #[must_use] pub fn with_input_args(mut self, input_args: Vec<(String, String)>) -> Self { self.input_args = input_args; self } @@ -90,14 +90,14 @@ pub struct OperateRespResultBuilder { } impl OperateRespResultBuilder { - pub const fn new(executed_command: String) -> Self { + #[must_use] pub const fn new(executed_command: String) -> Self { Self { operation_result: OperateRespOperationResult::None, executed_command, } } - pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { self.operation_result = OperateRespOperationResult::Failure { err_code, err_msg: err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string()), @@ -105,12 +105,12 @@ impl OperateRespResultBuilder { self } - pub fn set_path(mut self, req_obj_path: String) -> Self { + #[must_use] pub fn set_path(mut self, req_obj_path: String) -> Self { self.operation_result = OperateRespOperationResult::Path { req_obj_path }; self } - pub fn set_output_args(mut self, output_args: Vec<(String, String)>) -> Self { + #[must_use] pub fn set_output_args(mut self, output_args: Vec<(String, String)>) -> Self { self.operation_result = OperateRespOperationResult::OutputArgs { output_args: output_args.into_iter().collect(), }; @@ -152,13 +152,13 @@ pub struct OperateRespBuilder { } impl OperateRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { operation_results: vec![], } } - pub fn with_operation_results( + #[must_use] pub fn with_operation_results( mut self, operation_results: Vec, ) -> Self { @@ -174,7 +174,7 @@ impl OperateRespBuilder { operation_results: self .operation_results .into_iter() - .map(|s| s.build()) + .map(OperateRespResultBuilder::build) .collect::>>()?, }), } diff --git a/src/usp_builder/record.rs b/src/usp_builder/record.rs index d476707..b4ec20f 100644 --- a/src/usp_builder/record.rs +++ b/src/usp_builder/record.rs @@ -47,7 +47,7 @@ pub struct SessionContextBuilder { } impl SessionContextBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { session_id: None, sequence_id: None, @@ -57,27 +57,27 @@ impl SessionContextBuilder { } } - pub fn with_session_id(mut self, session_id: u64) -> Self { + #[must_use] pub const fn with_session_id(mut self, session_id: u64) -> Self { self.session_id = Some(session_id); self } - pub fn with_sequence_id(mut self, sequence_id: u64) -> Self { + #[must_use] pub const fn with_sequence_id(mut self, sequence_id: u64) -> Self { self.sequence_id = Some(sequence_id); self } - pub fn with_expected_id(mut self, expected_id: u64) -> Self { + #[must_use] pub const fn with_expected_id(mut self, expected_id: u64) -> Self { self.expected_id = Some(expected_id); self } - pub fn with_retransmit_id(mut self, retransmit_id: u64) -> Self { + #[must_use] pub const fn with_retransmit_id(mut self, retransmit_id: u64) -> Self { self.retransmit_id = retransmit_id; self } - pub fn with_payload(mut self, payload: Vec) -> Self { + #[must_use] pub fn with_payload(mut self, payload: Vec) -> Self { self.payload = Some(payload); self } @@ -122,7 +122,7 @@ pub struct RecordBuilder { } impl RecordBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { version: String::new(), to_id: None, @@ -135,27 +135,27 @@ impl RecordBuilder { } } - pub fn with_version(mut self, version: String) -> Self { + #[must_use] pub fn with_version(mut self, version: String) -> Self { self.version = version; self } - pub fn with_to_id(mut self, id: String) -> Self { + #[must_use] pub fn with_to_id(mut self, id: String) -> Self { self.to_id = Some(id); self } - pub fn with_from_id(mut self, id: String) -> Self { + #[must_use] pub fn with_from_id(mut self, id: String) -> Self { self.from_id = Some(id); self } - pub fn with_session_context_builder(mut self, session_context: SessionContextBuilder) -> Self { + #[must_use] pub fn with_session_context_builder(mut self, session_context: SessionContextBuilder) -> Self { self.typ = RecordType::SessionContext { session_context }; self } - pub fn with_no_session_context_payload(mut self, msg: Msg) -> Self { + #[must_use] pub fn with_no_session_context_payload(mut self, msg: Msg) -> Self { let mut buf = Vec::new(); let mut writer = quick_protobuf::Writer::new(&mut buf); quick_protobuf::MessageWrite::write_message(&msg, &mut writer).unwrap(); @@ -163,17 +163,17 @@ impl RecordBuilder { self.with_no_session_context_payload_bytes(buf) } - pub fn with_no_session_context_payload_bytes(mut self, buf: Vec) -> Self { + #[must_use] pub fn with_no_session_context_payload_bytes(mut self, buf: Vec) -> Self { self.payload = Some(buf); self } - pub fn as_websocket_connect_record(mut self) -> Self { + #[must_use] pub fn as_websocket_connect_record(mut self) -> Self { self.typ = RecordType::WebSocketConnect; self } - pub fn as_mqtt_connect_record( + #[must_use] pub fn as_mqtt_connect_record( mut self, version: MQTTVersion, subscribed_topic: String, @@ -185,7 +185,7 @@ impl RecordBuilder { self } - pub fn as_stomp_connect_record( + #[must_use] pub fn as_stomp_connect_record( mut self, version: crate::usp_record::mod_STOMPConnectRecord::STOMPVersion, subscribed_destination: String, @@ -197,7 +197,7 @@ impl RecordBuilder { self } - pub fn as_disconnect_record(mut self, reason: String, reason_code: u32) -> Self { + #[must_use] pub fn as_disconnect_record(mut self, reason: String, reason_code: u32) -> Self { self.typ = RecordType::Disconnect { reason, reason_code, @@ -205,7 +205,7 @@ impl RecordBuilder { self } - pub fn as_uds_connect_record(mut self) -> Self { + #[must_use] pub fn as_uds_connect_record(mut self) -> Self { self.typ = RecordType::UDSConnect; self } diff --git a/src/usp_builder/register.rs b/src/usp_builder/register.rs index 2bfbaa6..396d662 100644 --- a/src/usp_builder/register.rs +++ b/src/usp_builder/register.rs @@ -20,19 +20,19 @@ pub struct RegisterBuilder { } impl RegisterBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { allow_partial: false, reg_paths: vec![], } } - pub fn with_allow_partial(mut self, allow_partial: bool) -> Self { + #[must_use] pub const fn with_allow_partial(mut self, allow_partial: bool) -> Self { self.allow_partial = allow_partial; self } - pub fn with_reg_paths(mut self, reg_paths: Vec) -> Self { + #[must_use] pub fn with_reg_paths(mut self, reg_paths: Vec) -> Self { self.reg_paths = reg_paths; self } @@ -71,14 +71,14 @@ pub struct RegisteredPathResultBuilder { } impl RegisteredPathResultBuilder { - pub const fn new(requested_path: String) -> Self { + #[must_use] pub const fn new(requested_path: String) -> Self { Self { requested_path, oper_status: RegisterOperationStatus::None, } } - pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { + #[must_use] pub fn set_failure(mut self, err_code: u32, err_msg: Option) -> Self { self.oper_status = RegisterOperationStatus::Failure { err_code, err_msg: err_msg.unwrap_or_else(|| usp_errors::get_err_msg(err_code).to_string()), @@ -86,7 +86,7 @@ impl RegisteredPathResultBuilder { self } - pub fn set_success(mut self, registered_path: String) -> Self { + #[must_use] pub fn set_success(mut self, registered_path: String) -> Self { self.oper_status = RegisterOperationStatus::Success(registered_path); self } @@ -118,13 +118,13 @@ pub struct RegisterRespBuilder { } impl RegisterRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { registered_path_results: vec![], } } - pub fn with_registered_path_results( + #[must_use] pub fn with_registered_path_results( mut self, registered_path_results: Vec, ) -> Self { @@ -136,7 +136,7 @@ impl RegisterRespBuilder { let registered_path_results = self .registered_path_results .into_iter() - .map(|r| r.build()) + .map(RegisteredPathResultBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_builder/set.rs b/src/usp_builder/set.rs index c8c0272..919409e 100644 --- a/src/usp_builder/set.rs +++ b/src/usp_builder/set.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::usp::mod_Set::{UpdateObject, UpdateParamSetting}; use crate::usp::mod_SetResp::mod_UpdatedObjectResult::mod_OperationStatus::{ - OneOfoper_status::*, OperationFailure, OperationSuccess, + OneOfoper_status::{oper_failure, oper_success}, OperationFailure, OperationSuccess, }; use crate::usp::mod_SetResp::ParameterError; use crate::usp::mod_SetResp::{mod_UpdatedObjectResult::OperationStatus, UpdatedObjectResult}; @@ -19,14 +19,14 @@ pub struct UpdateObjectBuilder { } impl UpdateObjectBuilder { - pub const fn new(obj_path: String) -> Self { + #[must_use] pub const fn new(obj_path: String) -> Self { Self { obj_path, param_settings: vec![], } } - pub fn with_param_settings(mut self, param_settings: Vec<(String, String, bool)>) -> Self { + #[must_use] pub fn with_param_settings(mut self, param_settings: Vec<(String, String, bool)>) -> Self { self.param_settings = param_settings; self } @@ -56,31 +56,31 @@ pub struct SetBuilder { } impl SetBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { allow_partial: false, update_objs: vec![], } } - pub fn with_allow_partial(mut self, allow_partial: bool) -> Self { + #[must_use] pub const fn with_allow_partial(mut self, allow_partial: bool) -> Self { self.allow_partial = allow_partial; self } - pub fn with_update_objs(mut self, update_objs: Vec) -> Self { + #[must_use] pub fn with_update_objs(mut self, update_objs: Vec) -> Self { self.update_objs = update_objs; self } pub fn build(self) -> Result> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::set; let update_objs = self .update_objs .into_iter() - .map(|b| b.build()) + .map(UpdateObjectBuilder::build) .collect::>>()?; Ok(Body { @@ -119,14 +119,14 @@ pub struct UpdatedInstanceFailureBuilder { } impl UpdatedInstanceFailureBuilder { - pub const fn new(affected_path: String) -> Self { + #[must_use] pub const fn new(affected_path: String) -> Self { Self { affected_path, param_errs: vec![], } } - pub fn with_param_errs(mut self, param_errs: Vec) -> Self { + #[must_use] pub fn with_param_errs(mut self, param_errs: Vec) -> Self { self.param_errs = param_errs; self } @@ -147,11 +147,11 @@ pub enum SetOperationStatus { } impl SetOperationStatus { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self::None } - pub fn set_failure( + #[must_use] pub fn set_failure( self, err_code: u32, err_msg: Option, @@ -164,13 +164,13 @@ impl SetOperationStatus { }) } - pub fn set_success(self, updated_inst_results: Vec) -> Self { + #[must_use] pub fn set_success(self, updated_inst_results: Vec) -> Self { Self::Success(updated_inst_results) } pub fn build(self) -> Result> { match self { - SetOperationStatus::Failure(f) => Ok(OperationStatus { + Self::Failure(f) => Ok(OperationStatus { oper_status: oper_failure(OperationFailure { err_code: f.err_code, err_msg: f.err_msg.into(), @@ -196,7 +196,7 @@ impl SetOperationStatus { .collect(), }), }), - SetOperationStatus::Success(s) => Ok(OperationStatus { + Self::Success(s) => Ok(OperationStatus { oper_status: oper_success(OperationSuccess { updated_inst_results: s .into_iter() @@ -224,7 +224,7 @@ impl SetOperationStatus { .collect(), }), }), - SetOperationStatus::None => Err(anyhow::anyhow!("")), + Self::None => Err(anyhow::anyhow!("")), } } } @@ -236,7 +236,7 @@ pub struct UpdatedObjectResultsBuilder { } impl UpdatedObjectResultsBuilder { - pub const fn new(requested_path: String, oper_status: SetOperationStatus) -> Self { + #[must_use] pub const fn new(requested_path: String, oper_status: SetOperationStatus) -> Self { Self { requested_path, oper_status, @@ -257,13 +257,13 @@ pub struct SetRespBuilder { } impl SetRespBuilder { - pub const fn new() -> Self { + #[must_use] pub const fn new() -> Self { Self { updated_obj_results: vec![], } } - pub fn with_updated_obj_results( + #[must_use] pub fn with_updated_obj_results( mut self, updated_obj_results: Vec, ) -> Self { @@ -272,13 +272,13 @@ impl SetRespBuilder { } pub fn build(self) -> Result> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::set_resp; let updated_obj_results = self .updated_obj_results .into_iter() - .map(|b| b.build()) + .map(UpdatedObjectResultsBuilder::build) .collect::>>()?; Ok(Body { diff --git a/src/usp_decoder.rs b/src/usp_decoder.rs index 4e949f4..c27b13c 100644 --- a/src/usp_decoder.rs +++ b/src/usp_decoder.rs @@ -89,7 +89,7 @@ impl<'a> Msg<'a> { /// ]); /// assert_eq!(msg.unwrap().msg_id(), "AXSS-1544114045.442596"); /// ``` - pub fn msg_id(&'a self) -> &str { + #[must_use] pub fn msg_id(&'a self) -> &str { if let Some(header) = self.header.as_ref() { header.msg_id.as_ref() } else { @@ -136,7 +136,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert_eq!(msg.is_request(), false); /// ``` - pub fn is_request(&'a self) -> bool { + #[must_use] pub const fn is_request(&'a self) -> bool { if let Some(body) = self.body.as_ref() { matches!(&body.msg_body, usp::mod_Body::OneOfmsg_body::request(_)) } else { @@ -183,7 +183,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert_eq!(msg.is_notify_request(), false); /// ``` - pub fn is_notify_request(&'a self) -> bool { + #[must_use] pub const fn is_notify_request(&'a self) -> bool { self.get_notify_request().is_some() } @@ -226,7 +226,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert!(msg.get_notify_request().is_none()); /// ``` - pub fn get_notify_request(&'a self) -> Option<&Notify> { + #[must_use] pub const fn get_notify_request(&'a self) -> Option<&Notify> { if let Some(body) = self.body.as_ref() { if let usp::mod_Body::OneOfmsg_body::request(request) = &body.msg_body { if let usp::mod_Request::OneOfreq_type::notify(notify) = &request.req_type { @@ -277,7 +277,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert_eq!(msg.is_response(), true); /// ``` - pub fn is_response(&'a self) -> bool { + #[must_use] pub const fn is_response(&'a self) -> bool { if let Some(body) = self.body.as_ref() { matches!(&body.msg_body, usp::mod_Body::OneOfmsg_body::response(_)) } else { @@ -336,7 +336,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert_eq!(msg.is_error(), true); /// ``` - pub fn is_error(&'a self) -> bool { + #[must_use] pub const fn is_error(&'a self) -> bool { self.get_error().is_some() } @@ -391,7 +391,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert!(msg.get_error().is_some()); /// ``` - pub fn get_error(&'a self) -> Option<&Error> { + #[must_use] pub const fn get_error(&'a self) -> Option<&Error> { if let Some(body) = self.body.as_ref() { if let usp::mod_Body::OneOfmsg_body::error(error) = &body.msg_body { return Some(error); @@ -423,7 +423,7 @@ impl<'a> Msg<'a> { /// ]).unwrap(); /// assert_eq!(msg.to_json().unwrap(), "{\"Header\":{\"msg_id\":\"test\",\"msg_type\":\"NOTIFY\"},\"Body\":{\"Request\":{\"Notify\":{\"subscription_id\":\"notif\",\"send_resp\":true,\"on_board_req\":{\"oui\":\"0044FF\",\"product_class\":\"Foo\",\"serial_number\":\"01234\",\"agent_supported_protocol_versions\":\"1.3\"}}}}}"); /// ``` - pub fn to_json(&'a self) -> Option { + #[must_use] pub fn to_json(&'a self) -> Option { serde_json::to_string(self).ok() } diff --git a/src/usp_errors.rs b/src/usp_errors.rs index 69b29de..5beb2c7 100644 --- a/src/usp_errors.rs +++ b/src/usp_errors.rs @@ -1,5 +1,5 @@ /// Gets an USP error message from the error code, returning an empty str for unknown codes -pub const fn get_err_msg(code: u32) -> &'static str { +#[must_use] pub const fn get_err_msg(code: u32) -> &'static str { match code { 7000 => "Message failed", 7001 => "Message not supported", diff --git a/src/usp_generator.rs b/src/usp_generator.rs index ed3a517..31e8cee 100644 --- a/src/usp_generator.rs +++ b/src/usp_generator.rs @@ -30,11 +30,11 @@ pub use crate::usp_types::{NotifyType, PayloadSARState, PayloadSecurity}; /// usp_get_request(&["Device.", "Device.DeviceInfo."], 0), /// ); /// ``` -pub fn usp_msg(msg_id: String, body: Body) -> Msg { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Header::MsgType::*; - use crate::usp::mod_Request::OneOfreq_type::*; - use crate::usp::mod_Response::OneOfresp_type::*; +#[must_use] pub fn usp_msg(msg_id: String, body: Body) -> Msg { + use crate::usp::mod_Body::OneOfmsg_body::{error, request, response}; + use crate::usp::mod_Header::MsgType::{ADD, ADD_RESP, DELETE, DELETE_RESP, DEREGISTER, DEREGISTER_RESP, ERROR, GET, GET_INSTANCES, GET_INSTANCES_RESP, GET_RESP, GET_SUPPORTED_DM, GET_SUPPORTED_DM_RESP, GET_SUPPORTED_PROTO, GET_SUPPORTED_PROTO_RESP, NOTIFY, NOTIFY_RESP, OPERATE, OPERATE_RESP, REGISTER, REGISTER_RESP, SET, SET_RESP}; + use crate::usp::mod_Request::OneOfreq_type::{add, delete, deregister, get, get_instances, get_supported_dm, get_supported_protocol, notify, operate, register, set}; + use crate::usp::mod_Response::OneOfresp_type::{add_resp, delete_resp, deregister_resp, get_instances_resp, get_resp, get_supported_dm_resp, get_supported_protocol_resp, notify_resp, operate_resp, register_resp, set_resp}; let msg_type = match &body.msg_body { request(ref req) => match &req.req_type { @@ -94,11 +94,11 @@ pub fn usp_msg(msg_id: String, body: Body) -> Msg { /// &usp_get_request(&["Device.", "Device.DeviceInfo."], 0), /// ); /// ``` -pub fn usp_msg_by_ref<'a>(msg_id: &'a str, body: &Body<'a>) -> Msg<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Header::MsgType::*; - use crate::usp::mod_Request::OneOfreq_type::*; - use crate::usp::mod_Response::OneOfresp_type::*; +#[must_use] pub fn usp_msg_by_ref<'a>(msg_id: &'a str, body: &Body<'a>) -> Msg<'a> { + use crate::usp::mod_Body::OneOfmsg_body::{error, request, response}; + use crate::usp::mod_Header::MsgType::{ADD, ADD_RESP, DELETE, DELETE_RESP, DEREGISTER, DEREGISTER_RESP, ERROR, GET, GET_INSTANCES, GET_INSTANCES_RESP, GET_RESP, GET_SUPPORTED_DM, GET_SUPPORTED_DM_RESP, GET_SUPPORTED_PROTO, GET_SUPPORTED_PROTO_RESP, NOTIFY, NOTIFY_RESP, OPERATE, OPERATE_RESP, REGISTER, REGISTER_RESP, SET, SET_RESP}; + use crate::usp::mod_Request::OneOfreq_type::{add, delete, deregister, get, get_instances, get_supported_dm, get_supported_protocol, notify, operate, register, set}; + use crate::usp::mod_Response::OneOfresp_type::{add_resp, delete_resp, deregister_resp, get_instances_resp, get_resp, get_supported_dm_resp, get_supported_protocol_resp, notify_resp, operate_resp, register_resp, set_resp}; let msg_type = match body.msg_body { request(ref req) => match &req.req_type { @@ -162,8 +162,8 @@ pub fn usp_msg_by_ref<'a>(msg_id: &'a str, body: &Body<'a>) -> Msg<'a> { /// use rusp::usp_generator::usp_simple_error; /// let err = usp_simple_error(7803, Some("Funny custom vendor error")); /// ``` -pub fn usp_simple_error(code: u32, message: Option<&str>) -> Body { - use crate::usp::mod_Body::OneOfmsg_body::*; +#[must_use] pub fn usp_simple_error(code: u32, message: Option<&str>) -> Body { + use crate::usp::mod_Body::OneOfmsg_body::error; let err_msg = message.unwrap_or_else(|| get_err_msg(code)); @@ -203,12 +203,12 @@ pub fn usp_simple_error(code: u32, message: Option<&str>) -> Body { /// &[("Some.Path", 7804, "Funny error related to path")], /// ); /// ``` -pub fn usp_error<'a>( +#[must_use] pub fn usp_error<'a>( code: u32, message: Option<&'a str>, param_errs: &[(&'a str, u32, &'a str)], ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; + use crate::usp::mod_Body::OneOfmsg_body::error; use crate::usp::mod_Error::ParamError; let err_msg = message.unwrap_or_else(|| get_err_msg(code)); @@ -246,8 +246,8 @@ pub fn usp_error<'a>( /// let req = usp_get_request(&["Device.", "Device.DeviceInfo."], 0); /// ``` pub fn usp_get_request>(params: &'_ [S], max_depth: u32) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::get; Body { msg_body: request({ @@ -280,8 +280,8 @@ pub fn usp_add_request, V: AsRef<[(S, S, bool)]>>( allow_partial: bool, args: &'_ [(S, V)], ) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::add; Body { msg_body: request({ @@ -327,8 +327,8 @@ pub fn usp_add_request, V: AsRef<[(S, S, bool)]>>( /// let req = usp_delete_request(true, &["Device.XMPP.Connection.1."]); /// ``` pub fn usp_delete_request>(allow_partial: bool, obj_paths: &'_ [S]) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::delete; Body { msg_body: request({ @@ -364,8 +364,8 @@ pub fn usp_set_request, V: AsRef<[(S, S, bool)]>>( allow_partial: bool, args: &'_ [(S, V)], ) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::set; Body { msg_body: request({ @@ -401,7 +401,7 @@ pub fn usp_set_request, V: AsRef<[(S, S, bool)]>>( /// /// # Arguments /// -/// * `sub_id` - The subscription_id for the Notify +/// * `sub_id` - The `subscription_id` for the Notify /// * `send_resp` - Whether this requests expects a response to be sent /// * `typ` - A filled out `NotifyType` structure /// @@ -417,14 +417,14 @@ pub fn usp_set_request, V: AsRef<[(S, S, bool)]>>( /// agent_supported_protocol_versions: "1.0".to_string() /// }); /// ``` -pub fn usp_notify_request<'a>(sub_id: &'a str, send_resp: bool, typ: &'a NotifyType) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; +#[must_use] pub fn usp_notify_request<'a>(sub_id: &'a str, send_resp: bool, typ: &'a NotifyType) -> Body<'a> { + use crate::usp::mod_Body::OneOfmsg_body::request; use crate::usp::mod_Notify::mod_OperationComplete::OneOfoperation_resp; - use crate::usp::mod_Notify::OneOfnotification::*; + use crate::usp::mod_Notify::OneOfnotification::{event, obj_creation, obj_deletion, on_board_req, oper_complete, value_change}; use crate::usp::mod_Notify::{ Event, ObjectCreation, ObjectDeletion, OnBoardRequest, OperationComplete, ValueChange, }; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Request::OneOfreq_type::notify; use crate::usp_types::OperateResponse; Body { @@ -545,8 +545,8 @@ pub fn usp_operate_request<'a, V: AsRef<[(&'a str, &'a str)]>>( send_resp: bool, args: V, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::operate; Body { msg_body: request({ @@ -568,11 +568,11 @@ pub fn usp_operate_request<'a, V: AsRef<[(&'a str, &'a str)]>>( } } -/// Generates a body of a USP Msg with a USP GetInstances request +/// Generates a body of a USP Msg with a USP `GetInstances` request /// /// # Arguments /// -/// * `obj_paths` - An array of parameter/object names to put into the GetInstances request +/// * `obj_paths` - An array of parameter/object names to put into the `GetInstances` request /// * `first_level_only` - Whether to just return information for the requested path or recursively /// /// # Example @@ -585,8 +585,8 @@ pub fn usp_get_instances_request>( obj_paths: &'_ [S], first_level_only: bool, ) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::get_instances; Body { msg_body: request({ @@ -606,11 +606,11 @@ pub fn usp_get_instances_request>( } } -/// Generates a body of a USP Msg with a USP GetSupportedDM request +/// Generates a body of a USP Msg with a USP `GetSupportedDM` request /// /// # Arguments /// -/// * `paths` - An array of parameter/object names to put into the GetSupportedDM request +/// * `paths` - An array of parameter/object names to put into the `GetSupportedDM` request /// * `first_level_only` - Whether to just return information for the requested path or recursively /// * `return_commands` - Return commands in response /// * `return_events` - Return events in response @@ -629,8 +629,8 @@ pub fn usp_get_supported_dm_request>( return_events: bool, return_params: bool, ) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::get_supported_dm; Body { msg_body: request({ @@ -653,7 +653,7 @@ pub fn usp_get_supported_dm_request>( } } -/// Generates a body of a USP Msg with a USP GetSupportedProtocol request +/// Generates a body of a USP Msg with a USP `GetSupportedProtocol` request /// /// # Arguments /// @@ -665,9 +665,9 @@ pub fn usp_get_supported_dm_request>( /// use rusp::usp_generator::usp_get_supported_prototol_request; /// let req = usp_get_supported_prototol_request("1.1"); /// ``` -pub fn usp_get_supported_prototol_request(cspv: &str) -> Body { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Request::OneOfreq_type::*; +#[must_use] pub const fn usp_get_supported_prototol_request(cspv: &str) -> Body { + use crate::usp::mod_Body::OneOfmsg_body::request; + use crate::usp::mod_Request::OneOfreq_type::get_supported_protocol; Body { msg_body: request({ @@ -682,11 +682,11 @@ pub fn usp_get_supported_prototol_request(cspv: &str) -> Body { } } -/// Creates a body for a USP Msg with a USP GetResp response +/// Creates a body for a USP Msg with a USP `GetResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the GetResp response +/// * `result` - A vector of Result tuples to put into the `GetResp` response /// /// # Example /// @@ -697,15 +697,15 @@ pub fn usp_get_supported_prototol_request(cspv: &str) -> Body { /// ("Dev.", Err((7000, "Message failed"))), /// ]); /// ``` -pub fn usp_get_response<'a>( +#[must_use] pub fn usp_get_response<'a>( result: Vec<( &'a str, Result)>, (u32, &'a str)>, )>, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; + use crate::usp::mod_Body::OneOfmsg_body::response; use crate::usp::mod_GetResp::{RequestedPathResult, ResolvedPathResult}; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Response::OneOfresp_type::get_resp; use crate::usp::GetResp; Body { @@ -765,11 +765,11 @@ pub struct RequestedPathResult<'a> { pub type GetResp<'a> = Vec>; -/// Creates a body for a USP Msg with a USP GetResp response +/// Creates a body for a USP Msg with a USP `GetResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the GetResp response +/// * `result` - A vector of Result tuples to put into the `GetResp` response /// /// # Example /// @@ -779,7 +779,7 @@ pub type GetResp<'a> = Vec>; /// let deserialised : GetResp = serde_json::from_str(&json).unwrap(); /// let resp = usp_get_response_from_json(&deserialised); /// ``` -pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Body<'a> { +#[must_use] pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Body<'a> { let mut d: Vec<(&str, Result)>, (u32, &str)>)> = Default::default(); for req_path_result in getresp { @@ -798,7 +798,7 @@ pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Bo .collect(), )); } - d.push((req_path_result.requested_path, Ok(resolved_path_result))) + d.push((req_path_result.requested_path, Ok(resolved_path_result))); } _ => d.push(( @@ -811,7 +811,7 @@ pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Bo usp_get_response(d) } -/// Wraps a Usp Msg into an "no_session_context" USP Record with the specified record information +/// Wraps a Usp Msg into an "`no_session_context`" USP Record with the specified record information /// /// # Arguments /// @@ -823,7 +823,7 @@ pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Bo /// non-payload fields, when integrity protection of non-payload fields is performed /// * `sender_cert` - PEM encoded certificate used to provide the signature in the `mac_signature` /// field, when the payload security mechanism does not provide the mechanism to do so -/// * `msg` - The ProtoBuf encoded USP Msg +/// * `msg` - The `ProtoBuf` encoded USP Msg /// /// # Example /// @@ -840,7 +840,7 @@ pub fn usp_get_response_from_json<'a>(getresp: &[RequestedPathResult<'a>]) -> Bo /// &[], /// ); /// ``` -pub fn usp_no_session_context_record<'a>( +#[must_use] pub fn usp_no_session_context_record<'a>( version: &'a str, to_id: &'a str, from_id: &'a str, @@ -865,7 +865,7 @@ pub fn usp_no_session_context_record<'a>( } } -/// Wraps a Usp Msg into an "session_context" USP Record with the specified record information +/// Wraps a Usp Msg into an "`session_context`" USP Record with the specified record information /// /// # Arguments /// @@ -881,7 +881,7 @@ pub fn usp_no_session_context_record<'a>( /// * `sequence_id` - The sequence number within the context session /// * `expected_id` - The expected next sequence number within the context session /// * `retransmit_id` - The sequence number of the part which is being retransmitted -/// * `msg` - The ProtoBuf encoded USP Msg +/// * `msg` - The `ProtoBuf` encoded USP Msg /// /// # Example /// @@ -905,7 +905,7 @@ pub fn usp_no_session_context_record<'a>( /// ); /// ``` #[allow(clippy::too_many_arguments)] -pub fn usp_session_context_record<'a>( +#[must_use] pub fn usp_session_context_record<'a>( version: &'a str, to_id: &'a str, from_id: &'a str, @@ -965,7 +965,7 @@ pub fn usp_session_context_record<'a>( /// /// let newrecord = usp_mqtt_connect_record("1.3", "doc::to", "doc::from", PayloadSecurity::PLAINTEXT, &[], &[], false, "/topic/doc::from"); /// ``` -pub fn usp_mqtt_connect_record<'a>( +#[must_use] pub fn usp_mqtt_connect_record<'a>( version: &'a str, to_id: &'a str, from_id: &'a str, @@ -997,11 +997,11 @@ pub fn usp_mqtt_connect_record<'a>( } } -/// Creates a body for a USP Msg with a USP NotifyResp response +/// Creates a body for a USP Msg with a USP `NotifyResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the NotifyResp response +/// * `result` - A vector of Result tuples to put into the `NotifyResp` response /// /// # Example /// @@ -1009,9 +1009,9 @@ pub fn usp_mqtt_connect_record<'a>( /// use rusp::usp_generator::usp_notify_response; /// let resp = usp_notify_response("fancy_sub_id"); /// ``` -pub fn usp_notify_response(subscription_id: &'_ str) -> Body<'_> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; +#[must_use] pub const fn usp_notify_response(subscription_id: &'_ str) -> Body<'_> { + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::notify_resp; use crate::usp::NotifyResp; Body { @@ -1027,11 +1027,11 @@ pub fn usp_notify_response(subscription_id: &'_ str) -> Body<'_> { } } -/// Creates a body for a USP Msg with a USP AddResp response +/// Creates a body for a USP Msg with a USP `AddResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the AddResp response +/// * `result` - A vector of Result tuples to put into the `AddResp` response /// /// # Example /// @@ -1043,7 +1043,7 @@ pub fn usp_notify_response(subscription_id: &'_ str) -> Body<'_> { /// ]); /// ``` #[allow(clippy::type_complexity)] -pub fn usp_add_response<'a>( +#[must_use] pub fn usp_add_response<'a>( result: Vec<( &'a str, Result< @@ -1062,8 +1062,8 @@ pub fn usp_add_response<'a>( use crate::usp::mod_AddResp::mod_CreatedObjectResult::OperationStatus; use crate::usp::mod_AddResp::CreatedObjectResult; use crate::usp::mod_AddResp::ParameterError; - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::add_resp; use crate::usp::AddResp; Body { @@ -1112,7 +1112,7 @@ pub fn usp_add_response<'a>( }), } } - }) + }); } addrsp }), @@ -1121,11 +1121,11 @@ pub fn usp_add_response<'a>( } } -/// Creates a body for a USP Msg with a USP DeleteResp response +/// Creates a body for a USP Msg with a USP `DeleteResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the DeleteResp response +/// * `result` - A vector of Result tuples to put into the `DeleteResp` response /// /// # Example /// @@ -1143,13 +1143,13 @@ pub fn usp_delete_response<'a>( Result<(Vec<&'a str>, Vec<(&'a str, u32, &'a str)>), (u32, &'a str)>, )>, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; + use crate::usp::mod_Body::OneOfmsg_body::response; use crate::usp::mod_DeleteResp::mod_DeletedObjectResult::mod_OperationStatus::{ OneOfoper_status, OperationFailure, OperationSuccess, }; use crate::usp::mod_DeleteResp::mod_DeletedObjectResult::OperationStatus; use crate::usp::mod_DeleteResp::{DeletedObjectResult, UnaffectedPathError}; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Response::OneOfresp_type::delete_resp; use crate::usp::DeleteResp; Body { @@ -1197,7 +1197,7 @@ pub fn usp_delete_response<'a>( }), } } - }) + }); } del_rsp }), @@ -1206,11 +1206,11 @@ pub fn usp_delete_response<'a>( } } -/// Creates a body for a USP Msg with a USP GetInstancesResp response +/// Creates a body for a USP Msg with a USP `GetInstancesResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the GetInstancesResp response +/// * `result` - A vector of Result tuples to put into the `GetInstancesResp` response /// /// # Example /// @@ -1222,15 +1222,15 @@ pub fn usp_delete_response<'a>( /// ]); /// ``` #[allow(clippy::type_complexity)] -pub fn usp_get_instances_response<'a>( +#[must_use] pub fn usp_get_instances_response<'a>( result: Vec<( &'a str, Result)>, (u32, &'a str)>, )>, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; + use crate::usp::mod_Body::OneOfmsg_body::response; use crate::usp::mod_GetInstancesResp::{CurrInstance, RequestedPathResult}; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Response::OneOfresp_type::get_instances_resp; use crate::usp::GetInstancesResp; Body { @@ -1269,7 +1269,7 @@ pub fn usp_get_instances_response<'a>( err_msg: Cow::Borrowed(err_msg), curr_insts: Vec::default(), }, - }) + }); } get_instances_rsp }), @@ -1278,7 +1278,7 @@ pub fn usp_get_instances_response<'a>( } } -/// Creates a body for a USP Msg with a USP GetSupportedProtocolResp response +/// Creates a body for a USP Msg with a USP `GetSupportedProtocolResp` response /// /// # Arguments /// @@ -1290,9 +1290,9 @@ pub fn usp_get_instances_response<'a>( /// use rusp::usp_generator::usp_get_supported_protocol_response; /// let resp = usp_get_supported_protocol_response("1.1"); /// ``` -pub fn usp_get_supported_protocol_response(result: &str) -> Body { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; +#[must_use] pub const fn usp_get_supported_protocol_response(result: &str) -> Body { + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::get_supported_protocol_resp; use crate::usp::GetSupportedProtocolResp; Body { @@ -1319,7 +1319,7 @@ pub enum OperationResponse<'a> { Error(u32, &'a str), } -/// Creates a body for a USP Msg with a USP OperateResp response +/// Creates a body for a USP Msg with a USP `OperateResp` response /// /// # Arguments /// @@ -1338,13 +1338,13 @@ pub enum OperationResponse<'a> { /// ]); /// ``` #[allow(clippy::type_complexity)] -pub fn usp_operate_response<'a>(result: Vec<(&'a str, OperationResponse<'a>)>) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; +#[must_use] pub fn usp_operate_response<'a>(result: Vec<(&'a str, OperationResponse<'a>)>) -> Body<'a> { + use crate::usp::mod_Body::OneOfmsg_body::response; use crate::usp::mod_OperateResp::mod_OperationResult::{ CommandFailure, OneOfoperation_resp, OutputArgs, }; use crate::usp::mod_OperateResp::OperationResult; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Response::OneOfresp_type::operate_resp; use crate::usp::OperateResp; Body { @@ -1384,7 +1384,7 @@ pub fn usp_operate_response<'a>(result: Vec<(&'a str, OperationResponse<'a>)>) - operation_resp: OneOfoperation_resp::cmd_failure(cmd_fail), } } - }) + }); } operate_rsp }), @@ -1393,11 +1393,11 @@ pub fn usp_operate_response<'a>(result: Vec<(&'a str, OperationResponse<'a>)>) - } } -/// Creates a body for a USP Msg with a USP SetResp response +/// Creates a body for a USP Msg with a USP `SetResp` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the SetResp response +/// * `result` - A vector of Result tuples to put into the `SetResp` response /// /// # Example /// @@ -1409,7 +1409,7 @@ pub fn usp_operate_response<'a>(result: Vec<(&'a str, OperationResponse<'a>)>) - /// ]); /// ``` #[allow(clippy::type_complexity)] -pub fn usp_set_response<'a>( +#[must_use] pub fn usp_set_response<'a>( result: Vec<( &'a str, Result< @@ -1422,8 +1422,8 @@ pub fn usp_set_response<'a>( >, )>, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Body::OneOfmsg_body::response; + use crate::usp::mod_Response::OneOfresp_type::set_resp; use crate::usp::mod_SetResp::mod_UpdatedObjectResult::mod_OperationStatus::{ OneOfoper_status, OperationFailure, OperationSuccess, }; @@ -1503,7 +1503,7 @@ pub fn usp_set_response<'a>( oper_status: Some(op_status), } } - }) + }); } setrsp }), @@ -1512,11 +1512,11 @@ pub fn usp_set_response<'a>( } } -/// Creates a body for a USP Msg with a USP GetSupportedDM response +/// Creates a body for a USP Msg with a USP `GetSupportedDM` response /// /// # Arguments /// -/// * `result` - A vector of Result tuples to put into the GetSupportedDM response +/// * `result` - A vector of Result tuples to put into the `GetSupportedDM` response /// /// # Example /// @@ -1566,12 +1566,12 @@ pub fn usp_get_supported_dm_response<'a>( >, )>, ) -> Body<'a> { - use crate::usp::mod_Body::OneOfmsg_body::*; + use crate::usp::mod_Body::OneOfmsg_body::response; use crate::usp::mod_GetSupportedDMResp::{ RequestedObjectResult, SupportedCommandResult, SupportedEventResult, SupportedObjectResult, SupportedParamResult, }; - use crate::usp::mod_Response::OneOfresp_type::*; + use crate::usp::mod_Response::OneOfresp_type::get_supported_dm_resp; use crate::usp::GetSupportedDMResp; Body { @@ -1677,7 +1677,7 @@ pub fn usp_get_supported_dm_response<'a>( data_model_inst_uri: Cow::Borrowed(uri), supported_objs: Vec::default(), }, - }) + }); } supported_dm_rsp }), diff --git a/src/usp_json.rs b/src/usp_json.rs index 9d68add..3aa440f 100644 --- a/src/usp_json.rs +++ b/src/usp_json.rs @@ -1,7 +1,7 @@ //! An implementation of serde de-/serialisers for USP data structures generated by quick-protobuf -use crate::usp::*; -use crate::usp_record::*; +use crate::usp::{Add, AddResp, Body, Delete, DeleteResp, Deregister, DeregisterResp, Error, Get, GetInstances, GetInstancesResp, GetResp, GetSupportedDM, GetSupportedDMResp, GetSupportedProtocol, GetSupportedProtocolResp, Header, Msg, Notify, NotifyResp, Operate, OperateResp, Register, RegisterResp, Request, Response, Set, SetResp, mod_Add, mod_AddResp, mod_Body, mod_DeleteResp, mod_DeregisterResp, mod_Error, mod_GetInstancesResp, mod_GetResp, mod_GetSupportedDMResp, mod_Header, mod_Notify, mod_OperateResp, mod_Register, mod_RegisterResp, mod_Request, mod_Response, mod_Set, mod_SetResp}; +use crate::usp_record::{DisconnectRecord, MQTTConnectRecord, Record, STOMPConnectRecord, SessionContextRecord, WebSocketConnectRecord, mod_MQTTConnectRecord, mod_Record, mod_STOMPConnectRecord, mod_SessionContextRecord}; use anyhow::Context; use serde::ser::{Serialize, SerializeStruct, Serializer}; @@ -11,7 +11,7 @@ impl Serialize for Record<'_> { where S: Serializer, { - use crate::usp_decoder::*; + use crate::usp_decoder::try_decode_msg; use mod_Record::OneOfrecord_type::{ disconnect, mqtt_connect, no_session_context, session_context, stomp_connect, websocket_connect, @@ -35,7 +35,7 @@ impl Serialize for Record<'_> { "{:?}", msg.context("Interpreting USP Record payload as USP Msg") .unwrap_err() - )))? + )))?; } } session_context(context) => { @@ -59,7 +59,7 @@ impl Serialize for mod_Record::PayloadSecurity { where S: Serializer, { - use mod_Record::PayloadSecurity::*; + use mod_Record::PayloadSecurity::{PLAINTEXT, TLS12}; match *self { PLAINTEXT => serializer.serialize_unit_variant("PayloadSecurity", 0, "PLAINTEXT"), TLS12 => serializer.serialize_unit_variant("PayloadSecurity", 1, "TLS12"), @@ -89,7 +89,7 @@ impl Serialize for mod_SessionContextRecord::PayloadSARState { where S: Serializer, { - use mod_SessionContextRecord::PayloadSARState::*; + use mod_SessionContextRecord::PayloadSARState::{BEGIN, COMPLETE, INPROCESS, NONE}; match *self { NONE => serializer.serialize_unit_variant("PayloadSARState", 0, "NONE"), BEGIN => serializer.serialize_unit_variant("PayloadSARState", 1, "BEGIN"), @@ -125,7 +125,7 @@ impl Serialize for mod_MQTTConnectRecord::MQTTVersion { where S: Serializer, { - use mod_MQTTConnectRecord::MQTTVersion::*; + use mod_MQTTConnectRecord::MQTTVersion::{V3_1_1, V5}; let (value, index) = match self { V3_1_1 => ("V3_1_1", 0), @@ -152,7 +152,7 @@ impl Serialize for mod_STOMPConnectRecord::STOMPVersion { where S: Serializer, { - use mod_STOMPConnectRecord::STOMPVersion::*; + use mod_STOMPConnectRecord::STOMPVersion::V1_2; let (value, index) = match self { V1_2 => ("V1_2", 0), @@ -202,7 +202,7 @@ impl Serialize for mod_Header::MsgType { where S: Serializer, { - use mod_Header::MsgType::*; + use mod_Header::MsgType::{ADD, ADD_RESP, DELETE, DELETE_RESP, DEREGISTER, DEREGISTER_RESP, ERROR, GET, GET_INSTANCES, GET_INSTANCES_RESP, GET_RESP, GET_SUPPORTED_DM, GET_SUPPORTED_DM_RESP, GET_SUPPORTED_PROTO, GET_SUPPORTED_PROTO_RESP, NOTIFY, NOTIFY_RESP, OPERATE, OPERATE_RESP, REGISTER, REGISTER_RESP, SET, SET_RESP}; match *self { ERROR => serializer.serialize_unit_variant("MsgType", *self as u32, "ERROR"), @@ -261,7 +261,7 @@ impl Serialize for Body<'_> { where S: Serializer, { - use mod_Body::OneOfmsg_body::*; + use mod_Body::OneOfmsg_body::{None, error, request, response}; let mut state = serializer.serialize_struct("Body", 1)?; match self.msg_body { @@ -279,7 +279,7 @@ impl Serialize for Request<'_> { where S: Serializer, { - use mod_Request::OneOfreq_type::*; + use mod_Request::OneOfreq_type::{None, add, delete, deregister, get, get_instances, get_supported_dm, get_supported_protocol, notify, operate, register, set}; let mut state = serializer.serialize_struct("Request", 1)?; match self.req_type { @@ -305,7 +305,7 @@ impl Serialize for Response<'_> { where S: Serializer, { - use mod_Response::OneOfresp_type::*; + use mod_Response::OneOfresp_type::{None, add_resp, delete_resp, deregister_resp, get_instances_resp, get_resp, get_supported_dm_resp, get_supported_protocol_resp, notify_resp, operate_resp, register_resp, set_resp}; let mut state = serializer.serialize_struct("Response", 1)?; match self.resp_type { @@ -318,7 +318,7 @@ impl Serialize for Response<'_> { operate_resp(ref m) => state.serialize_field("OperateResp", &m)?, notify_resp(ref m) => state.serialize_field("NotifyResp", &m)?, get_supported_protocol_resp(ref m) => { - state.serialize_field("GetSupportedProtocolResp", &m)? + state.serialize_field("GetSupportedProtocolResp", &m)?; } register_resp(ref m) => state.serialize_field("RegisterResp", &m)?, deregister_resp(ref m) => state.serialize_field("DeregisterResp", &m)?, @@ -428,7 +428,7 @@ impl Serialize for Notify<'_> { where S: Serializer, { - use mod_Notify::OneOfnotification::*; + use mod_Notify::OneOfnotification::{None, event, obj_creation, obj_deletion, on_board_req, oper_complete, value_change}; let mut state = serializer.serialize_struct("Notify", 3)?; state.serialize_field("subscription_id", &self.subscription_id)?; @@ -535,7 +535,7 @@ impl Serialize for mod_Notify::OperationComplete<'_> { where S: Serializer, { - use mod_Notify::mod_OperationComplete::OneOfoperation_resp::*; + use mod_Notify::mod_OperationComplete::OneOfoperation_resp::{None, cmd_failure, req_output_args}; let mut state = serializer.serialize_struct("OperationComplete", 4)?; state.serialize_field("command_name", &self.command_name)?; @@ -751,7 +751,7 @@ impl Serialize for mod_GetSupportedDMResp::ObjAccessType { where S: Serializer, { - use mod_GetSupportedDMResp::ObjAccessType::*; + use mod_GetSupportedDMResp::ObjAccessType::{OBJ_ADD_DELETE, OBJ_ADD_ONLY, OBJ_DELETE_ONLY, OBJ_READ_ONLY}; match *self { OBJ_READ_ONLY => serializer.serialize_unit_variant("ObjAccessType", 0, "OBJ_READ_ONLY"), @@ -785,7 +785,7 @@ impl Serialize for mod_GetSupportedDMResp::CmdType { where S: Serializer, { - use mod_GetSupportedDMResp::CmdType::*; + use mod_GetSupportedDMResp::CmdType::{CMD_ASYNC, CMD_SYNC, CMD_UNKNOWN}; let (value, index) = match self { CMD_UNKNOWN => ("CMD_UNKNOWN", 0), @@ -827,7 +827,7 @@ impl Serialize for mod_GetSupportedDMResp::ParamValueType { where S: Serializer, { - use mod_GetSupportedDMResp::ParamValueType::*; + use mod_GetSupportedDMResp::ParamValueType::{PARAM_BASE_64, PARAM_BOOLEAN, PARAM_DATE_TIME, PARAM_DECIMAL, PARAM_HEX_BINARY, PARAM_INT, PARAM_LONG, PARAM_STRING, PARAM_UNKNOWN, PARAM_UNSIGNED_INT, PARAM_UNSIGNED_LONG}; let (value, index) = match self { PARAM_UNKNOWN => ("PARAM_UNKNOWN", 0), @@ -862,7 +862,7 @@ impl Serialize for mod_GetSupportedDMResp::ValueChangeType { where S: Serializer, { - use mod_GetSupportedDMResp::ValueChangeType::*; + use mod_GetSupportedDMResp::ValueChangeType::{VALUE_CHANGE_ALLOWED, VALUE_CHANGE_UNKNOWN, VALUE_CHANGE_WILL_IGNORE}; let (value, index) = match self { VALUE_CHANGE_UNKNOWN => ("VALUE_CHANGE_UNKNOWN", 0), @@ -878,7 +878,7 @@ impl Serialize for mod_GetSupportedDMResp::ParamAccessType { where S: Serializer, { - use mod_GetSupportedDMResp::ParamAccessType::*; + use mod_GetSupportedDMResp::ParamAccessType::{PARAM_READ_ONLY, PARAM_READ_WRITE, PARAM_WRITE_ONLY}; match *self { PARAM_READ_ONLY => { @@ -959,7 +959,7 @@ impl Serialize for mod_SetResp::mod_UpdatedObjectResult::OperationStatus<'_> { where S: Serializer, { - use mod_SetResp::mod_UpdatedObjectResult::mod_OperationStatus::OneOfoper_status::*; + use mod_SetResp::mod_UpdatedObjectResult::mod_OperationStatus::OneOfoper_status::{None, oper_failure, oper_success}; let mut state = serializer.serialize_struct("OperationStatus", 1)?; match &self.oper_status { @@ -1051,7 +1051,7 @@ impl Serialize for mod_OperateResp::OperationResult<'_> { where S: Serializer, { - use mod_OperateResp::mod_OperationResult::OneOfoperation_resp::*; + use mod_OperateResp::mod_OperationResult::OneOfoperation_resp::{None, cmd_failure, req_obj_path, req_output_args}; let mut state = serializer.serialize_struct("OperationResult", 2)?; state.serialize_field("executed_command", &self.executed_command)?; @@ -1143,7 +1143,7 @@ impl Serialize for mod_RegisterResp::mod_RegisteredPathResult::OperationStatus<' where S: Serializer, { - use mod_RegisterResp::mod_RegisteredPathResult::mod_OperationStatus::OneOfoper_status::*; + use mod_RegisterResp::mod_RegisteredPathResult::mod_OperationStatus::OneOfoper_status::{None, oper_failure, oper_success}; let mut state = serializer.serialize_struct("OperationStatus", 1)?; match &self.oper_status { @@ -1212,7 +1212,7 @@ impl Serialize for mod_DeregisterResp::mod_DeregisteredPathResult::OperationStat where S: Serializer, { - use mod_DeregisterResp::mod_DeregisteredPathResult::mod_OperationStatus::OneOfoper_status::*; + use mod_DeregisterResp::mod_DeregisteredPathResult::mod_OperationStatus::OneOfoper_status::{None, oper_failure, oper_success}; let mut state = serializer.serialize_struct("OperationStatus", 1)?; match &self.oper_status { @@ -1270,7 +1270,7 @@ impl Serialize for mod_DeleteResp::mod_DeletedObjectResult::OperationStatus<'_> where S: Serializer, { - use mod_DeleteResp::mod_DeletedObjectResult::mod_OperationStatus::OneOfoper_status::*; + use mod_DeleteResp::mod_DeletedObjectResult::mod_OperationStatus::OneOfoper_status::{None, oper_failure, oper_success}; let mut state = serializer.serialize_struct("OperationStatus", 1)?; match &self.oper_status { @@ -1379,7 +1379,7 @@ impl Serialize for mod_AddResp::mod_CreatedObjectResult::OperationStatus<'_> { where S: Serializer, { - use mod_AddResp::mod_CreatedObjectResult::mod_OperationStatus::OneOfoper_status::*; + use mod_AddResp::mod_CreatedObjectResult::mod_OperationStatus::OneOfoper_status::{None, oper_failure, oper_success}; let mut state = serializer.serialize_struct("OperationStatus", 1)?; match self.oper_status { oper_success(ref m) => state.serialize_field("oper_success", m)?, diff --git a/src/usp_record.rs b/src/usp_record.rs index 34724a7..6d54c97 100644 --- a/src/usp_record.rs +++ b/src/usp_record.rs @@ -11,8 +11,8 @@ use std::borrow::Cow; use quick_protobuf::{MessageInfo, MessageRead, MessageWrite, BytesReader, Writer, WriterBackend, Result}; -use quick_protobuf::sizeofs::*; -use super::*; +use quick_protobuf::sizeofs::{sizeof_len, sizeof_varint}; +use super::usp_record; #[allow(clippy::derive_partial_eq_without_eq)] #[derive(Debug, Default, PartialEq, Clone)] @@ -93,7 +93,7 @@ impl<'a> MessageWrite for Record<'a> { pub mod mod_Record { -use super::*; +use super::usp_record; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum PayloadSecurity { @@ -103,15 +103,15 @@ pub enum PayloadSecurity { impl Default for PayloadSecurity { fn default() -> Self { - PayloadSecurity::PLAINTEXT + Self::PLAINTEXT } } impl From for PayloadSecurity { fn from(i: i32) -> Self { match i { - 0 => PayloadSecurity::PLAINTEXT, - 1 => PayloadSecurity::TLS12, + 0 => Self::PLAINTEXT, + 1 => Self::TLS12, _ => Self::default(), } } @@ -120,8 +120,8 @@ impl From for PayloadSecurity { impl<'a> From<&'a str> for PayloadSecurity { fn from(s: &'a str) -> Self { match s { - "PLAINTEXT" => PayloadSecurity::PLAINTEXT, - "TLS12" => PayloadSecurity::TLS12, + "PLAINTEXT" => Self::PLAINTEXT, + "TLS12" => Self::TLS12, _ => Self::default(), } } @@ -248,17 +248,17 @@ pub enum PayloadSARState { impl Default for PayloadSARState { fn default() -> Self { - PayloadSARState::NONE + Self::NONE } } impl From for PayloadSARState { fn from(i: i32) -> Self { match i { - 0 => PayloadSARState::NONE, - 1 => PayloadSARState::BEGIN, - 2 => PayloadSARState::INPROCESS, - 3 => PayloadSARState::COMPLETE, + 0 => Self::NONE, + 1 => Self::BEGIN, + 2 => Self::INPROCESS, + 3 => Self::COMPLETE, _ => Self::default(), } } @@ -267,10 +267,10 @@ impl From for PayloadSARState { impl<'a> From<&'a str> for PayloadSARState { fn from(s: &'a str) -> Self { match s { - "NONE" => PayloadSARState::NONE, - "BEGIN" => PayloadSARState::BEGIN, - "INPROCESS" => PayloadSARState::INPROCESS, - "COMPLETE" => PayloadSARState::COMPLETE, + "NONE" => Self::NONE, + "BEGIN" => Self::BEGIN, + "INPROCESS" => Self::INPROCESS, + "COMPLETE" => Self::COMPLETE, _ => Self::default(), } } @@ -338,15 +338,15 @@ pub enum MQTTVersion { impl Default for MQTTVersion { fn default() -> Self { - MQTTVersion::V3_1_1 + Self::V3_1_1 } } impl From for MQTTVersion { fn from(i: i32) -> Self { match i { - 0 => MQTTVersion::V3_1_1, - 1 => MQTTVersion::V5, + 0 => Self::V3_1_1, + 1 => Self::V5, _ => Self::default(), } } @@ -355,8 +355,8 @@ impl From for MQTTVersion { impl<'a> From<&'a str> for MQTTVersion { fn from(s: &'a str) -> Self { match s { - "V3_1_1" => MQTTVersion::V3_1_1, - "V5" => MQTTVersion::V5, + "V3_1_1" => Self::V3_1_1, + "V5" => Self::V5, _ => Self::default(), } } @@ -410,14 +410,14 @@ pub enum STOMPVersion { impl Default for STOMPVersion { fn default() -> Self { - STOMPVersion::V1_2 + Self::V1_2 } } impl From for STOMPVersion { fn from(i: i32) -> Self { match i { - 0 => STOMPVersion::V1_2, + 0 => Self::V1_2, _ => Self::default(), } } @@ -426,7 +426,7 @@ impl From for STOMPVersion { impl<'a> From<&'a str> for STOMPVersion { fn from(s: &'a str) -> Self { match s { - "V1_2" => STOMPVersion::V1_2, + "V1_2" => Self::V1_2, _ => Self::default(), } } diff --git a/src/usp_types.rs b/src/usp_types.rs index ccacf72..e15d0f7 100644 --- a/src/usp_types.rs +++ b/src/usp_types.rs @@ -15,7 +15,7 @@ impl Default for OperateResponse { #[derive(Clone, Debug, PartialEq, Eq)] pub enum NotifyType { - /// USP OnBoardRequest notification + /// USP `OnBoardRequest` notification OnBoardRequest { /// The OUI associated with the manufacturer of the device oui: String, @@ -29,7 +29,7 @@ pub enum NotifyType { /// A comma separated list of supported USP versions agent_supported_protocol_versions: String, }, - /// USP ValueChange notification + /// USP `ValueChange` notification ValueChange { /// The path of the changed parameter param_path: String, @@ -45,20 +45,20 @@ pub enum NotifyType { /// A stringified JSON object containing the output arguments of the USP Event params: HashMap, }, - /// USP ObjectCreation notification + /// USP `ObjectCreation` notification ObjectCreation { /// The path of the created object obj_path: String, - /// A stringified JSON object containing the unique_keys and values of the created Object + /// A stringified JSON object containing the `unique_keys` and values of the created Object unique_keys: HashMap, }, - /// USP ObjectDeletion notification + /// USP `ObjectDeletion` notification ObjectDeletion { /// The path of the deleted object obj_path: String, }, - /// USP OperationComplete notification + /// USP `OperationComplete` notification OperationComplete { /// The path of the operation object obj_path: String, @@ -85,12 +85,12 @@ pub enum PayloadSARState { impl From for crate::usp_record::mod_SessionContextRecord::PayloadSARState { fn from(s: PayloadSARState) -> Self { - use crate::usp_record::mod_SessionContextRecord::PayloadSARState as PBPayloadSARState; + match s { - PayloadSARState::NONE => PBPayloadSARState::NONE, - PayloadSARState::BEGIN => PBPayloadSARState::BEGIN, - PayloadSARState::INPROCESS => PBPayloadSARState::INPROCESS, - PayloadSARState::COMPLETE => PBPayloadSARState::COMPLETE, + PayloadSARState::NONE => Self::NONE, + PayloadSARState::BEGIN => Self::BEGIN, + PayloadSARState::INPROCESS => Self::INPROCESS, + PayloadSARState::COMPLETE => Self::COMPLETE, } } }