Skip to content

Commit 44a135c

Browse files
committed
perf: apply minor optimizations
1 parent ab39d8d commit 44a135c

5 files changed

Lines changed: 63 additions & 64 deletions

File tree

src/config/deserialize.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ fn color_repr_to_wrapper(
167167
})
168168
}
169169

170-
impl<'de: 'static> serde::Deserialize<'de> for super::Config {
170+
impl<'de> serde::Deserialize<'de> for super::Config<'de> {
171171
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
172172
let config = ConfigWrapper::deserialize(deserializer)?;
173173
let language_func = get_language(config.language.into());

src/config/mod.rs

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ const DEFAULT_IPV6_PORT: u16 = 80;
2525
const DEFAULT_IPV6_PATH: &str = "/ip";
2626

2727
#[derive(Debug, Decode, Encode)]
28-
pub struct Config {
28+
pub struct Config<'a> {
2929
pub info: HashMap<InfoKind, Vec<InfoField>>,
30-
pub language: &'static str,
31-
pub entries: Vec<Entry<'static>>,
30+
pub language: &'a str,
31+
pub entries: Vec<Entry<'a>>,
3232
pub colors: ColorOption,
33-
pub logo: LogoStyle<'static>,
34-
pub parameters: InfoConfig<'static>,
33+
pub logo: LogoStyle<'a>,
34+
pub parameters: InfoConfig<'a>,
3535
}
3636

3737
#[derive(Debug, Default, Decode, Encode)]
@@ -236,7 +236,7 @@ impl From<Locale> for &str {
236236
}
237237
}
238238

