From 69a3867c0981428810bace164159ff4619bcf755 Mon Sep 17 00:00:00 2001 From: BinChengZhao Date: Tue, 21 Mar 2023 21:37:31 +0800 Subject: [PATCH] chore: Optimize code 2023 --- benches/body.rs | 14 +++++++------- examples/cycle_tokio_task.rs | 12 ++++++------ examples/demo.rs | 19 ++++++++++--------- examples/demo_async_tokio.rs | 4 ++-- examples/dynamic_cancel.rs | 2 +- examples/generic.rs | 3 +-- examples/increase.rs | 6 ++---- examples/profile_memory.rs | 8 ++++---- examples/share_tokio_runtime.rs | 2 +- src/entity.rs | 2 +- src/lib.rs | 1 + src/prelude.rs | 2 +- src/timer/task.rs | 12 ++++++------ src/utils/convenience.rs | 6 +++--- src/utils/parse.rs | 2 +- src/utils/status_report.rs | 2 +- tests/simulation.rs | 2 +- 17 files changed, 49 insertions(+), 50 deletions(-) diff --git a/benches/body.rs b/benches/body.rs index f40e72f..60d842e 100644 --- a/benches/body.rs +++ b/benches/body.rs @@ -1,5 +1,5 @@ #![feature(test)] -#![deny(warnings)] +#![allow(deprecated)] extern crate test; @@ -13,7 +13,7 @@ use test::Bencher; #[bench] fn bench_task_spwan(b: &mut Bencher) { - let body = move |_| create_default_delay_task_handler(); + let body = move || async {}; let mut task_builder = TaskBuilder::default(); task_builder @@ -23,16 +23,16 @@ fn bench_task_spwan(b: &mut Bencher) { // String parsing to corn-expression -> iterator is the most time-consuming operation about 1500ns ~ 3500 ns. // The iterator is used to find out when the next execution should take place, in about 500 ns. - b.iter(|| task_builder.spawn_async_routine(body.clone())); + b.iter(|| task_builder.spawn_async_routine(body)); } #[bench] fn bench_maintain_task(b: &mut Bencher) { let (timer_event_sender, _timer_event_receiver) = unbounded::(); let shared_header = SharedHeader::default(); - let mut timer = Timer::new(timer_event_sender.clone(), shared_header); + let mut timer = Timer::new(timer_event_sender, shared_header); - let body = move |_| create_default_delay_task_handler(); + let body = move || async {}; let mut task_builder = TaskBuilder::default(); task_builder @@ -57,12 +57,12 @@ fn bench_maintain_task(b: &mut Bencher) { fn bench_try_wait(b: &mut Bencher) { use std::process::Command; - if let Ok(mut child) = Command::new("ps").spawn_async_routine() { + if let Ok(mut child) = Command::new("ps").spawn() { b.iter(|| child.try_wait()); } } #[bench] fn bench_timestamp(b: &mut Bencher) { - b.iter(|| timestamp()); + b.iter(timestamp); } diff --git a/examples/cycle_tokio_task.rs b/examples/cycle_tokio_task.rs index 8462857..2a04457 100644 --- a/examples/cycle_tokio_task.rs +++ b/examples/cycle_tokio_task.rs @@ -67,14 +67,14 @@ pub async fn async_template(id: i32, name: String) -> Result<()> { // The default connector does not handle TLS. // Speaking to https destinations will require configuring a connector that implements TLS. // So use http for test. - let url = format!("http://httpbin.org/get?id={}&name={}", id, name); + let url = format!("http://httpbin.org/get?id={id}&name={name}"); let uri: Uri = url.parse()?; let res = client.get(uri).await?; println!("Response: {}", res.status()); // Concatenate the body stream into a single buffer... let buf = hyper::body::to_bytes(res).await?; - println!("body: {:?}", buf); + println!("body: {buf:?}"); Ok(()) } @@ -82,10 +82,10 @@ enum AuspiciousDay { Wake, } -impl Into for AuspiciousDay { - fn into(self) -> CandyCronStr { - match self { - Self::Wake => CandyCronStr("0 * * * Jan-Dec * 2020-2100".to_string()), +impl From for CandyCronStr { + fn from(val: AuspiciousDay) -> Self { + match val { + AuspiciousDay::Wake => CandyCronStr("0 * * * Jan-Dec * 2020-2100".to_string()), } } } diff --git a/examples/demo.rs b/examples/demo.rs index 55a48cb..c3fde28 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -5,7 +5,6 @@ use delay_timer::utils::convenience::functions::unblock_process_task_fn; use smol::Timer; use std::thread::{current, park, Thread}; use std::time::Duration; -use surf; // cargo run --package delay_timer --example demo --features=full @@ -115,7 +114,7 @@ fn build_task_customized_async_task() -> Result { } pub async fn async_template(id: i32, name: String) { - let url = format!("https://httpbin.org/get?id={}&name={}", id, name); + let url = format!("https://httpbin.org/get?id={id}&name={name}"); if let Ok(mut res) = surf::get(url).await { dbg!(res.body_string().await.unwrap_or_default()); } @@ -146,13 +145,15 @@ enum AuspiciousTime { PerDayFiveAclock, } -impl Into for AuspiciousTime { - fn into(self) -> CandyCronStr { - match self { - Self::PerSevenSeconds => CandyCronStr("0/7 * * * * * *".to_string()), - Self::PerEightSeconds => CandyCronStr("0/8 * * * * * *".to_string()), - Self::LoveTime => CandyCronStr("0,10,15,25,50 0/1 * * Jan-Dec * 2020-2100".to_string()), - Self::PerDayFiveAclock => CandyCronStr("01 00 1 * * * *".to_string()), +impl From for CandyCronStr { + fn from(val: AuspiciousTime) -> Self { + match val { + AuspiciousTime::PerSevenSeconds => CandyCronStr("0/7 * * * * * *".to_string()), + AuspiciousTime::PerEightSeconds => CandyCronStr("0/8 * * * * * *".to_string()), + AuspiciousTime::LoveTime => { + CandyCronStr("0,10,15,25,50 0/1 * * Jan-Dec * 2020-2100".to_string()) + } + AuspiciousTime::PerDayFiveAclock => CandyCronStr("01 00 1 * * * *".to_string()), } } } diff --git a/examples/demo_async_tokio.rs b/examples/demo_async_tokio.rs index ed92bdf..315a8b7 100644 --- a/examples/demo_async_tokio.rs +++ b/examples/demo_async_tokio.rs @@ -100,13 +100,13 @@ pub async fn async_template(id: i32, name: String) -> Result<()> { // The default connector does not handle TLS. // Speaking to https destinations will require configuring a connector that implements TLS. // So use http for test. - let url = format!("http://httpbin.org/get?id={}&name={}", id, name); + let url = format!("http://httpbin.org/get?id={id}&name={name}"); let uri: Uri = url.parse()?; let res = client.get(uri).await?; println!("Response: {}", res.status()); // Concatenate the body stream into a single buffer... let buf = hyper::body::to_bytes(res).await?; - println!("body: {:?}", buf); + println!("body: {buf:?}"); Ok(()) } diff --git a/examples/dynamic_cancel.rs b/examples/dynamic_cancel.rs index 8f03fe5..fed8d26 100644 --- a/examples/dynamic_cancel.rs +++ b/examples/dynamic_cancel.rs @@ -14,7 +14,7 @@ fn main() -> Result<()> { // Dynamically cancel in the context of `synchronization`. sync_cancel()?; - println!(""); + println!(); // Dynamic cancellation in `asynchronous` contexts. async_cancel() } diff --git a/examples/generic.rs b/examples/generic.rs index a1ab77e..bd6e924 100644 --- a/examples/generic.rs +++ b/examples/generic.rs @@ -6,7 +6,6 @@ use smol::Timer; use std::any::{type_name, Any}; use std::thread::park_timeout; use std::time::Duration; -use surf; // cargo run --package delay_timer --example generic --features=full @@ -33,7 +32,7 @@ fn build_generic_task_async_request(animal: T) -> Result impl Copy + Fn() { fn get_wake_fn( thread: Thread, run_flag_ref: SafePointer, -) -> impl Fn() -> () + Clone + Send + Sync + 'static { +) -> impl Fn() + Clone + Send + Sync + 'static { move || { let local_run_flag = run_flag_ref.as_ptr(); unsafe { @@ -102,7 +100,7 @@ fn get_async_fn() -> impl std::future::Future { async { if let Ok(mut res) = surf::get("https://httpbin.org/get").await { let body_str = res.body_string().await.unwrap_or_default(); - println!("{}", body_str); + println!("{body_str}"); } } } diff --git a/examples/profile_memory.rs b/examples/profile_memory.rs index 0ac86a6..8ffdc9f 100644 --- a/examples/profile_memory.rs +++ b/examples/profile_memory.rs @@ -21,16 +21,16 @@ impl RequstBody { } } -impl Into for RequstBody { - fn into(self) -> CandyCronStr { - CandyCronStr(self.cron_expression) +impl From for CandyCronStr { + fn from(val: RequstBody) -> Self { + CandyCronStr(val.cron_expression) } } // LD_PRELOAD=../../tools-bin/libmemory_profiler.so ./target/debug/examples/profile_memory // ../../tools-bin/memory-profiler-cli server memory-profiling_*.dat fn main() { - let capacity: usize = 256_00; + let capacity: usize = 25_600; let mut task_builder_vec: Vec = Vec::with_capacity(capacity); for _ in 0..capacity { diff --git a/examples/share_tokio_runtime.rs b/examples/share_tokio_runtime.rs index 4f6dfb7..0c1726b 100644 --- a/examples/share_tokio_runtime.rs +++ b/examples/share_tokio_runtime.rs @@ -27,7 +27,7 @@ fn main() -> Result<(), Report> { } })?; - Ok(read_config()?) + read_config() } fn build_task_async_print(id: u64, cron_str: &'static str) -> Result { diff --git a/src/entity.rs b/src/entity.rs index d3c5882..8d5a4ac 100644 --- a/src/entity.rs +++ b/src/entity.rs @@ -179,7 +179,7 @@ impl RuntimeInstance { .thread_name_fn(|| { static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); - format!("tokio-{}", id) + format!("tokio-{id}") }) .on_thread_start(|| { debug!("tokio-thread started"); diff --git a/src/lib.rs b/src/lib.rs index 87a5cea..3ce9a5a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -237,6 +237,7 @@ #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #![cfg_attr(RUSTC_IS_NIGHTLY, feature(linked_list_cursors))] #![cfg_attr(docsrs, feature(doc_cfg))] +#![allow(clippy::useless_transmute)] #[macro_use] pub mod macros; pub mod entity; diff --git a/src/prelude.rs b/src/prelude.rs index 458c1da..fdfaee2 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -50,7 +50,7 @@ pub(crate) use crate::timer::task::Routine; pub(crate) use crate::utils::parse::shell_command::{ChildGuard, ChildGuardList, ChildUnify}; pub(crate) use dashmap::DashMap; -pub(crate) use log::{debug, error, info, trace}; +pub(crate) use log::{debug, error, trace}; pub(crate) use smol::channel::{unbounded, Receiver as AsyncReceiver, Sender as AsyncSender}; pub(crate) use smol::future::yield_now; pub(crate) use smol::lock::Mutex as AsyncMutex; diff --git a/src/timer/task.rs b/src/timer/task.rs index 37e3b6f..5ad006e 100644 --- a/src/timer/task.rs +++ b/src/timer/task.rs @@ -220,7 +220,7 @@ impl<'a> TryFrom<(FrequencyUnify<'a>, ScheduleIteratorTimeZone)> for FrequencyIn let task_schedule = DelayTimerScheduleIteratorOwned::analyze_cron_expression(time_zone, cron_str)?; - FrequencyInner::CronExpressionCountDown(count_down as u64, task_schedule) + FrequencyInner::CronExpressionCountDown(count_down, task_schedule) } FrequencyUnify::FrequencySeconds(FrequencySeconds::Once(seconds)) => { @@ -847,7 +847,7 @@ impl<'a> TaskBuilder<'a> { }; unsafe { - Box::from_raw(std::mem::transmute::<&str, *mut str>(s)); + drop(Box::from_raw(std::mem::transmute::<&str, *mut str>(s))); } } } @@ -1155,7 +1155,7 @@ mod tests { #[test] fn test_get_next_exec_timestamp_seconds() -> AnyResult<()> { let mut rng = rand::thread_rng(); - let init_seconds: u64 = rng.gen_range(1..100_00_00); + let init_seconds: u64 = rng.gen_range(1..1_000_000); let mut task_builder = TaskBuilder::default(); task_builder.set_frequency_count_down_by_seconds(init_seconds, 3); @@ -1187,7 +1187,7 @@ mod tests { #[test] fn test_get_next_exec_timestamp_minutes() -> AnyResult<()> { let mut rng = rand::thread_rng(); - let init_minutes: u64 = rng.gen_range(1..100_00_00); + let init_minutes: u64 = rng.gen_range(1..1_000_000); let mut task_builder = TaskBuilder::default(); task_builder.set_frequency_repeated_by_minutes(init_minutes); @@ -1208,7 +1208,7 @@ mod tests { #[test] fn test_get_next_exec_timestamp_hours() -> AnyResult<()> { let mut rng = rand::thread_rng(); - let init_hours: u64 = rng.gen_range(1..100_00_00); + let init_hours: u64 = rng.gen_range(1..1_000_000); let mut task_builder = TaskBuilder::default(); task_builder.set_frequency_repeated_by_hours(init_hours); @@ -1229,7 +1229,7 @@ mod tests { #[test] fn test_get_next_exec_timestamp_days() -> AnyResult<()> { let mut rng = rand::thread_rng(); - let init_days: u64 = rng.gen_range(1..100_00_00); + let init_days: u64 = rng.gen_range(1..1_000_000); let mut task_builder = TaskBuilder::default(); task_builder.set_frequency_repeated_by_days(init_days); diff --git a/src/utils/convenience.rs b/src/utils/convenience.rs index 5414c8d..1c550fe 100644 --- a/src/utils/convenience.rs +++ b/src/utils/convenience.rs @@ -226,9 +226,9 @@ mod tests { struct CustomizationCandyCron(i32); - impl Into for CustomizationCandyCron { - fn into(self) -> CandyCronStr { - let s = match self.0 { + impl From for CandyCronStr { + fn from(val: CustomizationCandyCron) -> Self { + let s = match val.0 { 0 => "1 1 1 1 1 1 1", 1 => "0 59 23 18 11 3 2100", _ => "* * * * * * *", diff --git a/src/utils/parse.rs b/src/utils/parse.rs index 068bc3b..9de44d0 100644 --- a/src/utils/parse.rs +++ b/src/utils/parse.rs @@ -273,7 +273,7 @@ pub mod shell_command { .map_err(|e| CommandChildError::DisCondition(e.to_string()))?; } - let mut parts = command.trim().split_whitespace(); + let mut parts = command.split_whitespace(); let command = parts .next() .ok_or_else(|| CommandChildError::DisCondition("Without next part".to_string()))?; diff --git a/src/utils/status_report.rs b/src/utils/status_report.rs index 2644645..2d32f95 100644 --- a/src/utils/status_report.rs +++ b/src/utils/status_report.rs @@ -35,7 +35,7 @@ impl StatusReporter { /// Async get `PublicEvent` via `StatusReporter`. pub async fn next_public_event_with_async_wait(&self) -> Result { - Ok(self.inner.recv().await?) + self.inner.recv().await } pub(crate) fn new(inner: AsyncReceiver) -> Self { diff --git a/tests/simulation.rs b/tests/simulation.rs index 70ce25d..cb6d14d 100644 --- a/tests/simulation.rs +++ b/tests/simulation.rs @@ -288,7 +288,7 @@ fn tests_countdown() -> AnyResult<()> { let mut i = 0; loop { - i = i + 1; + i += 1; park_timeout(Duration::from_secs(3)); if i == 6 {