diff --git a/Cargo.lock b/Cargo.lock index b3788150..823688eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -286,7 +286,7 @@ version = "3.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" dependencies = [ - "heck 0.4.0", + "heck", "proc-macro-error", "proc-macro2", "quote", @@ -299,7 +299,7 @@ version = "4.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0177313f9f02afc995627906bbd8967e2be069f5261954222dac78290c2b9014" dependencies = [ - "heck 0.4.0", + "heck", "proc-macro-error", "proc-macro2", "quote", @@ -590,15 +590,6 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - [[package]] name = "heck" version = "0.4.0" @@ -889,14 +880,14 @@ checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "oo-bindgen" -version = "0.6.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c34c9ff5b3e71d13b30394094d2423fa0d8755c1947ee6e160e6cf18a0e6d8e" +checksum = "51dcf81e8585d49764404a4a8eece2a1aa77bc1c19644baf6371694c6c7f3dd3" dependencies = [ "backtrace", "clap 4.0.22", "dunce", - "heck 0.3.3", + "heck", "lazy_static", "platforms", "regex", @@ -1149,6 +1140,7 @@ dependencies = [ "oo-bindgen", "rodbus", "rodbus-schema", + "sfio-promise", "sfio-tokio-ffi", "sfio-tracing-ffi", "tokio", @@ -1310,11 +1302,17 @@ dependencies = [ "winapi", ] +[[package]] +name = "sfio-promise" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91547be5cac1551a6401a7cfa571524bbcb4d9d818b2756cbe3012b48cc79aaf" + [[package]] name = "sfio-tokio-ffi" -version = "0.5.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3011decee9900ac6162a077ba2a662a60082772a691ae50f2cc6759b8ea4d90" +checksum = "7264a1340f2fa1d79e749b85c1f9965dedbd811d1dfb32a6b354e8253cad2286" dependencies = [ "oo-bindgen", ] @@ -1330,9 +1328,9 @@ dependencies = [ [[package]] name = "sfio-tracing-ffi" -version = "0.5.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e582bebc03d7f2e8ebc86f0d44daa75ac6340b7a58d0da29b475aeddd6ac24f" +checksum = "94955ac2db413b6f32297e862581db2c05f6312881939393f4b68f173a8be8b4" dependencies = [ "oo-bindgen", ] @@ -1685,12 +1683,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" -[[package]] -name = "unicode-segmentation" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a" - [[package]] name = "unicode-width" version = "0.1.10" diff --git a/dep_config.json b/dep_config.json index 0d9d725e..c9332baf 100644 --- a/dep_config.json +++ b/dep_config.json @@ -51,6 +51,9 @@ "scursor": { "url": "https://github.com/stepfunc/scursor" }, + "sfio-promise": { + "url": "https://github.com/stepfunc/promise" + }, "sfio-tokio-ffi": { "url": "https://github.com/stepfunc/tokio-ffi" }, diff --git a/ffi/bindings/c/client_example.c b/ffi/bindings/c/client_example.c index 6aabe61d..a74f4ba9 100644 --- a/ffi/bindings/c/client_example.c +++ b/ffi/bindings/c/client_example.c @@ -64,14 +64,18 @@ void on_port_state_change(rodbus_port_state_t state, void *ctx) rodbus_client_state_listener_t get_client_listener() { - return rodbus_client_state_listener_init(on_client_state_change, NULL, NULL); + return (rodbus_client_state_listener_t) { + .on_change = &on_client_state_change, + }; } -rodbus_port_state_listener_t get_port_listener() -{ - return rodbus_port_state_listener_init(on_port_state_change, NULL, NULL); +rodbus_port_state_listener_t get_port_listener(){ + return (rodbus_port_state_listener_t) { + .on_change = &on_port_state_change, + }; } + run_channel(rodbus_client_channel_t* channel) { // ANCHOR: enable_channel @@ -93,26 +97,20 @@ run_channel(rodbus_client_channel_t* channel) // ANCHOR_END: address_range // ANCHOR: bit_read_callback_init - rodbus_bit_read_callback_t bit_callback = rodbus_bit_read_callback_init( - on_read_bits_complete, // Success callback - on_read_bits_failure, // Failure callback - NULL, // Destroy callback - NULL // Callback context - ); + rodbus_bit_read_callback_t bit_callback = { + .on_complete = &on_read_bits_complete, + .on_failure = &on_read_bits_failure, + }; // ANCHOR_END: bit_read_callback_init - rodbus_register_read_callback_t register_callback = rodbus_register_read_callback_init( - on_read_registers_complete, // Success callback - on_read_registers_failure, // Failure callback - NULL, // Destroy callback - NULL // Callback context - ); + rodbus_register_read_callback_t register_callback = { + .on_complete = on_read_registers_complete, // Success callback + .on_failure = on_read_registers_failure, // Failure callback + }; // ANCHOR: write_callback_init - rodbus_write_callback_t write_callback = rodbus_write_callback_init( - on_write_complete, // Success callback - on_write_failure, // Failure callback - NULL, // Destroy callback - NULL // Callback context - ); + rodbus_write_callback_t write_callback = { + .on_complete = on_write_complete, + .on_failure = on_write_failure, + }; /// ANCHOR_END: write_callback_init char cbuf[10]; @@ -304,7 +302,7 @@ int main(int argc, char* argv[]) { // ANCHOR: logging_init // initialize logging with the default configuration - rodbus_logger_t logger = rodbus_logger_init(&on_log_message, NULL, NULL); + rodbus_logger_t logger = {.on_message = on_log_message}; rodbus_configure_logging(rodbus_logging_config_init(), logger); // ANCHOR_END: logging_init diff --git a/ffi/bindings/c/server_example.c b/ffi/bindings/c/server_example.c index 2f99004d..e62eac45 100644 --- a/ffi/bindings/c/server_example.c +++ b/ffi/bindings/c/server_example.c @@ -154,17 +154,20 @@ int run_server(rodbus_server_t* server) } else if (strcmp(cbuf, "uc\n") == 0) { // ANCHOR: update_coil - rodbus_server_update_database(server, 1, rodbus_database_callback_init(update_coil, NULL, &state)); + rodbus_server_update_database(server, 1, (rodbus_database_callback_t) { + .callback = update_coil, + .ctx = &state, + }); // ANCHOR_END: update_coil } else if (strcmp(cbuf, "udi\n") == 0) { - rodbus_server_update_database(server, 1, rodbus_database_callback_init(update_discrete_input, NULL, &state)); + rodbus_server_update_database(server, 1, (rodbus_database_callback_t){.callback = update_discrete_input, .ctx = &state}); } else if (strcmp(cbuf, "uhr\n") == 0) { - rodbus_server_update_database(server, 1, rodbus_database_callback_init(update_holding_register, NULL, &state)); + rodbus_server_update_database(server, 1, (rodbus_database_callback_t){.callback = update_holding_register, .ctx = &state}); } else if (strcmp(cbuf, "uir\n") == 0) { - rodbus_server_update_database(server, 1, rodbus_database_callback_init(update_input_register, NULL, &state)); + rodbus_server_update_database(server, 1, (rodbus_database_callback_t){.callback = update_input_register, .ctx = &state}); } else { printf("Unknown command\n"); @@ -179,14 +182,17 @@ int run_server(rodbus_server_t* server) rodbus_device_map_t* build_device_map() { // ANCHOR: device_map_init - rodbus_write_handler_t write_handler = - rodbus_write_handler_init(&on_write_single_coil, &on_write_single_register, &on_write_multiple_coils, &on_write_multiple_registers, NULL, NULL); - + rodbus_write_handler_t write_handler = { + .write_single_coil = on_write_single_coil, + .write_single_register = on_write_single_register, + .write_multiple_coils = on_write_multiple_coils, + .write_multiple_registers = on_write_multiple_registers, + }; rodbus_device_map_t* map = rodbus_device_map_create(); rodbus_device_map_add_endpoint(map, 1, // Unit ID write_handler, // Handler for write requests - rodbus_database_callback_init(configure_db, NULL, NULL) // Callback for the initial state of the database + (rodbus_database_callback_t){.callback = configure_db } // Callback for the initial state of the database ); // ANCHOR_END: device_map_init @@ -234,11 +240,16 @@ int run_rtu_channel(rodbus_runtime_t* runtime) rodbus_authorization_handler_t get_auth_handler() { // ANCHOR: auth_handler_init - rodbus_authorization_handler_t auth_handler = rodbus_authorization_handler_init( - &auth_read, &auth_read, &auth_read, &auth_read, - &auth_single_write, &auth_single_write, &auth_multiple_writes, &auth_multiple_writes, - NULL, NULL - ); + rodbus_authorization_handler_t auth_handler = { + .read_coils = auth_read, + .read_discrete_inputs = auth_read, + .read_holding_registers = auth_read, + .read_input_registers = auth_read, + .write_single_coil = auth_single_write, + .write_single_register = auth_single_write, + .write_multiple_coils = auth_multiple_writes, + .write_multiple_registers = auth_multiple_writes, + }; // ANCHOR_END: auth_handler_init return auth_handler; @@ -324,7 +335,7 @@ int create_and_run_channel(int argc, char *argv[], rodbus_runtime_t *runtime) int main(int argc, char* argv[]) { // initialize logging with the default configuration - rodbus_logger_t logger = rodbus_logger_init(&on_log_message, NULL, NULL); + rodbus_logger_t logger = {.on_message = on_log_message}; rodbus_configure_logging(rodbus_logging_config_init(), logger); // Create runtime diff --git a/ffi/rodbus-bindings/Cargo.toml b/ffi/rodbus-bindings/Cargo.toml index 5d128070..b24f72a4 100644 --- a/ffi/rodbus-bindings/Cargo.toml +++ b/ffi/rodbus-bindings/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/stepfunc/rodbus" readme = "../README.md" [dependencies] -oo-bindgen = "0.6" +oo-bindgen = "0.8" rodbus-schema = { path = "../rodbus-schema" } tracing = "^0.1" tracing-subscriber = "^0.3" diff --git a/ffi/rodbus-ffi-java/Cargo.toml b/ffi/rodbus-ffi-java/Cargo.toml index e9f28768..0b1f5d06 100644 --- a/ffi/rodbus-ffi-java/Cargo.toml +++ b/ffi/rodbus-ffi-java/Cargo.toml @@ -19,4 +19,4 @@ tls = ["rodbus-ffi/tls"] [build-dependencies] rodbus-schema = { path = "../rodbus-schema" } -oo-bindgen = "0.6" \ No newline at end of file +oo-bindgen = "0.8" \ No newline at end of file diff --git a/ffi/rodbus-ffi-java/build.rs b/ffi/rodbus-ffi-java/build.rs index c7d01513..77b22739 100644 --- a/ffi/rodbus-ffi-java/build.rs +++ b/ffi/rodbus-ffi-java/build.rs @@ -14,7 +14,7 @@ fn main() { match rodbus_schema::build_lib() { Err(err) => { - eprintln!("{}", err); + eprintln!("{err}"); std::process::exit(-1); } Ok(lib) => { diff --git a/ffi/rodbus-ffi-java/src/lib.rs b/ffi/rodbus-ffi-java/src/lib.rs index 12948c99..bcc50ec0 100644 --- a/ffi/rodbus-ffi-java/src/lib.rs +++ b/ffi/rodbus-ffi-java/src/lib.rs @@ -6,6 +6,7 @@ clippy::let_unit_value, clippy::needless_return, clippy::not_unsafe_ptr_arg_deref, + clippy::uninlined_format_args, unused_variables, dead_code )] diff --git a/ffi/rodbus-ffi/Cargo.toml b/ffi/rodbus-ffi/Cargo.toml index 665839dc..d454ea63 100644 --- a/ffi/rodbus-ffi/Cargo.toml +++ b/ffi/rodbus-ffi/Cargo.toml @@ -20,12 +20,13 @@ tracing-subscriber = "0.2" rodbus = { path = "../../rodbus", default-features = false } tokio = { version = "1.5", features = ["rt-multi-thread"]} num_cpus = "1" +sfio-promise = "0.2" [build-dependencies] rodbus-schema = { path = "../rodbus-schema" } -oo-bindgen = "0.6" -sfio-tracing-ffi = "0.5" -sfio-tokio-ffi = "0.5" +oo-bindgen = "0.8" +sfio-tracing-ffi = "0.8" +sfio-tokio-ffi = "0.8" [features] diff --git a/ffi/rodbus-ffi/build.rs b/ffi/rodbus-ffi/build.rs index c1d04421..5e30e12b 100644 --- a/ffi/rodbus-ffi/build.rs +++ b/ffi/rodbus-ffi/build.rs @@ -29,7 +29,7 @@ fn main() { oo_bindgen::backend::rust::generate_ffi(&lib).unwrap(); } Err(err) => { - eprintln!("rodbus model error: {}", err); + eprintln!("rodbus model error: {err}"); std::process::exit(-1); } }; diff --git a/ffi/rodbus-ffi/src/client.rs b/ffi/rodbus-ffi/src/client.rs index 89a7a774..49151d60 100644 --- a/ffi/rodbus-ffi/src/client.rs +++ b/ffi/rodbus-ffi/src/client.rs @@ -33,7 +33,7 @@ pub(crate) unsafe fn client_channel_create_tcp( let runtime = runtime.as_ref().ok_or(ffi::ParamError::NullParameter)?; // enter the runtime context so we can spawn - let _enter = runtime.inner.enter(); + let _enter = runtime.enter(); let channel = rodbus::client::spawn_tcp_client_task( get_host_addr(host, port)?, @@ -75,7 +75,7 @@ pub(crate) unsafe fn client_channel_create_rtu( let runtime = runtime.as_ref().ok_or(ffi::ParamError::NullParameter)?; // enter the runtime context so we can spawn - let _enter = runtime.inner.enter(); + let _enter = runtime.enter(); let channel = rodbus::client::spawn_rtu_client_task( &path.to_string_lossy(), @@ -144,7 +144,7 @@ pub(crate) unsafe fn client_channel_create_tls( let host_addr = get_host_addr(host, port)?; // enter the runtime context so we can spawn - let _enter = runtime.inner.enter(); + let _enter = runtime.enter(); let channel = rodbus::client::spawn_tls_client_task( host_addr, @@ -175,12 +175,14 @@ pub(crate) unsafe fn client_channel_read_coils( ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let range = AddressRange::try_from(range.start, range.count)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.read_coils(range, callback).await })?; + channel.runtime.spawn(async move { + session + .read_coils(range, |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -193,12 +195,14 @@ pub(crate) unsafe fn client_channel_read_discrete_inputs( ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let range = AddressRange::try_from(range.start, range.count)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.read_discrete_inputs(range, callback).await })?; + channel.runtime.spawn(async move { + session + .read_discrete_inputs(range, |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -211,12 +215,14 @@ pub(crate) unsafe fn client_channel_read_holding_registers( ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let range = AddressRange::try_from(range.start, range.count)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.read_holding_registers(range, callback).await })?; + channel.runtime.spawn(async move { + session + .read_holding_registers(range, |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -229,12 +235,14 @@ pub(crate) unsafe fn client_channel_read_input_registers( ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let range = AddressRange::try_from(range.start, range.count)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.read_input_registers(range, callback).await })?; + channel.runtime.spawn(async move { + session + .read_input_registers(range, |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -246,12 +254,14 @@ pub(crate) unsafe fn client_channel_write_single_coil( callback: crate::ffi::WriteCallback, ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.write_single_coil(bit.into(), callback).await })?; + channel.runtime.spawn(async move { + session + .write_single_coil(bit.into(), |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -263,12 +273,12 @@ pub(crate) unsafe fn client_channel_write_single_register( callback: crate::ffi::WriteCallback, ) -> Result<(), ffi::ParamError> { let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); channel.runtime.spawn(async move { session - .write_single_register(register.into(), callback) + .write_single_register(register.into(), |res| callback.complete(res)) .await })?; @@ -285,12 +295,14 @@ pub(crate) unsafe fn client_channel_write_multiple_coils( let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let items = items.as_ref().ok_or(ffi::ParamError::NullParameter)?; let args = WriteMultiple::from(start, items.inner.clone())?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.write_multiple_coils(args, callback).await })?; + channel.runtime.spawn(async move { + session + .write_multiple_coils(args, |res| callback.complete(res)) + .await + })?; Ok(()) } @@ -305,12 +317,14 @@ pub(crate) unsafe fn client_channel_write_multiple_registers( let channel = channel.as_ref().ok_or(ffi::ParamError::NullParameter)?; let items = items.as_ref().ok_or(ffi::ParamError::NullParameter)?; let args = WriteMultiple::from(start, items.inner.clone())?; - let callback = callback.convert_to_fn_once(); + let callback = sfio_promise::wrap(callback); let mut session = param.build_session(channel); - channel - .runtime - .spawn(async move { session.write_multiple_registers(args, callback).await })?; + channel.runtime.spawn(async move { + session + .write_multiple_registers(args, |res| callback.complete(res)) + .await + })?; Ok(()) } diff --git a/ffi/rodbus-ffi/src/helpers/ext.rs b/ffi/rodbus-ffi/src/helpers/ext.rs index 88879f93..f0fc6578 100644 --- a/ffi/rodbus-ffi/src/helpers/ext.rs +++ b/ffi/rodbus-ffi/src/helpers/ext.rs @@ -1,6 +1,6 @@ use crate::ffi; use rodbus::client::{CallbackSession, RequestParam}; -use rodbus::UnitId; +use rodbus::{BitIterator, RegisterIterator, RequestError, UnitId}; impl ffi::RequestParam { pub(crate) fn build_session(&self, channel: &crate::ClientChannel) -> CallbackSession { @@ -11,53 +11,59 @@ impl ffi::RequestParam { } } -impl ffi::BitReadCallback { - pub(crate) fn convert_to_fn_once( - self, - ) -> impl FnOnce(std::result::Result) { - move |result: std::result::Result| match result { +impl<'a> sfio_promise::FutureType, rodbus::RequestError>> + for ffi::BitReadCallback +{ + fn on_drop() -> Result, rodbus::RequestError> { + Err(rodbus::RequestError::Shutdown) + } + + fn complete(self, result: Result) { + match result { + Ok(x) => { + let mut iter = crate::iterator::BitValueIterator::new(x); + self.on_complete(&mut iter); + } Err(err) => { self.on_failure(err.into()); } - Ok(values) => { - let mut iter = crate::BitValueIterator::new(values); - self.on_complete(&mut iter as *mut _); - } } } } -impl ffi::RegisterReadCallback { - pub(crate) fn convert_to_fn_once( - self, - ) -> impl FnOnce(std::result::Result) { - move |result: std::result::Result| { - match result { - Err(err) => { - self.on_failure(err.into()); - } - Ok(values) => { - let mut iter = crate::RegisterValueIterator::new(values); - self.on_complete(&mut iter as *mut _); - } - } - } +impl<'a> sfio_promise::FutureType, rodbus::RequestError>> + for ffi::RegisterReadCallback +{ + fn on_drop() -> Result, rodbus::RequestError> { + Err(rodbus::RequestError::Shutdown) } -} -impl ffi::WriteCallback { - /// we do't care what type T is b/c we're going to ignore it - /// ^ you ok mate? (É.G.) - pub(crate) fn convert_to_fn_once( - self, - ) -> impl FnOnce(std::result::Result) { - move |result: std::result::Result| match result { + fn complete(self, result: Result) { + match result { + Ok(x) => { + let mut iter = crate::iterator::RegisterValueIterator::new(x); + self.on_complete(&mut iter); + } Err(err) => { self.on_failure(err.into()); } + } + } +} + +impl sfio_promise::FutureType> for ffi::WriteCallback { + fn on_drop() -> Result { + Err(rodbus::RequestError::Shutdown) + } + + fn complete(self, result: Result) { + match result { Ok(_) => { self.on_complete(ffi::Nothing::Nothing); } + Err(err) => { + self.on_failure(err.into()); + } } } } diff --git a/ffi/rodbus-ffi/src/server.rs b/ffi/rodbus-ffi/src/server.rs index 4dcb5f34..b8a10624 100644 --- a/ffi/rodbus-ffi/src/server.rs +++ b/ffi/rodbus-ffi/src/server.rs @@ -300,8 +300,8 @@ pub(crate) unsafe fn server_create_tcp( ); let handle = runtime - .inner - .block_on(create_server) + .handle() + .block_on(create_server)? .map_err(|_| ffi::ParamError::ServerBindError)?; let server_handle = Server { @@ -339,7 +339,7 @@ pub(crate) unsafe fn server_create_rtu( let handler_map = endpoints.drain_and_convert(); // enter the runtime context so we can spawn - let _enter = runtime.inner.enter(); + let _enter = runtime.enter(); let handle = rodbus::server::spawn_rtu_server_task( &path.to_string_lossy(), @@ -477,8 +477,8 @@ pub(crate) unsafe fn server_create_tls_impl( ); runtime - .inner - .block_on(create_server) + .handle() + .block_on(create_server)? .map_err(|_| ffi::ParamError::ServerBindError)? } None => { @@ -492,8 +492,8 @@ pub(crate) unsafe fn server_create_tls_impl( ); runtime - .inner - .block_on(create_server) + .handle() + .block_on(create_server)? .map_err(|_| ffi::ParamError::ServerBindError)? } }; diff --git a/ffi/rodbus-schema/Cargo.toml b/ffi/rodbus-schema/Cargo.toml index 13cc7932..8a4b5d50 100644 --- a/ffi/rodbus-schema/Cargo.toml +++ b/ffi/rodbus-schema/Cargo.toml @@ -11,6 +11,6 @@ repository = "https://github.com/stepfunc/rodbus" readme = "../README.md" [dependencies] -oo-bindgen = "0.6" -sfio-tokio-ffi = "0.5" -sfio-tracing-ffi = "0.5" +oo-bindgen = "0.8" +sfio-tokio-ffi = "0.8" +sfio-tracing-ffi = "0.8" diff --git a/ffi/rodbus-schema/src/client.rs b/ffi/rodbus-schema/src/client.rs index 0f799ab6..ac97f786 100644 --- a/ffi/rodbus-schema/src/client.rs +++ b/ffi/rodbus-schema/src/client.rs @@ -423,7 +423,7 @@ fn build_bit_read_callback( "Callbacks received when reading coils or discrete inputs", common.bit_iterator.clone(), "response", - Some(common.error_info.clone()), + common.error_info.clone(), )?; Ok(future) @@ -438,7 +438,7 @@ fn build_register_read_callback( "Callbacks received when reading reading holding or input registers", common.register_iterator.clone(), "response", - Some(common.error_info.clone()), + common.error_info.clone(), )?; Ok(future) @@ -453,7 +453,7 @@ fn build_write_callback( "Callback methods received from asynchronous write operations", common.nothing.clone(), "response", - Some(common.error_info.clone()), + common.error_info.clone(), )?; Ok(future) diff --git a/ffi/rodbus-schema/src/common.rs b/ffi/rodbus-schema/src/common.rs index f2857e7d..7837ab79 100644 --- a/ffi/rodbus-schema/src/common.rs +++ b/ffi/rodbus-schema/src/common.rs @@ -206,7 +206,7 @@ fn build_iterator( ) -> BackTraced { let base_name = item_type.name(); let iter = - lib.define_iterator_with_lifetime(format!("{}_iterator", base_name), item_type.clone())?; + lib.define_iterator_with_lifetime(format!("{base_name}_iterator"), item_type.clone())?; Ok(iter) } @@ -253,7 +253,7 @@ fn build_request_error(lib: &mut LibraryBuilder) -> BackTraced )?; for (name, _value, desc) in MODBUS_EXCEPTION { - builder = builder.add_error(format!("modbus_exception_{}", name), desc)?; + builder = builder.add_error(format!("modbus_exception_{name}"), desc)?; } let definition = builder.build()?; diff --git a/ffi/rodbus-schema/src/server.rs b/ffi/rodbus-schema/src/server.rs index 263f7b44..835074e0 100644 --- a/ffi/rodbus-schema/src/server.rs +++ b/ffi/rodbus-schema/src/server.rs @@ -212,19 +212,19 @@ fn build_add_method( let spaced_name = snake_name.replace('_', " "); let method = lib - .define_method(format!("add_{}", snake_name), db.clone())? + .define_method(format!("add_{snake_name}"), db.clone())? .param( "index", Primitive::U16, - format!("Address of the {}", spaced_name), + format!("Address of the {spaced_name}"), )? .param( "value", value_type, - format!("Initial value of the {}", spaced_name), + format!("Initial value of the {spaced_name}"), )? .returns(Primitive::Bool, "true if the value is new, false otherwise")? - .doc(format!("Add a new {} to the database", spaced_name))? + .doc(format!("Add a new {spaced_name} to the database"))? .build()?; Ok(method) @@ -240,17 +240,16 @@ fn build_get_method( let spaced_name = snake_name.replace('_', " "); let method = lib - .define_method(format!("get_{}", snake_name), db.clone())? + .define_method(format!("get_{snake_name}"), db.clone())? .param( "index", Primitive::U16, - format!("Address of the {}", spaced_name), + format!("Address of the {spaced_name}"), )? .returns(value_type, "Current value of the point")? .fails_with(error_type.clone())? .doc(format!( - "Get the current {} value of the database", - spaced_name + "Get the current {spaced_name} value of the database" ))? .build()?; @@ -265,17 +264,14 @@ fn build_delete_method( let spaced_name = snake_name.replace('_', " "); let method = lib - .define_method(format!("delete_{}", snake_name), db.clone())? + .define_method(format!("delete_{snake_name}"), db.clone())? .param( "index", Primitive::U16, - format!("Address of the {}", spaced_name), + format!("Address of the {spaced_name}"), )? .returns(Primitive::Bool, "true if the value is new, false otherwise")? - .doc(format!( - "Remove a {} address from the database", - spaced_name - ))? + .doc(format!("Remove a {spaced_name} address from the database"))? .build()?; Ok(method) @@ -290,24 +286,23 @@ fn build_update_method( let spaced_name = snake_name.replace('_', " "); let method = lib - .define_method(format!("update_{}", snake_name), db.clone())? + .define_method(format!("update_{snake_name}"), db.clone())? .param( "index", Primitive::U16, - format!("Address of the {}", spaced_name), + format!("Address of the {spaced_name}"), )? .param( "value", value_type, - format!("New value of the {}", spaced_name), + format!("New value of the {spaced_name}"), )? .returns( Primitive::Bool, "true if the address is defined, false otherwise", )? .doc(format!( - "Update the current value of a {} in the database", - spaced_name + "Update the current value of a {spaced_name} in the database" ))? .build()?; diff --git a/rodbus-client/src/main.rs b/rodbus-client/src/main.rs index a7a60ae5..f41a7291 100644 --- a/rodbus-client/src/main.rs +++ b/rodbus-client/src/main.rs @@ -60,7 +60,7 @@ async fn main() -> Result<(), Box> { .init(); if let Err(ref e) = run().await { - println!("error: {}", e); + println!("error: {e}"); } Ok(()) @@ -440,11 +440,11 @@ impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { match self { - Error::BadRange(err) => write!(f, "{}", err), - Error::BadAddr(err) => write!(f, "{}", err), + Error::BadRange(err) => write!(f, "{err}"), + Error::BadAddr(err) => write!(f, "{err}"), Error::BadInt(err) => err.fmt(f), Error::BadBool(err) => err.fmt(f), - Error::BadCharInBitString(char) => write!(f, "Bad character in bit string: {}", char), + Error::BadCharInBitString(char) => write!(f, "Bad character in bit string: {char}"), Error::Request(err) => err.fmt(f), Error::MissingSubCommand => f.write_str("No sub-command provided"), Error::Shutdown => f.write_str("channel was shut down"), diff --git a/rodbus/examples/client.rs b/rodbus/examples/client.rs index 618a04dc..527c62c3 100644 --- a/rodbus/examples/client.rs +++ b/rodbus/examples/client.rs @@ -40,8 +40,7 @@ async fn main() -> Result<(), Box> { "tls-self-signed" => run_tls(get_self_signed_config()?).await, _ => { eprintln!( - "unknown transport '{}', options are (tcp, rtu, tls-ca, tls-self-signed)", - transport + "unknown transport '{transport}', options are (tcp, rtu, tls-ca, tls-self-signed)" ); exit(-1); } @@ -119,9 +118,9 @@ fn get_self_signed_config() -> Result Result> // ANCHOR: tls_ca_chain_config let tls_config = TlsClientConfig::new( "test.com", - &Path::new("./certs/ca_chain/ca_cert.pem"), - &Path::new("./certs/ca_chain/client_cert.pem"), - &Path::new("./certs/ca_chain/client_key.pem"), + Path::new("./certs/ca_chain/ca_cert.pem"), + Path::new("./certs/ca_chain/client_cert.pem"), + Path::new("./certs/ca_chain/client_key.pem"), None, // no password MinTlsVersion::V1_2, CertificateMode::AuthorityBased, @@ -160,9 +159,9 @@ where } } Err(rodbus::RequestError::Exception(exception)) => { - println!("Modbus exception: {}", exception); + println!("Modbus exception: {exception}"); } - Err(err) => println!("read error: {}", err), + Err(err) => println!("read error: {err}"), } } @@ -172,9 +171,9 @@ fn print_write_result(result: Result) { println!("write successful"); } Err(rodbus::RequestError::Exception(exception)) => { - println!("Modbus exception: {}", exception); + println!("Modbus exception: {exception}"); } - Err(err) => println!("writer error: {}", err), + Err(err) => println!("writer error: {err}"), } } diff --git a/rodbus/examples/perf.rs b/rodbus/examples/perf.rs index c6f0be2e..cc64784f 100644 --- a/rodbus/examples/perf.rs +++ b/rodbus/examples/perf.rs @@ -114,7 +114,7 @@ async fn main() -> Result<(), Box> { ) .await { - println!("failure: {}", err); + println!("failure: {err}"); return Err(err); } @@ -136,9 +136,9 @@ async fn main() -> Result<(), Box> { let requests_per_sec: f64 = (iterations as f64) / elapsed.as_secs_f64(); let registers_per_sec = requests_per_sec * (MAX_READ_REGISTERS_COUNT as f64); - println!("performed {} requests in {:?}", iterations, elapsed); - println!("requests/sec == {:.1}", requests_per_sec); - println!("registers/sec == {:.1}", registers_per_sec); + println!("performed {iterations} requests in {elapsed:?}"); + println!("requests/sec == {requests_per_sec:.1}"); + println!("registers/sec == {registers_per_sec:.1}"); Ok(()) } diff --git a/rodbus/examples/server.rs b/rodbus/examples/server.rs index a52b1f4f..4fc490cb 100644 --- a/rodbus/examples/server.rs +++ b/rodbus/examples/server.rs @@ -154,8 +154,7 @@ async fn main() -> Result<(), Box> { "tls-self-signed" => run_tls(get_self_signed_config()?).await, _ => { eprintln!( - "unknown transport '{}', options are (tcp, rtu, tls-ca, tls-self-signed)", - transport + "unknown transport '{transport}', options are (tcp, rtu, tls-ca, tls-self-signed)" ); exit(-1); } @@ -240,9 +239,9 @@ fn get_self_signed_config() -> Result Result> use std::path::Path; // ANCHOR: tls_ca_chain_config let tls_config = TlsServerConfig::new( - &Path::new("./certs/ca_chain/ca_cert.pem"), - &Path::new("./certs/ca_chain/server_cert.pem"), - &Path::new("./certs/ca_chain/server_key.pem"), + Path::new("./certs/ca_chain/ca_cert.pem"), + Path::new("./certs/ca_chain/server_cert.pem"), + Path::new("./certs/ca_chain/server_key.pem"), None, // no password MinTlsVersion::V1_2, CertificateMode::AuthorityBased, @@ -306,13 +305,13 @@ async fn run_server( "uhr" => { let mut handler = handler.lock().unwrap(); for holding_register in handler.holding_registers_as_mut() { - *holding_register = *holding_register + 1; + *holding_register += 1; } } "uir" => { let mut handler = handler.lock().unwrap(); for input_register in handler.input_registers_as_mut() { - *input_register = *input_register + 1; + *input_register += 1; } } _ => println!("unknown command"), diff --git a/rodbus/src/client/message.rs b/rodbus/src/client/message.rs index 77b23aaa..c18abb7e 100644 --- a/rodbus/src/client/message.rs +++ b/rodbus/src/client/message.rs @@ -229,7 +229,7 @@ impl std::fmt::Display for RequestDetailsDisplay<'_> { write!(f, "{}", details.request.range)?; if self.level.data_values() { for x in details.request.iter() { - write!(f, "\n{}", x)?; + write!(f, "\n{x}")?; } } } @@ -237,7 +237,7 @@ impl std::fmt::Display for RequestDetailsDisplay<'_> { write!(f, "{}", details.request.range)?; if self.level.data_values() { for x in details.request.iter() { - write!(f, "\n{}", x)?; + write!(f, "\n{x}")?; } } } diff --git a/rodbus/src/client/task.rs b/rodbus/src/client/task.rs index ccc9025d..27391686 100644 --- a/rodbus/src/client/task.rs +++ b/rodbus/src/client/task.rs @@ -35,7 +35,7 @@ impl std::fmt::Display for SessionError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { SessionError::IoError(err) => { - write!(f, "i/o error: {}", err) + write!(f, "i/o error: {err}") } SessionError::BadFrame => { write!(f, "Parser encountered a bad frame") diff --git a/rodbus/src/common/frame.rs b/rodbus/src/common/frame.rs index b4b42f46..d6031aff 100644 --- a/rodbus/src/common/frame.rs +++ b/rodbus/src/common/frame.rs @@ -110,7 +110,7 @@ impl FrameDestination { impl std::fmt::Display for FrameDestination { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::UnitId(unit_id) => write!(f, "{}", unit_id), + Self::UnitId(unit_id) => write!(f, "{unit_id}"), Self::Broadcast => write!(f, "BCAST ({})", UnitId::broadcast()), } } @@ -268,13 +268,13 @@ impl std::fmt::Display for FunctionField { let value = self.get_value(); match self { FunctionField::Valid(x) => { - write!(f, "{}", x) + write!(f, "{x}") } FunctionField::Exception(x) => { - write!(f, "Exception({}) for {}", value, x) + write!(f, "Exception({value}) for {x}") } FunctionField::UnknownFunction(_) => { - write!(f, "Unknown Function Exception: {}", value) + write!(f, "Unknown Function Exception: {value}") } } } diff --git a/rodbus/src/common/phys.rs b/rodbus/src/common/phys.rs index 7d45e132..ad328b47 100644 --- a/rodbus/src/common/phys.rs +++ b/rodbus/src/common/phys.rs @@ -179,7 +179,7 @@ pub(crate) fn format_bytes(f: &mut std::fmt::Formatter, bytes: &[u8]) -> std::fm f.write_char(' ')?; } first = false; - write!(f, "{:02X?}", byte)?; + write!(f, "{byte:02X?}")?; } } Ok(()) diff --git a/rodbus/src/common/serialize.rs b/rodbus/src/common/serialize.rs index 753f3659..905cfe01 100644 --- a/rodbus/src/common/serialize.rs +++ b/rodbus/src/common/serialize.rs @@ -45,7 +45,7 @@ impl Loggable for AddressRange { let mut cursor = ReadCursor::new(payload); if let Ok(value) = AddressRange::parse(&mut cursor) { - write!(f, "{}", value)?; + write!(f, "{value}")?; } } @@ -92,7 +92,7 @@ impl Loggable for Indexed { }; let value = Indexed::new(index, coil_value); - write!(f, "{}", value)?; + write!(f, "{value}")?; } Ok(()) @@ -127,7 +127,7 @@ impl Loggable for Indexed { }; let value = Indexed::new(index, raw_value); - write!(f, "{}", value)?; + write!(f, "{value}")?; } Ok(()) diff --git a/rodbus/src/common/traits.rs b/rodbus/src/common/traits.rs index 86a80a7b..bc3cc5e8 100644 --- a/rodbus/src/common/traits.rs +++ b/rodbus/src/common/traits.rs @@ -50,6 +50,6 @@ impl Loggable for ExceptionCode { _level: AppDecodeLevel, f: &mut std::fmt::Formatter, ) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/rodbus/src/error.rs b/rodbus/src/error.rs index 11a994c4..5a15447b 100644 --- a/rodbus/src/error.rs +++ b/rodbus/src/error.rs @@ -179,27 +179,22 @@ impl std::fmt::Display for InternalError { match self { InternalError::InsufficientWriteSpace(written, remaining) => write!( f, - "attempted to write {} bytes with {} bytes remaining", - written, remaining + "attempted to write {written} bytes with {remaining} bytes remaining" ), InternalError::FrameTooBig(size, max) => write!( f, - "Frame length of {} exceeds the maximum allowed length of {}", - size, max + "Frame length of {size} exceeds the maximum allowed length of {max}" ), InternalError::InsufficientBytesForRead(requested, remaining) => write!( f, - "attempted to read {} bytes with only {} remaining", - requested, remaining + "attempted to read {requested} bytes with only {remaining} remaining" ), InternalError::BadSeekOperation => { f.write_str("Cursor seek operation exceeded the bounds of the underlying buffer") } - InternalError::BadByteCount(size) => write!( - f, - "Byte count of in ADU {} exceeds maximum size of u8", - size - ), + InternalError::BadByteCount(size) => { + write!(f, "Byte count of in ADU {size} exceeds maximum size of u8") + } } } } @@ -229,20 +224,18 @@ impl std::fmt::Display for FrameParseError { } FrameParseError::FrameLengthTooBig(size, max) => write!( f, - "Received TCP frame with length ({}) that exceeds max allowed size ({})", - size, max + "Received TCP frame with length ({size}) that exceeds max allowed size ({max})" ), FrameParseError::UnknownProtocolId(id) => { - write!(f, "Received TCP frame with non-Modbus protocol id: {}", id) + write!(f, "Received TCP frame with non-Modbus protocol id: {id}") } FrameParseError::UnknownFunctionCode(code) => { - write!(f, "Received unknown function code ({:#04X}), cannot determine the length of the message", code) + write!(f, "Received unknown function code ({code:#04X}), cannot determine the length of the message") } FrameParseError::CrcValidationFailure(received, expected) => { write!( f, - "Received incorrect CRC value {:#06X}, expected {:#06X}", - received, expected + "Received incorrect CRC value {received:#06X}, expected {expected:#06X}" ) } } @@ -274,24 +267,21 @@ impl std::fmt::Display for AduParseError { AduParseError::InsufficientBytes => f.write_str("response is too short to be valid"), AduParseError::InsufficientBytesForByteCount(count, remaining) => write!( f, - "byte count ({}) doesn't match the actual number of bytes remaining ({})", - count, remaining + "byte count ({count}) doesn't match the actual number of bytes remaining ({remaining})" ), AduParseError::TrailingBytes(remaining) => { - write!(f, "response contains {} extra trailing bytes", remaining) + write!(f, "response contains {remaining} extra trailing bytes") } AduParseError::ReplyEchoMismatch => { f.write_str("a parameter expected to be echoed in the reply did not match") } AduParseError::UnknownResponseFunction(actual, expected, error) => write!( f, - "received unknown response function code: {}. Expected {} or {}", - actual, expected, error + "received unknown response function code: {actual}. Expected {expected} or {error}" ), AduParseError::UnknownCoilState(value) => write!( f, - "received coil state with unspecified value: 0x{:04X}", - value + "received coil state with unspecified value: 0x{value:04X}" ), } } @@ -313,17 +303,15 @@ impl std::error::Error for InvalidRequest {} impl std::fmt::Display for InvalidRequest { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { match self { - InvalidRequest::BadRange(err) => write!(f, "{}", err), + InvalidRequest::BadRange(err) => write!(f, "{err}"), InvalidRequest::CountTooBigForU16(count) => write!( f, - "The requested count of objects exceeds the maximum value of u16: {}", - count + "The requested count of objects exceeds the maximum value of u16: {count}" ), InvalidRequest::CountTooBigForType(count, max) => write!( f, - "the request count of {} exceeds maximum allowed count of {} for this type", - count, max + "the request count of {count} exceeds maximum allowed count of {max} for this type" ), } } @@ -335,13 +323,11 @@ impl std::fmt::Display for InvalidRange { InvalidRange::CountOfZero => f.write_str("range contains count == 0"), InvalidRange::AddressOverflow(start, count) => write!( f, - "start == {} and count = {} would overflow u16 representation", - start, count + "start == {start} and count = {count} would overflow u16 representation" ), InvalidRange::CountTooLargeForType(x, y) => write!( f, - "count of {} is too large for the specified type (max == {})", - x, y + "count of {x} is too large for the specified type (max == {y})" ), } } diff --git a/rodbus/src/exception.rs b/rodbus/src/exception.rs index 101d30e9..d45bc586 100644 --- a/rodbus/src/exception.rs +++ b/rodbus/src/exception.rs @@ -98,7 +98,7 @@ impl std::fmt::Display for ExceptionCode { ExceptionCode::MemoryParityError=> f.write_str("server attempted to read a record file, but detected a parity error in the memory"), ExceptionCode::GatewayPathUnavailable=> f.write_str("gateway was unable to allocate an internal communication path from the input port to the output port for processing the request"), ExceptionCode::GatewayTargetDeviceFailedToRespond=> f.write_str("gateway did not receive a response from the target device"), - ExceptionCode::Unknown(code) => write!(f, "received unknown exception code: {}", code) + ExceptionCode::Unknown(code) => write!(f, "received unknown exception code: {code}") } } } diff --git a/rodbus/src/serial/frame.rs b/rodbus/src/serial/frame.rs index 500dd80f..642f7a8a 100644 --- a/rodbus/src/serial/frame.rs +++ b/rodbus/src/serial/frame.rs @@ -561,7 +561,7 @@ mod tests { tokio_test::task::spawn(reader.next_frame(&mut layer, DecodeLevel::nothing())); // Send bytes to parser byte per byte - for byte in frame.into_iter().take(frame.len() - 1) { + for byte in frame.iter().take(frame.len() - 1) { io_handle.read(&[*byte]); assert!(matches!(task.poll(), Poll::Pending)); } @@ -705,7 +705,7 @@ mod tests { } impl<'a> Serialize for MockMessage<'a> { - fn serialize(self: &Self, cursor: &mut WriteCursor) -> Result<(), RequestError> { + fn serialize(&self, cursor: &mut WriteCursor) -> Result<(), RequestError> { for byte in &self.frame[2..self.frame.len() - 2] { cursor.write_u8(*byte)?; } diff --git a/rodbus/src/server/request.rs b/rodbus/src/server/request.rs index 78f2a149..77843d67 100644 --- a/rodbus/src/server/request.rs +++ b/rodbus/src/server/request.rs @@ -234,10 +234,10 @@ impl std::fmt::Display for RequestDisplay<'_, '_> { write!(f, " {}", range.get())?; } Request::WriteSingleCoil(request) => { - write!(f, " {}", request)?; + write!(f, " {request}")?; } Request::WriteSingleRegister(request) => { - write!(f, " {}", request)?; + write!(f, " {request}")?; } Request::WriteMultipleCoils(items) => { write!( diff --git a/rodbus/src/tcp/frame.rs b/rodbus/src/tcp/frame.rs index a851a518..738574a6 100644 --- a/rodbus/src/tcp/frame.rs +++ b/rodbus/src/tcp/frame.rs @@ -219,7 +219,7 @@ mod tests { } impl Serialize for MockBody { - fn serialize(self: &Self, cursor: &mut WriteCursor) -> Result<(), RequestError> { + fn serialize(&self, cursor: &mut WriteCursor) -> Result<(), RequestError> { for b in self.body { cursor.write_u8(*b)?; } @@ -264,7 +264,7 @@ mod tests { io_handle.read(input); if let Poll::Ready(frame) = task.poll() { - return frame.err().unwrap(); + frame.err().unwrap() } else { panic!("Task not ready"); } diff --git a/rodbus/src/tcp/tls/client.rs b/rodbus/src/tcp/tls/client.rs index ebd5018f..c31de5e9 100644 --- a/rodbus/src/tcp/tls/client.rs +++ b/rodbus/src/tcp/tls/client.rs @@ -153,8 +153,7 @@ impl TlsClientConfig { let connector = tokio_rustls::TlsConnector::from(self.config.clone()); match connector.connect(self.dns_name.clone(), socket).await { Err(err) => Err(format!( - "failed to establish TLS session with {}: {}", - endpoint, err + "failed to establish TLS session with {endpoint}: {err}" )), Ok(stream) => Ok(PhysLayer::new_tls(tokio_rustls::TlsStream::from(stream))), } @@ -314,8 +313,7 @@ impl rustls::client::ServerCertVerifier for SelfSignedCertificateServerCertVerif // Check that the certificate is still valid let parsed_cert = rx509::x509::Certificate::parse(&end_entity.0).map_err(|err| { rustls::Error::InvalidCertificateData(format!( - "unable to parse cert with rasn: {:?}", - err + "unable to parse cert with rasn: {err:?}" )) })?; diff --git a/rodbus/src/tcp/tls/mod.rs b/rodbus/src/tcp/tls/mod.rs index 356ffc15..12675076 100644 --- a/rodbus/src/tcp/tls/mod.rs +++ b/rodbus/src/tcp/tls/mod.rs @@ -51,14 +51,14 @@ impl std::fmt::Display for TlsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::InvalidPeerCertificate(err) => { - write!(f, "invalid peer certificate file: {}", err) + write!(f, "invalid peer certificate file: {err}") } Self::InvalidLocalCertificate(err) => { - write!(f, "invalid local certificate file: {}", err) + write!(f, "invalid local certificate file: {err}") } - Self::InvalidPrivateKey(err) => write!(f, "invalid private key file: {}", err), + Self::InvalidPrivateKey(err) => write!(f, "invalid private key file: {err}"), Self::InvalidDnsName => write!(f, "invalid DNS name"), - Self::BadConfig(err) => write!(f, "bad config: {}", err), + Self::BadConfig(err) => write!(f, "bad config: {err}"), } } } @@ -104,8 +104,7 @@ fn verify_dns_name(cert: &rustls::Certificate, server_name: &str) -> Result<(), // Parse the certificate using rasn let parsed_cert = rx509::x509::Certificate::parse(&cert.0).map_err(|err| { rustls::Error::InvalidCertificateData(format!( - "unable to parse cert with rasn: {:?}", - err + "unable to parse cert with rasn: {err:?}" )) })?; @@ -114,8 +113,7 @@ fn verify_dns_name(cert: &rustls::Certificate, server_name: &str) -> Result<(), // Parse the extensions let extensions = extensions.parse().map_err(|err| { rustls::Error::InvalidCertificateData(format!( - "unable to parse certificate extensions with rasn: {:?}", - err + "unable to parse certificate extensions with rasn: {err:?}" )) })?; @@ -140,8 +138,7 @@ fn verify_dns_name(cert: &rustls::Certificate, server_name: &str) -> Result<(), .parse() .map_err(|err| { rustls::Error::InvalidCertificateData(format!( - "unable to parse certificate subject: {:?}", - err + "unable to parse certificate subject: {err:?}" )) })?; @@ -170,7 +167,7 @@ fn pki_error(error: webpki::Error) -> rustls::Error { UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => { rustls::Error::InvalidCertificateSignatureType } - e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {}", e)), + e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {e}")), } } diff --git a/rodbus/src/tcp/tls/server.rs b/rodbus/src/tcp/tls/server.rs index 3b5dbddc..1a3b894c 100644 --- a/rodbus/src/tcp/tls/server.rs +++ b/rodbus/src/tcp/tls/server.rs @@ -78,7 +78,7 @@ impl TlsServerConfig { ) -> Result<(PhysLayer, AuthorizationType), String> { let connector = tokio_rustls::TlsAcceptor::from(self.inner.clone()); match connector.accept(socket).await { - Err(err) => Err(format!("failed to establish TLS session: {}", err)), + Err(err) => Err(format!("failed to establish TLS session: {err}")), Ok(stream) => { let auth_type = match auth_handler { // bare TLS mode without authz @@ -96,9 +96,8 @@ impl TlsServerConfig { .as_slice(); let parsed = rx509::x509::Certificate::parse(peer_cert) - .map_err(|err| format!("ASNError: {}", err))?; - let role = - extract_modbus_role(&parsed).map_err(|err| format!("{}", err))?; + .map_err(|err| format!("ASNError: {err}"))?; + let role = extract_modbus_role(&parsed).map_err(|err| format!("{err}"))?; tracing::info!("client role: {}", role); AuthorizationType::Handler(handler, role) @@ -204,8 +203,7 @@ impl rustls::server::ClientCertVerifier for SelfSignedCertificateClientCertVerif let parsed_cert = rx509::x509::Certificate::parse(&end_entity.0).map_err(|err| { rustls::Error::InvalidCertificateData(format!( - "unable to parse cert with rasn: {:?}", - err + "unable to parse cert with rasn: {err:?}" )) })?; @@ -257,8 +255,7 @@ fn extract_modbus_role(cert: &rx509::x509::Certificate) -> Result { if self.level.data_values() { for x in self.iterator { - write!(f, "\n{}", x)?; + write!(f, "\n{x}")?; } } @@ -153,7 +153,7 @@ impl std::fmt::Display for RegisterIteratorDisplay<'_> { if self.level.data_values() { for x in self.iterator { - write!(f, "\n{}", x)?; + write!(f, "\n{x}")?; } }