use std::path::{Path, PathBuf};
use crate::Result;
use crate::config::Pid;
use super::configuration;
use super::sysfs_io::{
invalid_kernel_value, read_bool, read_i32, read_usize, write_bool, write_value,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Target {
pub(super) path: PathBuf,
}
impl Target {
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn pid(&self) -> Result<Option<Pid>> {
let raw = read_i32(&self.path.join("pid_target"))?;
if raw == 0 {
return Ok(None);
}
if raw < 0 {
return Err(invalid_kernel_value(
&self.path.join("pid_target"),
raw.to_string(),
"a process ID or zero",
));
}
let raw = u32::try_from(raw).map_err(|_| {
invalid_kernel_value(
&self.path.join("pid_target"),
raw.to_string(),
"a process ID",
)
})?;
Pid::new(raw).map(Some).map_err(|_| {
invalid_kernel_value(
&self.path.join("pid_target"),
raw.to_string(),
"a process ID",
)
})
}
pub fn set_pid(&self, pid: Pid) -> Result<()> {
write_value(&self.path.join("pid_target"), pid.get())
}
pub fn clear_pid(&self) -> Result<()> {
write_value(&self.path.join("pid_target"), 0_u8)
}
pub fn is_obsolete(&self) -> Result<bool> {
read_bool(&self.path.join("obsolete_target"))
}
pub fn set_obsolete(&self, obsolete: bool) -> Result<()> {
write_bool(&self.path.join("obsolete_target"), obsolete)
}
pub fn initial_region_count(&self) -> Result<usize> {
read_usize(&self.path.join("regions/nr_regions"))
}
pub fn set_initial_region_count(&self, count: usize) -> Result<()> {
configuration::validate_count("initial region count", count)?;
write_value(&self.path.join("regions/nr_regions"), count)
}
}