From 44a135c1a37a12a1fcfbeafd149c0ed29beeeaf1 Mon Sep 17 00:00:00 2001 From: Asthowen Date: Mon, 5 Jan 2026 14:35:08 +0100 Subject: [PATCH] perf: apply minor optimizations --- src/config/deserialize.rs | 2 +- src/config/mod.rs | 84 +++++++++++++++++++-------------------- src/lib.rs | 2 +- src/main.rs | 37 +++++++++-------- src/system/disk.rs | 2 +- 5 files changed, 63 insertions(+), 64 deletions(-) diff --git a/src/config/deserialize.rs b/src/config/deserialize.rs index 6515726..efd0d64 100644 --- a/src/config/deserialize.rs +++ b/src/config/deserialize.rs @@ -167,7 +167,7 @@ fn color_repr_to_wrapper( }) } -impl<'de: 'static> serde::Deserialize<'de> for super::Config { +impl<'de> serde::Deserialize<'de> for super::Config<'de> { fn deserialize>(deserializer: D) -> Result { let config = ConfigWrapper::deserialize(deserializer)?; let language_func = get_language(config.language.into()); diff --git a/src/config/mod.rs b/src/config/mod.rs index 704cea7..bc9e5e7 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -25,13 +25,13 @@ const DEFAULT_IPV6_PORT: u16 = 80; const DEFAULT_IPV6_PATH: &str = "/ip"; #[derive(Debug, Decode, Encode)] -pub struct Config { +pub struct Config<'a> { pub info: HashMap>, - pub language: &'static str, - pub entries: Vec>, + pub language: &'a str, + pub entries: Vec>, pub colors: ColorOption, - pub logo: LogoStyle<'static>, - pub parameters: InfoConfig<'static>, + pub logo: LogoStyle<'a>, + pub parameters: InfoConfig<'a>, } #[derive(Debug, Default, Decode, Encode)] @@ -236,7 +236,7 @@ impl From for &str { } } -impl Default for Config { +impl Default for Config<'_> { fn default() -> Self { let entries = default_entries(Locale::default()); Self { @@ -250,7 +250,7 @@ impl Default for Config { } } -pub fn load_config() -> Config { +pub fn load_config(buffer: &mut Vec) -> Config<'_> { let cache_path = dirs::cache_dir() .map(|p| p.join("afetch.bin")) .ok_or_else(|| { @@ -261,44 +261,44 @@ pub fn load_config() -> Config { ) }) .unwrap(); - std::fs::read(&cache_path) - .ok() - .and_then(|buf| { - let buf = Box::leak(buf.into_boxed_slice()); - bitcode::decode(buf).ok() - }) - .or_else(|| { - let config_path = dirs::config_dir() - .map(|p| p.join("afetch").join("config.json")) - .ok_or_else(|| { - FetchInfoError::error_exit( - "An error occurred while retrieving the config folder, \ + + if let Ok(content) = std::fs::read(&cache_path) { + *buffer = content; + return bitcode::decode(buffer).ok().unwrap_or_default(); + } + + let config_path = dirs::config_dir() + .map(|p| p.join("afetch").join("config.json")) + .ok_or_else(|| { + FetchInfoError::error_exit( + "An error occurred while retrieving the config folder, \ please open an issue at: https://github.com/Asthowen/AFetch/issues/new \ so that we can solve your issue.", - ) - }) - .unwrap(); - - std::fs::read(config_path) - .ok() - .and_then(|buf| { - let buf = Box::leak(buf.into_boxed_slice()); - serde_json::from_slice(buf) - .inspect_err(|error| { - eprintln!( - "Warning: Your configuration is malformed ({error}). \ - Falling back to the default one.", - ); - }) - .ok() - }) - .inspect(|config| { - std::fs::create_dir_all(cache_path.parent().unwrap()) - .and_then(|()| std::fs::write(cache_path, bitcode::encode(config))) - .ok(); - }) + ) }) - .unwrap_or_default() + .unwrap(); + + if let Ok(content) = std::fs::read(&config_path) { + *buffer = content; + + let config: Config = serde_json::from_slice(buffer) + .inspect_err(|error| { + eprintln!( + "Warning: Your configuration is malformed ({error}). \ + Falling back to the default one.", + ); + }) + .ok() + .unwrap_or_default(); + + std::fs::create_dir_all(cache_path.parent().unwrap()) + .and_then(|()| std::fs::write(cache_path, bitcode::encode(&config))) + .ok(); + + return config; + } + + Config::default() } fn default_entries(locale: Locale) -> Vec> { diff --git a/src/lib.rs b/src/lib.rs index f957f71..5c96d03 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,7 +39,7 @@ clippy::if_let_mutex, clippy::imprecise_flops, clippy::mutex_integer, - clippy::string_to_string, + clippy::implicit_clone, clippy::string_add, clippy::ref_option_ref, clippy::use_self diff --git a/src/main.rs b/src/main.rs index 92f8840..2f02470 100755 --- a/src/main.rs +++ b/src/main.rs @@ -27,7 +27,8 @@ use std::fmt::Write; use supports_unicode::supports_unicode; fn main() -> Result<(), FetchInfoError> { - let config: Config = load_config(); + let mut config_buffer: Vec = Vec::new(); + let config: Config = load_config(&mut config_buffer); let language_func = get_language(config.language); let results: HashMap> = config @@ -55,17 +56,20 @@ fn main() -> Result<(), FetchInfoError> { }) .collect(); - let logo = if supports_unicode() { + let logo_buffer; + let mut logo = if supports_unicode() { match config.logo { - LogoStyle::Braille { logo } => Some(get_logo(logo.map(str::to_owned))), + LogoStyle::Braille { logo } => Some(get_logo(logo.map(str::to_owned))) + .map(|(max_length, ansi, logo)| (max_length, ansi, logo.lines())), LogoStyle::File { location: path } => { - let file_content: &str = Box::leak(std::fs::read_to_string(path)?.into_boxed_str()); - let max_length = count_str_length(file_content) + 6; - Some((max_length, 0, file_content)) + logo_buffer = Some(std::fs::read_to_string(path)?); + logo_buffer.as_deref().map(|logo| { + let max_length = count_str_length(logo) + 6; + (max_length, 0, logo.lines()) + }) } _ => None, } - .map(|(max_length, ansi, logo)| (max_length, ansi, logo.lines().collect::>())) } else { None }; @@ -105,7 +109,6 @@ fn main() -> Result<(), FetchInfoError> { let mut output: String = String::default(); let mut last_info_len = 0; - let mut i = 0; for entry in &config.entries { let mut write_entry = |entry: String| { @@ -114,11 +117,11 @@ fn main() -> Result<(), FetchInfoError> { writeln!(output, "{}{}", " ".repeat(47), entry).ok(); } - if let Some((logo_width, _, lines)) = &logo { - if lines.len() > i { - writeln!(output, " {}{} {}", lines[i], "".white(), entry).ok(); + if let Some((width, _, lines)) = logo.as_mut() { + if let Some(line) = lines.next() { + writeln!(output, " {}{} {}", line, "".white(), entry).ok(); } else { - writeln!(output, "{}{}", " ".repeat(*logo_width), entry).ok(); + writeln!(output, "{}{}", " ".repeat(*width), entry).ok(); } } @@ -126,8 +129,6 @@ fn main() -> Result<(), FetchInfoError> { if logo.is_none() { writeln!(output, "{entry}").ok(); } - - i += 1; }; match entry { @@ -208,11 +209,9 @@ fn main() -> Result<(), FetchInfoError> { } } - if let Some((_, _, lines)) = &logo - && i < lines.len() - { - for logo_line in &lines[i..] { - writeln!(output, " {}{}", logo_line, "".white()).ok(); + if let Some((_, _, lines)) = logo { + for line in lines { + writeln!(output, " {}{}", line, "".white()).ok(); } } diff --git a/src/system/disk.rs b/src/system/disk.rs index 429934a..7c2a934 100644 --- a/src/system/disk.rs +++ b/src/system/disk.rs @@ -43,7 +43,7 @@ pub fn get_disk( InfoField::DiskTotalSpace, convert_to_readable_unity(disk.total_space() as f64) ), - (InfoField::DiskMountPoint, mount_point.to_owned()), + (InfoField::DiskMountPoint, mount_point), ( InfoField::DiskFileSystem, disk.file_system().to_string_lossy().to_string()