use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use super::{Devices, GpuInner};
pub(super) fn read_file<P: AsRef<Path>>(path: P, buffer: &mut String) -> io::Result<usize> {
buffer.clear();
let mut f = File::open(path)?;
f.read_to_string(buffer)
}
pub(super) struct CustomBufReader<'a> {
buffer: &'a mut String,
reader: BufReader<File>,
}
impl<'a> CustomBufReader<'a> {
pub(super) fn next_line(&mut self) -> Option<&str> {
loop {
self.buffer.clear();
if self.reader.read_line(self.buffer).ok()? == 0 {
return None;
} else if self.buffer.starts_with("C ") {
return None;
} else if !self.buffer.starts_with('#') {
return Some(self.buffer.as_str());
}
}
}
}
pub(super) fn find_first_vendor(reader: &mut CustomBufReader<'_>) -> Option<(u32, Devices)> {
while let Some(line) = reader.next_line() {
if line.starts_with('\t') {
continue;
}
if let Some((id, vendor_name)) = get_id_and_name(line) {
return Some((id, Devices::new(vendor_name)));
}
}
None
}
pub(super) fn get_id_and_name(line: &str) -> Option<(u32, &str)> {
let (id, name) = line.split_once(' ')?;
let id = u32::from_str_radix(id, 16).ok()?;
Some((id, name.trim()))
}
pub(super) fn fill_device_map(device_map: &mut HashMap<u32, Devices>, buffer: &mut String) {
let Ok(f) = File::open("/usr/share/hwdata/pci.ids") else {
return;
};
let mut reader = CustomBufReader {
buffer,
reader: BufReader::new(f),
};
let Some((mut vendor_id, mut devices)) = find_first_vendor(&mut reader) else {
return;
};
while let Some(line) = reader.next_line() {
match line.strip_prefix('\t') {
None => {
if let Some((id, vendor_name)) = get_id_and_name(line) {
device_map.insert(vendor_id, devices);
vendor_id = id;
devices = Devices::new(vendor_name);
}
}
Some(line) => {
if !line.starts_with('\t')
&& let Some((id, model_name)) = get_id_and_name(line)
{
devices.devices.insert(id, model_name.to_owned());
}
}
}
}
}
pub(super) fn get_amd_info(gpu: &mut GpuInner, buffer: &mut String, path: &Path) {
if read_file(path.join("gpu_busy_percent"), buffer).is_ok() {
gpu.usage = buffer.trim().parse::<f32>().ok();
}
if read_file(path.join("mem_info_vram_used"), buffer).is_ok() {
gpu.used_memory = buffer.trim().parse::<u64>().ok();
}
if read_file(path.join("mem_info_vram_total"), buffer).is_ok() {
gpu.total_memory = buffer.trim().parse::<u64>().ok();
}
gpu.updated = true;
}
pub(super) fn convert_to_string(data: &[libc::c_char]) -> Option<String> {
data.split(|c| *c == 0).next().map(|s| unsafe {
let s: &[u8] = std::slice::from_raw_parts(s.as_ptr() as *const u8, s.len());
String::from_utf8_lossy(s).into_owned()
})
}
pub(super) fn convert_to_str(data: &[libc::c_char]) -> Option<Cow<'_, str>> {
data.split(|c| *c == 0).next().map(|s| unsafe {
let s: &[u8] = std::slice::from_raw_parts(s.as_ptr() as *const u8, s.len());
String::from_utf8_lossy(s)
})
}