mirror of
https://github.com/NotAShelf/microfetch.git
synced 2025-12-08 22:13:52 +00:00
various: reduce allocations where available
Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: I517d855b14c015569a325deb64948f3b6a6a6964
This commit is contained in:
parent
325ec69024
commit
2ad765ef98
5 changed files with 125 additions and 65 deletions
|
|
@ -1,6 +1,7 @@
|
|||
use std::{
|
||||
fmt::Write as _,
|
||||
fs::File,
|
||||
io::{self, BufRead, BufReader},
|
||||
io::{self, Read},
|
||||
};
|
||||
|
||||
use nix::sys::utsname::UtsName;
|
||||
|
|
@ -8,21 +9,26 @@ use nix::sys::utsname::UtsName;
|
|||
#[must_use]
|
||||
#[cfg_attr(feature = "hotpath", hotpath::measure)]
|
||||
pub fn get_system_info(utsname: &UtsName) -> String {
|
||||
format!(
|
||||
"{} {} ({})",
|
||||
utsname.sysname().to_str().unwrap_or("Unknown"),
|
||||
utsname.release().to_str().unwrap_or("Unknown"),
|
||||
utsname.machine().to_str().unwrap_or("Unknown")
|
||||
)
|
||||
let sysname = utsname.sysname().to_str().unwrap_or("Unknown");
|
||||
let release = utsname.release().to_str().unwrap_or("Unknown");
|
||||
let machine = utsname.machine().to_str().unwrap_or("Unknown");
|
||||
|
||||
// Pre-allocate capacity: sysname + " " + release + " (" + machine + ")"
|
||||
let capacity = sysname.len() + 1 + release.len() + 2 + machine.len() + 1;
|
||||
let mut result = String::with_capacity(capacity);
|
||||
|
||||
write!(result, "{sysname} {release} ({machine})").unwrap();
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "hotpath", hotpath::measure)]
|
||||
pub fn get_os_pretty_name() -> Result<String, io::Error> {
|
||||
let file = File::open("/etc/os-release")?;
|
||||
let reader = BufReader::new(file);
|
||||
// We use a stack-allocated buffer here, which seems to perform MUCH better
|
||||
// than `BufReader`. In hindsight, I should've seen this coming.
|
||||
let mut buffer = String::with_capacity(1024);
|
||||
File::open("/etc/os-release")?.read_to_string(&mut buffer)?;
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = line?;
|
||||
for line in buffer.lines() {
|
||||
if let Some(pretty_name) = line.strip_prefix("PRETTY_NAME=") {
|
||||
if let Some(trimmed) = pretty_name
|
||||
.strip_prefix('"')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue