fix: mechanical string conversions

- &String parameters become &str (event payload fields borrow &str; wire format unchanged)
- Cow/std-string double conversions collapse to a single Into
- sha256 digests format through a shared hex lookup table instead of one
  format! allocation per byte
- i18n placeholder replacement only allocates when the placeholder exists
This commit is contained in:
Tunglies
2026-11-16 23:24:35 +08:00
parent 65042b8887
commit 13bce76c51
13 changed files with 46 additions and 33 deletions
+2 -2
View File
@@ -210,10 +210,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(())
}
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.to_owned()),
current: Some(prev_profile.into()),
items: None,
};
Config::profiles()
+2 -3
View File
@@ -1,4 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::utils::help;
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use serde::{Deserialize, Serialize};
@@ -49,9 +50,7 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
digest.update(profile_uid.as_bytes());
digest.update([0]);
digest.update(serde_json::to_vec(&canonical)?);
Ok(Some(
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
))
Ok(Some(help::hex_encode(&digest.finalize()).into()))
}
#[derive(Debug, Clone)]
+1 -1
View File
@@ -26,7 +26,7 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
}
url.host_str()?;
Some(url.to_string().into())
Some(url.as_str().into())
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
+3 -3
View File
@@ -605,7 +605,7 @@ async fn fetch_proxies_with_timeout() -> Result<Proxies> {
.map_err(Into::into)
}
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
handle::Handle::mihomo().select_node_for_group(group_name, node).await
})
@@ -809,7 +809,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
}
async fn persist_reconciled_selected(
profile_uid: &String,
profile_uid: &str,
original_selected: &[PrfSelected],
selected: Vec<PrfSelected>,
generation: u64,
@@ -818,7 +818,7 @@ async fn persist_reconciled_selected(
return Ok(());
}
let profile_uid = profile_uid.clone();
let profile_uid = String::from(profile_uid);
let original_selected = original_selected.to_vec();
persist_selected_update(false, move |mut profiles| async move {
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
+6 -3
View File
@@ -42,9 +42,12 @@ pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
}
NotificationEvent::ClashModeChanged { mode } => {
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
.replace("{mode}", mode)
.into();
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body");
let body = if body.contains("{mode}") {
body.replace("{mode}", mode).into()
} else {
body
};
notify(title, body);
}
NotificationEvent::SystemProxyToggled(enabled) => {
+5 -4
View File
@@ -1,5 +1,6 @@
use super::NoticeStatus;
use crate::{APP_HANDLE, singleton};
#[cfg(target_os = "macos")]
use smartstring::alias::String;
use std::sync::{
Arc,
@@ -55,21 +56,21 @@ impl Handle {
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
}
pub fn notify_profile_changed(profile_id: &String) {
pub fn notify_profile_changed(profile_id: &str) {
Self::send_event(FrontendEvent::ProfileChanged {
current_profile_id: profile_id,
});
}
pub fn notify_timer_updated(profile_index: &String) {
pub fn notify_timer_updated(profile_index: &str) {
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
}
pub fn notify_profile_update_started(uid: &String) {
pub fn notify_profile_update_started(uid: &str) {
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
}
pub fn notify_profile_update_completed(uid: &String) {
pub fn notify_profile_update_completed(uid: &str) {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
}
+5 -5
View File
@@ -20,16 +20,16 @@ pub enum FrontendEvent<'a> {
message: Arc<str>,
},
ProfileChanged {
current_profile_id: &'a String,
current_profile_id: &'a str,
},
TimerUpdated {
profile_index: &'a String,
profile_index: &'a str,
},
ProfileUpdateStarted {
uid: &'a String,
uid: &'a str,
},
ProfileUpdateCompleted {
uid: &'a String,
uid: &'a str,
},
RunStateChanged {
state: crate::core::runstate::RunStateView,
@@ -369,7 +369,7 @@ mod wire_tests {
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
#[cfg(test)]
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
let state = crate::core::runstate::RunState {
health: Default::default(),
pending: None,
+1 -1
View File
@@ -122,7 +122,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
digest.update(destination.as_bytes());
digest.update([0]);
digest.update(url.as_bytes());
let digest: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
let path = Path::new(destination);
let extension = path
.extension()
+1 -1
View File
@@ -458,7 +458,7 @@ impl Timer {
}
}
fn emit_update_event(uid: &String, is_start: bool) {
fn emit_update_event(uid: &str, is_start: bool) {
if is_start {
super::handle::Handle::notify_profile_update_started(uid);
} else {
+2 -2
View File
@@ -123,7 +123,7 @@ pub async fn list_wevdav_backup() -> Result<Vec<ListFile>> {
}
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
let name = filename.to_string();
let name = filename.clone();
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
logging!(
error,
@@ -165,7 +165,7 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
let backup_storage_path = app_home_dir()
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
.join(filename.as_str());
let name = filename.to_string();
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, backup_storage_path.clone())
.await
+5 -5
View File
@@ -103,7 +103,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
Ok(())
}
async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
@@ -138,8 +138,8 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &String,
url: &String,
uid: &str,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
is_mannual_trigger: bool,
@@ -234,7 +234,7 @@ async fn perform_profile_update(
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
let profile_persisted = match url_opt {
@@ -245,7 +245,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_ref() == Some(uid);
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
if should_refresh {
+10
View File
@@ -220,6 +220,16 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
})
}
pub fn hex_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
out.push(HEX[usize::from(byte >> 4)] as char);
out.push(HEX[usize::from(byte & 0x0f)] as char);
}
out
}
/// Masks query values and token-like path segments for logging.
pub fn mask_url(url: &str) -> String {
let (path_part, query_part) = match url.find('?') {
+3 -3
View File
@@ -47,7 +47,7 @@ fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String,
let name = link_parsed
.query_pairs()
.find(|(key, _)| key == "name")
.map(|(_, value)| value.into_owned().into());
.map(|(_, value)| value.into());
let url = extract_subscription_url(link_parsed)?;
Some((url, name))
}
@@ -123,7 +123,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
}
}
async fn post_import_updates(uid: &String, had_current_profile: bool) {
async fn post_import_updates(uid: &str, had_current_profile: bool) {
handle::Handle::refresh_verge();
handle::Handle::notify_profile_changed(uid);
@@ -131,7 +131,7 @@ async fn post_import_updates(uid: &String, had_current_profile: bool) {
false
} else {
let profiles = Config::profiles().await;
profiles.latest_arc().current.as_ref() == Some(uid)
profiles.latest_arc().current.as_deref() == Some(uid)
};
if should_update_core {