diff --git a/src/error.rs b/src/error.rs index 570c1b1a..4f8595e3 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,6 +6,7 @@ https://github.com/JakeRoggenbuck/auto-clock-speed/issues/new/choose"; pub enum Error { IO(std::io::Error), TimeError(std::time::SystemTimeError), + Parse, HdwNotFound, Unknown, DivisionByZero, @@ -23,6 +24,12 @@ impl From for Error { } } +impl From for Error { + fn from(_: std::num::ParseIntError) -> Self { + Error::Parse + } +} + impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Something went wrong. Try running with sudo.") diff --git a/src/power/battery.rs b/src/power/battery.rs index 4eafa59f..6ad1a940 100644 --- a/src/power/battery.rs +++ b/src/power/battery.rs @@ -86,8 +86,7 @@ impl Battery { sysfs::read( &mut self.capacity, &self.sys_parent_path.clone().join("capacity"), - ) - .unwrap(); + )?; Ok(()) } @@ -134,14 +133,12 @@ impl Battery { sysfs::read( &mut self.energy_full_design, &self.sys_parent_path.clone().join("energy_full_design"), - ) - .unwrap(); + )?; sysfs::read( &mut self.energy_full, &self.sys_parent_path.clone().join("energy_full"), - ) - .unwrap(); + )?; Ok(()) } @@ -150,14 +147,12 @@ impl Battery { sysfs::read( &mut self.charge_full_design, &self.sys_parent_path.clone().join("charge_full_design"), - ) - .unwrap(); + )?; sysfs::read( &mut self.charge_full, &self.sys_parent_path.clone().join("charge_full"), - ) - .unwrap(); + )?; Ok(()) } diff --git a/src/sysfs.rs b/src/sysfs.rs index 455b6aca..f81386ea 100644 --- a/src/sysfs.rs +++ b/src/sysfs.rs @@ -14,7 +14,7 @@ where file_content.pop(); // Convert String to expected value - *val = file_content.parse::().unwrap(); + *val = file_content.parse::().map_err(|_| Error::Unknown)?; Ok(()) } @@ -24,11 +24,13 @@ pub fn get_path_by_glob(sysfs_parent_path: &str, hdw_glob: &str) -> Result i32 { temp_max } -fn open_cpu_info() -> String { - fs::read_to_string("/proc/cpuinfo").unwrap_or_else(|_| { - panic!("Could not read /proc/cpuinfo"); - }) +fn open_cpu_info() -> Result { + Ok(fs::read_to_string("/proc/cpuinfo")?) } fn get_name_from_cpu_info(cpu_info: String) -> Result { @@ -61,7 +59,7 @@ fn get_name_from_cpu_info(cpu_info: String) -> Result { } pub fn check_cpu_name() -> Result { - let cpu_info: String = open_cpu_info(); + let cpu_info: String = open_cpu_info()?; let name: String = get_name_from_cpu_info(cpu_info)?; Ok(name) } @@ -280,9 +278,7 @@ pub fn read_int(path: &str) -> Result { // Remove trailing newline value.pop(); - Ok(value - .parse::() - .unwrap_or_else(|e| panic!("Could not parse {}\n{}", path, e))) + Ok(value.parse::()?) } pub fn read_str(path: &str) -> Result {