mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 17:15:38 +08:00
refactor: replace unwrap_or with unwrap_or_else for improved error handling (#5163)
In Rust, the `or` and `or_else` methods have distinct behavioral differences. The `or` method always eagerly evaluates its argument and executes any associated function calls. This can lead to unnecessary performance costs—especially in expensive operations like string processing or file handling—and may even trigger unintended side effects. In contrast, `or_else` evaluates its closure lazily, only when necessary. Introducing a Clippy lint to disallow `or` sacrifices a bit of code simplicity but ensures predictable behavior and enforces lazy evaluation for better performance.
This commit is contained in:
@@ -155,9 +155,9 @@ pub async fn delete_log() -> Result<()> {
|
||||
let month = u32::from_str(sa[1])?;
|
||||
let day = u32::from_str(sa[2])?;
|
||||
let time = chrono::NaiveDate::from_ymd_opt(year, month, day)
|
||||
.ok_or(anyhow::anyhow!("invalid time str"))?
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid time str"))?
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.ok_or(anyhow::anyhow!("invalid time str"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid time str"))?;
|
||||
Ok(time)
|
||||
};
|
||||
|
||||
@@ -171,7 +171,7 @@ pub async fn delete_log() -> Result<()> {
|
||||
let file_time = Local
|
||||
.from_local_datetime(&created_time)
|
||||
.single()
|
||||
.ok_or(anyhow::anyhow!("invalid local datetime"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid local datetime"))?;
|
||||
|
||||
let duration = now.signed_duration_since(file_time);
|
||||
if duration.num_days() > day {
|
||||
@@ -523,7 +523,7 @@ pub async fn startup_script() -> Result<()> {
|
||||
let script_path = {
|
||||
let verge = Config::verge().await;
|
||||
let verge = verge.latest_ref();
|
||||
verge.startup_script.clone().unwrap_or("".into())
|
||||
verge.startup_script.clone().unwrap_or_else(|| "".into())
|
||||
};
|
||||
|
||||
if script_path.is_empty() {
|
||||
@@ -547,7 +547,7 @@ pub async fn startup_script() -> Result<()> {
|
||||
}
|
||||
|
||||
let parent_dir = script_dir.parent();
|
||||
let working_dir = parent_dir.unwrap_or(script_dir.as_ref());
|
||||
let working_dir = parent_dir.unwrap_or_else(|| script_dir.as_ref());
|
||||
|
||||
app_handle
|
||||
.shell()
|
||||
|
||||
Reference in New Issue
Block a user