microfetch/src/release.rs
NotAShelf fd18e9d244
release: conditionally improve performance for get_os_pretty_name
It is difficult to get completely accurate benchmarks, given how small
the numbers we are dealing with are, but this seems to point at an
overall trend of *slightly* faster execution. The change minimizes
unnecessary memory allocations and string manipulations, to help ensure
more performant line reading and immediate return upon finding the
PRETTY_NAME without additional, redundant operations.
2024-12-19 18:30:33 +03:00

35 lines
988 B
Rust

use color_eyre::Result;
use nix::sys::utsname::UtsName;
use std::{
fs::File,
io::{self, BufRead, BufReader},
};
pub fn get_system_info(utsname: &UtsName) -> nix::Result<String> {
Ok(format!(
"{} {} ({})",
utsname.sysname().to_str().unwrap_or("Unknown"),
utsname.release().to_str().unwrap_or("Unknown"),
utsname.machine().to_str().unwrap_or("Unknown")
))
}
pub fn get_os_pretty_name() -> Result<String, io::Error> {
let file = File::open("/etc/os-release")?;
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
if let Some(pretty_name) = line.strip_prefix("PRETTY_NAME=") {
if let Some(trimmed) = pretty_name
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
{
return Ok(trimmed.to_string());
}
return Ok(pretty_name.to_string());
}
}
Ok("Unknown".to_string())
}