amdgpu_sysfs/
sysfs.rs

1//! Utilities for working with SysFS.
2use crate::{
3    error::{Error, ErrorContext},
4    Result,
5};
6use std::{fmt::Debug, fs, path::Path, str::FromStr};
7
8/// General functionality of a SysFS.
9pub trait SysFS {
10    /// Gets the path of the current SysFS.
11    fn get_path(&self) -> &Path;
12
13    /// Reads the content of a file in the `SysFS`.
14    fn read_file(&self, file: impl AsRef<Path> + Debug) -> Result<String> {
15        let path = file.as_ref();
16        Ok(fs::read_to_string(self.get_path().join(path))
17            .with_context(|| format!("Could not read file {file:?}"))?
18            .replace(char::from(0), "") // Workaround for random null bytes in SysFS entries
19            .trim()
20            .to_owned())
21    }
22
23    /// Reads the content of a file and then parses it
24    fn read_file_parsed<T: FromStr<Err = E>, E: ToString>(&self, file: &str) -> Result<T> {
25        fs::read_to_string(self.get_path().join(file))
26            .with_context(|| format!("Could not read file {file}"))?
27            .trim()
28            .parse()
29            .map_err(|err: E| Error::basic_parse_error(err.to_string()))
30    }
31
32    /// Write to a file in the `SysFS`.
33    fn write_file<C: AsRef<[u8]> + Send>(&self, file: &str, contents: C) -> Result<()> {
34        Ok(fs::write(self.get_path().join(file), contents)?)
35    }
36}