239-
impl Default for Config {
239+
impl Default for Config<'_> {
240240
fn default() -> Self {
241241
let entries = default_entries(Locale::default());
242242
Self {
@@ -250,7 +250,7 @@ impl Default for Config {
250250
}
251251
}
252252

253-
pub fn load_config() -> Config {
253+
pub fn load_config(buffer: &mut Vec<u8>) -> Config<'_> {
254254
let cache_path = dirs::cache_dir()
255255
.map(|p| p.join("afetch.bin"))
256256
.ok_or_else(|| {
@@ -261,44 +261,44 @@ pub fn load_config() -> Config {
261261
)
262262
})
263263
.unwrap();
264-
std::fs::read(&cache_path)
265-
.ok()
266-
.and_then(|buf| {
267-
let buf = Box::leak(buf.into_boxed_slice());
268-
bitcode::decode(buf).ok()
269-
})
270-
.or_else(|| {
271-
let config_path = dirs::config_dir()
272-
.map(|p| p.join("afetch").join("config.json"))
273-
.ok_or_else(|| {
274-
FetchInfoError::error_exit(
275-
"An error occurred while retrieving the config folder, \
264+
265+
if let Ok(content) = std::fs::read(&cache_path) {
266+
*buffer = content;
267+
return bitcode::decode(buffer).ok().unwrap_or_default();
268+
}
269+
270+
let config_path = dirs::config_dir()
271+
.map(|p| p.join("afetch").join("config.json"))
272+
.ok_or_else(|| {
273+
FetchInfoError::error_exit(
274+
"An error occurred while retrieving the config folder, \
276275
please open an issue at: https://github.com/Asthowen/AFetch/issues/new \
277276
so that we can solve your issue.",
278-
)
279-
})
280-
.unwrap();
281-
282-
std::fs::read(config_path)
283-
.ok()
284-
.and_then(|buf| {
285-
let buf = Box::leak(buf.into_boxed_slice());
286-
serde_json::from_slice(buf)
287-
.inspect_err(|error| {
288-
eprintln!(
289-
"Warning: Your configuration is malformed ({error}). \
290-
Falling back to the default one.",
291-
);
292-
})
293-
.ok()
294-
})
295-
.inspect(|config| {
296-
std::fs::create_dir_all(cache_path.parent().unwrap())
297-
.and_then(|()| std::fs::write(cache_path, bitcode::encode(config)))
298-
.ok();
299-
})
277+
)
300278
})
301-
.unwrap_or_default()
279+
.unwrap();
280+
281+
if let Ok(content) = std::fs::read(&config_path) {
282+
*buffer = content;
283+
284+
let config: Config = serde_json::from_slice(buffer)
285+
.inspect_err(|error| {
286+
eprintln!(
287+
"Warning: Your configuration is malformed ({error}). \
288+
Falling back to the default one.",
289+
);
290+
})
291+
.ok()
292+
.unwrap_or_default();
293+
294+
std::fs::create_dir_all(cache_path.parent().unwrap())
295+
.and_then(|()| std::fs::write(cache_path, bitcode::encode(&config)))
296+
.ok();
297+
298+
return config;
299+
}
300+
301+
Config::default()
302302
}
303303

304304
fn default_entries(locale: Locale) -> Vec<Entry<'static>> {

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
clippy::if_let_mutex,
4040
clippy::imprecise_flops,
4141
clippy::mutex_integer,
42-
clippy::string_to_string,
42+
clippy::implicit_clone,
4343
clippy::string_add,
4444
clippy::ref_option_ref,
4545
clippy::use_self

src/main.rs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ use std::fmt::Write;
2727
use supports_unicode::supports_unicode;
2828

2929
fn main() -> Result<(), FetchInfoError> {
30-
let config: Config = load_config();
30+
let mut config_buffer: Vec<u8> = Vec::new();
31+
let config: Config = load_config(&mut config_buffer);
3132
let language_func = get_language(config.language);
3233

3334
let results: HashMap<InfoKind, Result<InfoResult, FetchInfoError>> = config
@@ -55,17 +56,20 @@ fn main() -> Result<(), FetchInfoError> {
5556
})
5657
.collect();
5758

58-
let logo = if supports_unicode() {
59+
let logo_buffer;
60+
let mut logo = if supports_unicode() {
5961
match config.logo {
60-
LogoStyle::Braille { logo } => Some(get_logo(logo.map(str::to_owned))),
62+
LogoStyle::Braille { logo } => Some(get_logo(logo.map(str::to_owned)))
63+
.map(|(max_length, ansi, logo)| (max_length, ansi, logo.lines())),
6164
LogoStyle::File { location: path } => {
62-
let file_content: &str = Box::leak(std::fs::read_to_string(path)?.into_boxed_str());
63-
let max_length = count_str_length(file_content) + 6;
64-
Some((max_length, 0, file_content))
65+
logo_buffer = Some(std::fs::read_to_string(path)?);
66+
logo_buffer.as_deref().map(|logo| {
67+
let max_length = count_str_length(logo) + 6;
68+
(max_length, 0, logo.lines())
69+
})
6570
}
6671
_ => None,
6772
}
68-
.map(|(max_length, ansi, logo)| (max_length, ansi, logo.lines().collect::<Vec<&str>>()))
6973
} else {
7074
None
7175
};
@@ -105,7 +109,6 @@ fn main() -> Result<(), FetchInfoError> {
105109

106110
let mut output: String = String::default();
107111
let mut last_info_len = 0;
108-
let mut i = 0;
109112

110113
for entry in &config.entries {
111114
let mut write_entry = |entry: String| {
@@ -114,20 +117,18 @@ fn main() -> Result<(), FetchInfoError> {
114117
writeln!(output, "{}{}", " ".repeat(47), entry).ok();
115118
}
116119

117-
if let Some((logo_width, _, lines)) = &logo {
118-
if lines.len() > i {
119-
writeln!(output, " {}{} {}", lines[i], "".white(), entry).ok();
120+
if let Some((width, _, lines)) = logo.as_mut() {
121+
if let Some(line) = lines.next() {
122+
writeln!(output, " {}{} {}", line, "".white(), entry).ok();
120123
} else {
121-
writeln!(output, "{}{}", " ".repeat(*logo_width), entry).ok();
124+
writeln!(output, "{}{}", " ".repeat(*width), entry).ok();
122125
}
123126
}
124127

125128
#[cfg(not(feature = "image"))]
126129
if logo.is_none() {
127130
writeln!(output, "{entry}").ok();
128131
}
129-
130-
i += 1;
131132
};
132133

133134
match entry {
@@ -208,11 +209,9 @@ fn main() -> Result<(), FetchInfoError> {
208209
}
209210
}
210211

211-
if let Some((_, _, lines)) = &logo
212-
&& i < lines.len()
213-
{
214-
for logo_line in &lines[i..] {
215-
writeln!(output, " {}{}", logo_line, "".white()).ok();
212+
if let Some((_, _, lines)) = logo {
213+
for line in lines {
214+
writeln!(output, " {}{}", line, "".white()).ok();
216215
}
217216
}
218217

src/system/disk.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub fn get_disk(
4343
InfoField::DiskTotalSpace,
4444
convert_to_readable_unity(disk.total_space() as f64)
4545
),
46-
(InfoField::DiskMountPoint, mount_point.to_owned()),
46+
(InfoField::DiskMountPoint, mount_point),
4747
(
4848
InfoField::DiskFileSystem,
4949
disk.file_system().to_string_lossy().to_string()

0 commit comments

Comments
 (0)