Skip to content

Commit

Permalink
chore: Optimize code 2023
Browse files Browse the repository at this point in the history
  • Loading branch information
BinChengZhao committed Mar 21, 2023
1 parent 366bcc4 commit 69a3867
Show file tree
Hide file tree
Showing 17 changed files with 49 additions and 50 deletions.
14 changes: 7 additions & 7 deletions benches/body.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![feature(test)]
#![deny(warnings)]
#![allow(deprecated)]

extern crate test;

Expand All @@ -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
Expand All @@ -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::<TimerEvent>();
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
Expand All @@ -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);
}
12 changes: 6 additions & 6 deletions examples/cycle_tokio_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,25 +67,25 @@ 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(())
}

enum AuspiciousDay {
Wake,
}

impl Into<CandyCronStr> for AuspiciousDay {
fn into(self) -> CandyCronStr {
match self {
Self::Wake => CandyCronStr("0 * * * Jan-Dec * 2020-2100".to_string()),
impl From<AuspiciousDay> for CandyCronStr {
fn from(val: AuspiciousDay) -> Self {
match val {
AuspiciousDay::Wake => CandyCronStr("0 * * * Jan-Dec * 2020-2100".to_string()),
}
}
}
19 changes: 10 additions & 9 deletions examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -115,7 +114,7 @@ fn build_task_customized_async_task() -> Result<Task, TaskError> {
}

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());
}
Expand Down Expand Up @@ -146,13 +145,15 @@ enum AuspiciousTime {
PerDayFiveAclock,
}

impl Into<CandyCronStr> 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<AuspiciousTime> 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()),
}
}
}
4 changes: 2 additions & 2 deletions examples/demo_async_tokio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
2 changes: 1 addition & 1 deletion examples/dynamic_cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
3 changes: 1 addition & 2 deletions examples/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -33,7 +32,7 @@ fn build_generic_task_async_request<T: Animal>(animal: T) -> Result<Task, TaskEr

let body = move || {
let animal_ref = animal.clone();
let other_animal_ref = other_animal.clone();
let other_animal_ref = other_animal;
async move {
if let Ok(mut res) = surf::get("https://httpbin.org/get").await {
dbg!(res.body_string().await.unwrap_or_default());
Expand Down
6 changes: 2 additions & 4 deletions examples/increase.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#![allow(deprecated)]

use surf;

use delay_timer::prelude::*;
use std::ops::Deref;
use std::ptr::NonNull;
Expand Down Expand Up @@ -84,7 +82,7 @@ fn get_increase_fn(run_flag_ref: SafePointer) -> 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 {
Expand All @@ -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}");
}
}
}
8 changes: 4 additions & 4 deletions examples/profile_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ impl RequstBody {
}
}

impl Into<CandyCronStr> for RequstBody {
fn into(self) -> CandyCronStr {
CandyCronStr(self.cron_expression)
impl From<RequstBody> 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<TaskBuilder> = Vec::with_capacity(capacity);

for _ in 0..capacity {
Expand Down
2 changes: 1 addition & 1 deletion examples/share_tokio_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Task, TaskError> {
Expand Down
2 changes: 1 addition & 1 deletion src/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
12 changes: 6 additions & 6 deletions src/timer/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)) => {
Expand Down Expand Up @@ -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)));
}
}
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions src/utils/convenience.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,9 @@ mod tests {

struct CustomizationCandyCron(i32);

impl Into<CandyCronStr> for CustomizationCandyCron {
fn into(self) -> CandyCronStr {
let s = match self.0 {
impl From<CustomizationCandyCron> 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",
_ => "* * * * * * *",
Expand Down
2 changes: 1 addition & 1 deletion src/utils/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))?;
Expand Down
2 changes: 1 addition & 1 deletion src/utils/status_report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl StatusReporter {

/// Async get `PublicEvent` via `StatusReporter`.
pub async fn next_public_event_with_async_wait(&self) -> Result<PublicEvent, channel::RecvError> {
Ok(self.inner.recv().await?)
self.inner.recv().await
}

pub(crate) fn new(inner: AsyncReceiver<PublicEvent>) -> Self {
Expand Down
2 changes: 1 addition & 1 deletion tests/simulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 69a3867

Please sign in to comment.