From cf0a52150c29cf5f3c1b49af0b70354c6de37d6f Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Sun, 4 Aug 2024 17:20:34 +0300 Subject: [PATCH] minify and optimize uptime reader --- src/uptime.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/uptime.rs b/src/uptime.rs index 2183143..b89cb42 100644 --- a/src/uptime.rs +++ b/src/uptime.rs @@ -1,16 +1,14 @@ use std::fs::File; -use std::io::{self, BufRead}; +use std::io::{self, BufRead, BufReader}; use std::path::Path; pub fn get_current() -> Result { let path = Path::new("/proc/uptime"); let file = File::open(path)?; - let reader = io::BufReader::new(file); + let mut reader = BufReader::new(file); - let line = reader - .lines() - .next() - .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to read uptime"))??; + let mut line = String::new(); + reader.read_line(&mut line)?; let uptime_seconds: f64 = line .split_whitespace() @@ -19,7 +17,6 @@ pub fn get_current() -> Result { .parse() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - // calculate days, hours, and minutes let total_minutes = (uptime_seconds / 60.0).round() as u64; let days = total_minutes / (60 * 24); let hours = (total_minutes % (60 * 24)) / 60; @@ -29,11 +26,9 @@ pub fn get_current() -> Result { if days > 0 { parts.push(format!("{days} days")); } - if hours > 0 || days > 0 { parts.push(format!("{hours} hours")); } - if minutes > 0 || hours > 0 || days > 0 { parts.push(format!("{minutes} minutes")); }