Skip to content

Commit c59820d

Browse files
committed
uptime: Change get_uptime return to Duration
1 parent 402907e commit c59820d

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/uucore/src/lib/features/uptime.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use crate::error::{UError, UResult};
1616
use chrono::Local;
1717
use libc::time_t;
18+
use std::time::Duration;
1819
use thiserror::Error;
1920

2021
#[derive(Debug, Error)]
@@ -51,8 +52,8 @@ pub fn get_formatted_time() -> String {
5152
/// Returns a UResult with the uptime in seconds if successful, otherwise an UptimeError.
5253
#[cfg(target_os = "openbsd")]
5354
pub fn get_uptime(_boot_time: Option<time_t>) -> UResult<i64> {
54-
use libc::CLOCK_BOOTTIME;
5555
use libc::clock_gettime;
56+
use libc::CLOCK_BOOTTIME;
5657

5758
use libc::c_int;
5859
use libc::timespec;
@@ -86,10 +87,10 @@ pub fn get_uptime(_boot_time: Option<time_t>) -> UResult<i64> {
8687
///
8788
/// # Returns
8889
///
89-
/// Returns a UResult with the uptime in seconds if successful, otherwise an UptimeError.
90+
/// Returns a UResult with the uptime as a Duration if successful, otherwise an UptimeError.
9091
#[cfg(unix)]
9192
#[cfg(not(target_os = "openbsd"))]
92-
pub fn get_uptime(boot_time: Option<time_t>) -> UResult<i64> {
93+
pub fn get_uptime(boot_time: Option<time_t>) -> UResult<Duration> {
9394
use crate::utmpx::Utmpx;
9495
use libc::BOOT_TIME;
9596
use std::fs::File;
@@ -101,7 +102,8 @@ pub fn get_uptime(boot_time: Option<time_t>) -> UResult<i64> {
101102
.ok()
102103
.and_then(|mut f| f.read_to_string(&mut proc_uptime_s).ok())
103104
.and_then(|_| proc_uptime_s.split_whitespace().next())
104-
.and_then(|s| s.split('.').next().unwrap_or("0").parse::<i64>().ok());
105+
.and_then(|s| s.parse::<f64>().ok())
106+
.and_then(|f| Duration::try_from_secs_f64(f).ok());
105107

106108
if let Some(uptime) = proc_uptime {
107109
return Ok(uptime);
@@ -132,7 +134,7 @@ pub fn get_uptime(boot_time: Option<time_t>) -> UResult<i64> {
132134
if now < boottime {
133135
Err(UptimeError::BootTime)?;
134136
}
135-
return Ok(now - boottime);
137+
return Ok(Duration::from_secs(u64::try_from(now - boottime).unwrap()));
136138
}
137139

138140
Err(UptimeError::SystemUptime)?
@@ -209,7 +211,7 @@ pub fn get_nusers() -> usize {
209211
/// Returns the number of users currently logged in if successful, otherwise 0
210212
#[cfg(target_os = "openbsd")]
211213
pub fn get_nusers(file: &str) -> usize {
212-
use utmp_classic::{UtmpEntry, parse_from_path};
214+
use utmp_classic::{parse_from_path, UtmpEntry};
213215

214216
let mut nusers = 0;
215217

0 commit comments

Comments
 (0)